phone

    • chevron_right

      Erlang Solutions: Here’s Why You Should Build Scalable Systems with Erlang

      news.movim.eu / PlanetJabber • 16 March, 2023 • 5 minutes

    Building systems in the earlier days of the internet used to be pretty simple.

    While the system was admittedly pretty limited, the demand to scale past one or two servers wasn’t particularly high. But upon entering the 21st century, we saw large companies (think Amazon, Starbucks, Yahoo) and many more find the need to scale not just a few servers, but thousands. Even tens of thousands. Suddenly, the old-school system was impractical and nearly impossible to scale past one of two servers.

    The need for a system that offers scalability, flexibility and resilience had arrived. Enter Erlang- the powerful programming language designed for building highly scalable, fault-tolerant systems.

    Wondering what benefits there are to a scalable system like Erlang? Keep reading. We’ll be breaking down those very basics in this blog.

    A bit of background on Erlang

    But first, a bit of history of the Erlang language.

    Erlang was developed in the 1980s by Ericsson. Since then, it has been used to build large-scale distributed systems, such as telecom switching systems, online gaming platforms, and social networking sites.

    So, what is a scalable system?

    Before we start discussing scalable systems , let’s see what is really meant by the term ‘scaleable’.

    Measuring scalability is the ability to measure a system’s ability to increase or decrease in cost and performance, in response to the changes in a system’s demands.

    Now, it may seem obvious that an application being used by one user would require different levels of technology than one being used by a hundred. Yet, the reality is that there are still many businesses using technology that does not allow for this flexibility. This often leads to companies having to invest more money in creating software from scratch whenever they grow.

    As digital transformation drives accelerated business growth, businesses of all sizes need to be able to scale operations and adapt to their rapidly changing environments quickly. It’s no surprise that scalability has become an increasingly important factor when dealing with developing applications. Businesses have no choice but to be scalable, or they will face becoming overwhelmed when usage increases and will eventually become unable to meet the demands of a growing user base.

    A scalable computer language such as Erlang can write large new programmes and extend large existing ones relatively pain-free, depending on the complexity of the size of the programme it is trying to manage.

    Concurrency and parallelism in Erlang

    Erlang does a lot of things differently, one of those things being concurrency. When compared to most other programming languages that treat concurrency as an afterthought, Erlang builds in concurrency from the very base of the system.

    It was designed from the ground up to support concurrency and parallelism.

    Illustrating concurrency and parallelism on a 2-core CPU. Source: OpenClassrooms 2020. https://devopedia.org/concurrency-vs-parallelism

    Erlang’s lightweight processes, also known as actors, can execute in parallel, and they communicate with each other by exchanging messages. This message-passing model makes it easy to build highly concurrent systems that can handle a large number of users.

    Fault tolerance (Let it Crash)

    The philosophy behind Erlang is simply ‘Let it Crash.’

    Sound odd, right? Actually, letting it crash isn’t about crashing for the user or system.

    It’s about containing failure and letting Erlang clean it up.

    It knows that errors will happen, and things will break.

    Instead of trying to simply guard against those errors, Erlang has a built-in mechanism to handle those errors and failures.

    These mechanisms allow guarding against errors. So when a process crashes, it can restart automatically. In turn, the system restarts quickly and continues to operate smoothly.

    OTP

    The Open Telecom Platform (OTP) is a set of tools, frameworks and principles that are designed to guide and support the deployment of Erlang systems.

    OTP includes a wide range of components, such as a supervision tree, process registry, and message queues, which can be used to build complex distributed systems.

    Supervision tree example https://www.erlang.org/doc/design_principles/des_princ.htm

    Focusing on the supervision tree is a key hierarchical structuring model that is based on the idea of workers and supervisors, which makes it possible to design and programme fault-tolerant software.

    The workers are processes that perform computations meaning, they do the actual work. And supervisors are processes that monitor the behaviour of those workers. A supervisor can restart a worker if something goes wrong.

    Using OTP in your projects will help you to avoid accidental complexity.

    Distributed systems

    Erlang was designed for building distributed systems. It has built-in support for building systems that span multiple nodes. Erlang’s distribution mechanism allows processes to communicate with each other across the network, making it simple to build systems that scale horizontally.

    Erlang is high- performance

    Erlang is an incredibly high-performing language that can handle a large number of concurrent users and has great resilience over high task loads.

    Well known for its low latency, it is well-suited for building systems that require real-time processing and also has a small memory footprint, which enables it to run efficiently on low-end hardware.

    Hot Code Loading

    Erlang has a unique feature known as hot code loading, which enables developers to update their systems without shutting them down.

    Another way to think of it is that Hot Code Loading is the art of replacing an engine from a running car, without ever having to stop the car itself. It can update the code without causing any disruption to the service, meaning zero impact on users.

    This feature is particularly useful for building systems that need to be available 24/7.

    Scalability

    Last but not least, Erlang’s scalability is next to none. This language can be used to build systems that can handle millions of users. Erlang’s concurrency model and distributed architecture make it easy to build systems that can scale horizontally across multiple nodes, allowing developers to handle increasing loads, without sacrificing performance.

    To conclude

    Overall, Erlang is a great choice for building large-scale distributed systems that need to be highly available and performant. It handles concurrency and all its complexities with robustness and ease. But don’t just take our word for it. There are thousands of companies across the globe that have enlisted Erlang beyond its early days in telecoms.

    But don’t just take our word for it. Here are some of the clients who have felt the real-life impact of Erlang on their businesses .

    Fancy finding more out about Erlang? Check out our page .

    The post Here’s Why You Should Build Scalable Systems with Erlang appeared first on Erlang Solutions .

    • wifi_tethering open_in_new

      This post is public

      www.erlang-solutions.com /blog/heres-why-you-should-build-scalable-systems-with-erlang/

    • chevron_right

      Ignite Realtime Blog: Developing Openfire Efficient XML Interchange (EXI) functionality

      news.movim.eu / PlanetJabber • 14 March, 2023 • 1 minute

    We am excited to announce that a new plugin for the Openfire real time collaboration server is in the works! This plugin implements Efficient XML Interchange (EXI) functionality and provides an XMPP implementation of EXI as defined in XEP-0322 .

    Efficient XML Interchange (EXI) is a binary XML format for exchange of data on a computer network. It is one of the most prominent efforts to encode XML documents in a binary data format, rather than plain text. Using EXI format reduces the verbosity of XML documents as well as the cost of parsing.

    EXI is useful for:

    • a complete range of XML document sizes, from dozens of bytes to terabytes
    • reducing computational overhead to speed up parsing of compressed documents
    • increasing endurance of small devices by utilizing efficient decompression

    Read more about EXI in its Wikipedia article (where the above definition was taken from).

    The plugin that we’re developing today was first created by Javier Placencio, in 2013 and 2014. In 2023, that now dormant project was forked by the Ignite Realtime community.

    Work on the plugin is progressing steadily. Most of the core functionality is believed to be ready. In preparation for the official release of the plugin, we are looking for opportunities to perform interoperability testing. So far, testing has been done with our own mock client implementations. To be able to release a fully functional plugin, we’d like to test against implementations of other authors. Development builds of the plugin can be downloaded from the Openfire EXI plugin archive page .

    Are you interested in this? Please reach out to us on the Ignite Realtime Community , or stop by the open chat ! We would love to hear from you!

    For other release announcements and news follow us on Twitter and Mastodon .

    1 post - 1 participant

    Read full topic

    • wifi_tethering open_in_new

      This post is public

      discourse.igniterealtime.org /t/developing-openfire-efficient-xml-interchange-exi-functionality/92663

    • chevron_right

      Erlang Solutions: Presentamos el soporte de transmisión en RabbitMQ

      news.movim.eu / PlanetJabber • 13 March, 2023 • 11 minutes

    ¿Quiere saber más sobre el soporte de transmisión en RabbitMQ? Arnaud Cogoluègnes, ingeniero de personal de VMware, desglosa todo lo que hay que saber en la Cumbre RabbitMQ de 2021.

    En julio de 2021, se introdujeron streams a RabbitMQ, utilizando un nuevo protocolo extremadamente rápido que se puede utilizar junto con AMQP 0.9.1. Los streams ofrecen una forma más fácil de resolver varios problemas en RabbitMQ, incluyendo grandes fan-outs, replay y time travel, y grandes logs, todo con un rendimiento muy alto (1 millón de mensajes por segundo en un clúster de 3 nodos). Arnaud Cogoluègnes , Ingeniero de Staff en VMware , presentó los streams y cómo se utilizan mejor.

    Esta charla fue grabada en el RabbitMQ Summit 2021. La 4ta edición del RabbitMQ Summit se llevará a cabo como un evento híbrido, tanto en persona (en el lugar CodeNode en Londres) como virtual, el 16 de septiembre de 2022 y reunirá a algunas de las mayores empresas del mundo que utilizan RabbitMQ, todas en un solo lugar.

    Streams: Un Nuevo Tipo de Estructura de Datos en RabbitMQ

    Streams son una nueva estructura de datos en RabbitMQ que abren un mundo de posibilidades para nuevos casos de uso. Modelan un registro de solo agregado, lo que representa un gran cambio respecto a las colas tradicionales de RabbitMQ, ya que tienen semántica de consumidor no destructiva. Esto significa que cuando se leen mensajes de un Stream, no se eliminan, mientras que en las colas, cuando se lee un mensaje de una cola, se destruye. Este comportamiento reutilizable de RabbitMQ Streams se facilita mediante la estructura de registro de solo agregado.

    Text from the image:(Streams: a un nuevo tipo de estructura de datos en RabbitMQ)
    (Modela registros de solo anexar) (Persistente y replicado)(semántica de cliente no destructiva)(AMQP 0.9.1 y protocolo nuevo)

    RabbitMQ también introdujo un nuevo protocolo, el protocolo Stream, que permite un flujo de mensajes mucho más rápido. Sin embargo, también puedes acceder a Streams a través del protocolo AMQP 0.9.1 tradicional, que sigue siendo el protocolo más utilizado en RabbitMQ. También son accesibles a través de otros protocolos que RabbitMQ soporta, como MQTT y STOMP.

    Fortalezas de Streams

    Los Streams tienen fortalezas únicas que les permiten destacar en algunos casos de uso. Estas incluyen:

    Difusión masiva

    Cuando tienes varias aplicaciones en tu sistema que necesitan leer los mismos mensajes, tienes una arquitectura de difusión masiva. Los Streams son excelentes para las difusiones masivas, gracias a sus semánticas de consumo no destructivas, eliminando la necesidad de copiar el mensaje dentro de RabbitMQ tantas veces como haya consumidores.

    Reproducción y viaje en el tiempo

    Los Streams también ofrecen capacidades de reproducción y viaje en el tiempo. Los consumidores pueden adjuntarse en cualquier lugar de un Stream, utilizando un desplazamiento absoluto o una marca de tiempo, y pueden leer y volver a leer los mismos datos tantas veces como sea necesario.

    Rendimiento

    Gracias al nuevo protocolo de stream, los streams tienen el potencial de ser significativamente más rápidos que las colas tradicionales. Si necesitas un alto rendimiento o estás trabajando con mensajes grandes, los streams a menudo pueden ser una opción adecuada.

    Mensajes grandes

    Los Streams también son buenos para grandes registros. Los mensajes en los streams siempre son persistentes en el sistema de archivos, y los mensajes no permanecen en la memoria por mucho tiempo. Al consumirse, se utiliza la caché de archivos del sistema operativo para permitir un flujo de mensajes rápido.

    RabbitMQ also introduced a new protocol, the Stream protocol, which allows much faster message flow, however, you can access Streams through the traditional AMQP 0.9.1 protocol as well, which remains the most used protocol in RabbitMQ. They are also accessible through the other protocols that RabbitMQ supports, such as MQTT and STOMP.

    Text from the image:(Grandes fan-outs) (Repetición/tiempo de viaje)(Alto rendimiento)(Grandes registros)

    La Abstracción del Log

    Un stream es inmutable, puedes añadir mensajes, pero una vez que un mensaje ha entrado en el stream, no se puede eliminar. Esto hace que la abstracción del log del stream sea una estructura de datos bastante simple en comparación con las colas donde los mensajes siempre se añaden y se eliminan. Esto nos lleva a otro concepto importante, el offset. El offset es simplemente un índice técnico de un mensaje dentro del stream, o una marca de tiempo. Los consumidores pueden indicar a RabbitMQ que empiece a leer desde un offset en lugar del principio del stream. Esto permite una fácil reproducción y viaje en el tiempo de los mensajes. Los consumidores también pueden delegar la responsabilidad de seguimiento del offset a RabbitMQ.

    Text from the image:
    (La abstracción de registros)
    (Un modelo de secuencias y un registro de solo anexar)

    (Estructura de datos FIFO)
    (Lectura no destructiva)

    (Mensaje más viejo) (Compensar)(Último mensaje)(Proximo mensaje iría aquí en su lugar)

    Podemos tener cualquier cantidad de consumidores en un stream, no compiten entre sí, una aplicación consumidora no robará mensajes de otras aplicaciones, y la misma aplicación puede leer el flujo de mensajes muchas veces.

    Las colas pueden almacenar mensajes en memoria o en disco, pueden estar en un solo nodo o estar replicadas, los streams son persistentes y replicados en todo momento. Cuando creamos un stream, tendrá un líder ubicado en un nodo y réplicas en otros nodos. Las réplicas seguirán al líder y sincronizarán los datos. El líder es el único que puede crear operaciones de escritura y las réplicas solo se utilizarán para servir a los consumidores.

    Colas de RabbitMQ vs. Streams

    Los streams están aquí para complementar las colas y ampliar los casos de uso de RabbitMQ. Las colas tradicionales siguen siendo la mejor herramienta para los casos de uso más comunes en RabbitMQ, pero tienen sus limitaciones, hay momentos en los que no son la mejor opción.

    Los streams son, al igual que las colas, una estructura de datos FIFO, es decir, el mensaje más antiguo publicado se leerá primero. Proporcionar un desplazamiento permite al cliente omitir el comienzo del flujo, pero los mensajes se leerán en el orden de publicación.

    En RabbitMQ, tiene una cola tradicional con un par de mensajes y una aplicación consumidora. Después de registrar el consumidor, el intermediario comenzará a despachar mensajes al cliente y la aplicación puede comenzar a procesarlos.

    Cuando, en este punto, el mensaje está en un punto importante de su vida útil, está presente en el lado del remitente y también en el lado del consumidor. El intermediario todavía necesita preocuparse por el mensaje porque puede ser rechazado y debe saber que aún no se ha reconocido. Después de que la aplicación termine de procesar el mensaje, puede reconocerlo y, a partir de este momento, el intermediario puede deshacerse del mensaje y considerarlo procesado. Esto es lo que podemos llamar consumo destructivo, y es el comportamiento de las colas clásicas y de cuórum. Al usar Streams, el mensaje permanece en el Stream mientras la política de retención lo permita.

    Implementar configuraciones de gran difusión masiva con RabbitMQ no era óptimo antes de Streams. Cuando entra un mensaje, va a un intercambio y se enruta a una cola. Si desea que otra aplicación procese los mensajes, debe crear una nueva cola, vincular la cola al intercambio y comenzar a consumir. Este proceso crea una copia del mensaje para cada aplicación, y si necesita que otra aplicación procese los mismos mensajes, debe repetir el proceso; entonces otra cola, un nuevo enlace, un nuevo consumidor y una nueva copia del mensaje.

    Este método funciona y se ha utilizado durante años, pero no escala de manera elegante cuando se tienen muchas aplicaciones consumidoras. Los streams proporcionan una mejor manera de implementar esto, ya que los mensajes pueden ser leídos por cada consumidor por separado, en orden, desde el Stream.

    Rendimiento de los streams de RabbitMQ usando AMQP y el protocolo de Stream

    Como se explica en la charla, hubo un mayor rendimiento con Streams en comparación con las colas de cuórum.

    Obtuvieron alrededor de 40,000 mensajes por segundo con las Colas Quórum y 64,000 mensajes por segundo con Streams. Esto se debe a que Streams son una estructura de datos más simple que las Colas Quórum, ya que no tienen que lidiar con cosas complicadas como la confirmación de mensajes, mensajes rechazados o reencolado.

    Text from the image:
    (Streams en AMQP)
    (Cluster de 3 nodos (instancias c2-standard-16))
    (Tarifas de publicación)
    (mensajes/segundos)

    (Colas Quorum)(Stream en AMQP)

    Las colas de Quorum siguen siendo colas replicadas y persistentes de vanguardia, mientras que las Streams son para otros casos de uso. Al usar el protocolo Stream dedicado, se pueden lograr tasas de transferencia de un millón de mensajes por segundo.

    Text from the image: (Protocolo Stream)
    (Cluster de 3 nodos (instancias c2-standard-16))
    (Tarifas de publicación)
    (mensajes/segundos)
    (Colas Quorum)
    (Stream en AMQP)
    (Stream con protocolo de stream)

    El Protocolo Stream ha sido diseñado teniendo en cuenta el rendimiento y utiliza técnicas de bajo nivel como la API libC sendfile, la caché de página del sistema operativo y el agrupamiento, lo que lo hace más rápido que las colas AMQP.

    El plugin RabbitMQ Stream y los clientes

    Los Streams están disponibles a través de un nuevo plugin en la distribución principal. Cuando está activado, RabbitMQ comenzará a escuchar en un nuevo puerto que puede ser utilizado por los clientes que comprenden el Protocolo Stream. Está integrado con la infraestructura existente en RabbitMQ, como la interfaz de gestión, la API REST y Prometheus.

    Text from the image: (Los Streams son también accesibles a través de un nuevo protocolo)
    (Rápido) (Complemento en la distribución principal)(integración de gestión)

    Hay un cliente dedicado en Java y Go que utiliza este nuevo protocolo de flujo. El cliente de Java es la implementación de referencia. También está disponible una herramienta de prueba de rendimiento. Los clientes para otros lenguajes también son desarrollados activamente por la comunidad y el equipo central.

    El protocolo de flujo es un poco más simple que AMQP; no hay enrutamiento; simplemente se publica en un flujo, no hay intercambio involucrado, y se consume de un flujo como de una cola. No se necesita lógica para decidir dónde se debe dirigir el mensaje. Cuando publicas un mensaje desde tus aplicaciones cliente, este va a la red y casi directamente al almacenamiento.

    Existe una excelente interoperabilidad entre los flujos y el resto de RabbitMQ. Los mensajes se pueden consumir desde una aplicación cliente AMQP 0.9.1 y también funciona en sentido contrario.

    Ejemplo de caso de uso para interoperabilidad:

    Las colas y los flujos viven en el mismo espacio de nombres en RabbitMQ, por lo que se puede especificar el nombre del flujo del que se desea consumir utilizando los clientes AMQP habituales y mediante el parámetro x-stream-offset para basicConsume.

    Es muy fácil publicar con clientes AMQP porque es lo mismo que con las colas, se publica en un intercambio.

    Text from the image: (Agregar Stream para Analiticas)
    (Editor)(Cola) (Procesando AMER)
    (Editor)(Cola) (Procesando EMEA)
    (Editor)(Cola) (Procesando APAC)
    (Cola) (Analiticas globales)
    ((Posibilidad) editores multiprotocolos)

    Arriba se muestra un ejemplo de cómo se puede imaginar el uso de streams. Se tiene un publicador que publica mensajes en un exchange y, según la clave de enrutamiento de los mensajes, se enrutan a diferentes colas. Por lo tanto, se tiene una cola para cada región del mundo. Por ejemplo, se tiene una cola para las Américas, una para Europa, una para Asia y una para la sede. Se tiene una aplicación consumidora dedicada que realizará un procesamiento específico para cada región.

    Si se actualiza a RabbitMQ 3.9 o posterior, se puede simplemente crear un stream, vincularlo al exchange con un comodín para que todos los mensajes se enruten a las colas pero el stream reciba todos los mensajes. Luego se puede dirigir una aplicación que utiliza el Protocolo Stream a este stream y podemos imaginar que esta aplicación realizará análisis mundiales todos los días sin siquiera leer el stream muy rápido. Así es como podemos imaginar que los streams se ajustan a las aplicaciones existentes.

    Garantías para RabbitMQ Streams

    Los streams admiten entrega al menos una vez, ya que admiten un mecanismo similar a AMQP Publish Confirms. También hay un mecanismo de deduplicación, el agente filtra los mensajes duplicados según el número de secuencia de publicación, como una clave en una base de datos o un número de línea en un archivo.

    Text from the image: (Garantías)                              (Mensajes de deduplicación)                (Control de flujo)
    (Al menos uno)                        (publicando)
    (Sin pérdida de mensajes)

    En ambos lados, tenemos control de flujo, por lo que se bloquearán las conexiones TCP de los editores rápidos. El corredor solo enviará mensajes al cliente cuando esté listo para aceptarlos.

    Resumen

    Text from the image: (Streams: una nueva estructura de tipo de registro replicada y persistente en RabbitMQ)
    (Desbloquear los nuevos escenarios con RabbitMQ)
    (Grandes fan-outs) (Repetición/tiempo de viaje)(Alto rendimiento)(Grandes registros)

    (Pruebalo)

    Los Streams son una nueva estructura de datos replicada y persistente en RabbitMQ, que modelan un registro de solo anexión. Son buenos para distribución masiva, soportan funciones de reproducción y viaje en el tiempo, son adecuados para escenarios de alto rendimiento y para grandes registros. Almacenan sus datos en el sistema de archivos y nunca en memoria.

    Si crees que los Streams o RabbitMQ podrían ser útiles para ti pero no sabes por dónde empezar, habla con nuestros expertos , siempre estamos dispuestos a ayudar. Si quieres ver las últimas características y estudios de casos del mundo de RabbitMQ, únete a nosotros en RabbitMQ Summit 2022.

    The post Presentamos el soporte de transmisión en RabbitMQ appeared first on Erlang Solutions .

    • wifi_tethering open_in_new

      This post is public

      www.erlang-solutions.com /blog/presentamos-el-soporte-de-transmision-en-rabbitmq/

    • chevron_right

      Ignite Realtime Blog: Botz version 1.2.0 release

      news.movim.eu / PlanetJabber • 9 March, 2023

    We have just released version 1.2.0 of the Botz framework for Openfire!

    The Botz library adds to the already rich and extensible Openfire with the ability to create internal user bots.

    In this release, a bug that prevented client sessions for bots from being created was fixed. Hat-tip to
    Kris Iyer for working with us on a fix!

    Download the latest version of the Botz framework from its project page !

    For other release announcements and news follow us on Twitter and Mastodon .

    1 post - 1 participant

    Read full topic

    • chevron_right

      Erlang Solutions: Creating a simple weather application with Phoenix LiveView

      news.movim.eu / PlanetJabber • 9 March, 2023 • 7 minutes

    Introduction

    In this article we will discuss our experience building an online weather application in Elixir using Phoenix LiveView. We created a real-time weather application that allows users to see the past, current, and forecast temperature and precipitation data for any UK postcode. The goals of building this app were:

    • to further familiarise ourselves with Phoenix LiveView
    • to investigate some of the libraries available for displaying graphs in LiveView

    Our reason for displaying both temperature and precipitation data simultaneously was to test the capabilities of the libraries in question, as some rather complex graph configurations are required to display two lines on one y-axis (minimum and maximum temperature) and an additional line on a second, independent y-axis (precipitation).

    We wrote our app’s front-end using a combination of simple HTML attributes and Phoenix LiveView’s built-in hooks to create dynamic behaviour without any JavaScript. For example, when the user inputs a postcode and submits the form, a new graph for the temperature and precipitation in the given area is instantly generated.

    We investigated two libraries in order to generate our graphs: Contex and Vega-Lite. Contex is a simple library for generating charts and plots in Elixir by generating SVG output. Vega-Lite is a more general tool, a high-level language (based on Vega, a declarative language for creating interactive visualisations) with various functionality for different common graph types, where the visualisation is created as a JSON object.

    Using APIs and creating an input form

    Before we could work with any graph libraries, our first task was to use an open-source API to retrieve the weather data we required for the graph. We began by getting the current temperature for a fixed “default” postcode, to ensure it was working correctly. It was not difficult to find an API that suited our purposes. We soon came across Open-Meteo, which contained all the information we needed: the current temperature, the maximum and minimum temperature for a given day, the seven-day forecast, and the precipitation.

    However, this API came with a limitation: it was only able to retrieve the weather for a given latitude and longitude, rather than for a given postcode. Due to this, we had to find a second open-source API, which could fetch the latitude and longitude for a given postcode. We ultimately landed on the API provided by postcodes.io for this purpose. We then followed this up with a call to Open-Meteo, so that when the application was fully set up inserting a postcode would seamlessly fetch the relevant temperature data for that location. The following code shows the function to retrieve this information and add it to the LiveView socket:

    elixir
    def assign_temp_and_location(socket, location) do
      {coordinates, admin_ward} = Weather.get_location(location)
      temperature = Weather.get_weather(coordinates)
    
      assign(socket,
        temperature: temperature,
        admin_ward: admin_ward
      )
    end
    
    

    Having achieved this, our next task was simple: creating an input field to allow the user to specify a postcode that we would then fetch the weather data for. We were able to implement this using a simple HTML form element which, upon submission, queries the APIs and generates a new graph based on the data received.

    Creating a graph with Contex

    At this stage we had a barebones implementation of the current temperature through an input field. The next step of the process was expanding this from a basic plaintext temperature display to a more detailed graph containing the forecast, maximum and minimum temperature, and precipitation. We needed to make use of an external library to accomplish this, and originally found Contex, which allows for the creation and rendering of SVG charts through Elixir. This initially seemed like the right call, as the Contex charts were neat and legible, and the code needed to create them was relatively simple:

    elixir
    defp assign_chart_svg(%{assigns: %{chart: chart, admin_ward: admin_ward}} = socket) do
      assign(socket,
        :chart_svg,
        Contex.Plot.new(700, 400, chart)
        |> Contex.Plot.titles("Daily maximum and minimum temperature in #{admin_ward}", "")
        |> Contex.Plot.axis_labels("Date", "Temperature")
        |> Contex.Plot.plot_options(%{legend_setting: :legend_right})
        |> Contex.Plot.to_svg()
      )
    end
    
    

    However, problems soon arose with attempting to use this library for our purposes. Firstly, Contex would not allow for the setting of custom intervals on a line graph, meaning when trying to include both the seven-day history and seven-day forecast the x-axis would be abbreviated, with an interval every two days instead of every day. Secondly, our desire to make use of multiple y-axes to display both the maximum and minimum temperature and the precipitation simultaneously was not possible.

    The graph generated by Contex

    Exacerbating this problem was Contex’s documentation, which was very limited, particularly for line charts, a relatively recent addition to the library. This meant that it was difficult to ascertain whether there were solutions to our problems. Unable to achieve what we set out for with Contex, we opted to investigate different libraries.

    From Contex to Vega-Lite

    We were recommended to look at Vega-Lite, which has very thorough documentation for the JSON specification. By combining this with the documentation for Vega-Lite Elixir bindings, we had the possibility to generate graphs with much greater functionality than Contex had provided.

    Vega-Lite is very powerful, and using it allowed us to easily display both the seven-day history and the seven-day forecast data received from the API. We were also able to show the precipitation in addition to the temperature data, each with its own independent y-axis. We could also modify the colours of the lines, add axis labels and modify their angles for optimum visual appeal. We were also able to add a vertical line in the middle of the graph, indicating the data points for the current date.

    |The graph generated by Contex

    It’s worth noting however, that when using the Vega-Lite Elixir bindings, all of the options have been normalised to snake-case atom keys. For example, in axis (for colouring the axes labels), the field is title_colour :, rather than ` titleColor :` as given in the JSON specification. This caused us some brief trouble when at first we used the camel-case version, and the options were not displaying. The following is a partial excerpt of the code used for the graph:

    elixir
    new_chart = Vl.new(width: 700, height: 400, resolve: [scale: [y: "independent"]])
    
    chart =
      Vl.data_from_values(new_chart, dataset)
      |> Vl.layers([
        Vl.new()
        |> Vl.layers([
          Vl.new()
          |> Vl.mark(:line, color: "#FF2D00")
          |> Vl.encode_field(:x, "date", type: :ordinal, title: "Date", axis: [label_angle: -45])
          |> Vl.encode_field(:y, "max", type: :quantitative, title: "Maximum temperature"),
    

    In order to render the Vega-Lite graphs to a usable format (in our case SVG) we needed the VegaLite.Export functions. Unfortunately for SVG, PDF, and PNG exports, these functions rely on npm packages, meaning we had to add Node.js, npm, and some additional Vega and Vega-Lite dependencies to our project. Exporting the graph as an SVG was the best option as it allowed us to reuse code from the Contex implementation and display the graph in our HTML page render as we had before, but if we had wanted to avoid installing the npm packages, it would also have been possible to export the graph directly to HTML or as a JSON instead.

    Conclusion

    At the end of the process, we had broadly succeeded in creating what we set out to create: a Phoenix LiveView app that could display the weather and precipitation data for a week on either side of the current date for any given UK postcode, in a neat and colour-coded line graph. We came away from the process with both a better understanding of LiveView and a good idea of the strengths and weaknesses of the two libraries we utilised.

    Contex provides a simpler and lightweight functionality, making it easy to create basic graphs. However, its comparatively limited library and its insufficient documentation provide obstacles to using it for more complex graphs, and as such it ultimately proved unsuitable for our purposes. Meanwhile, Vega-Lite is thoroughly documented and contains more intricate and advanced functionality, allowing us to create the application as outlined. Despite this, it does also have several drawbacks: its language-agnostic documentation occasionally made it slightly confusing to implement in Elixir, and the packages necessary to export the graphs create a significant JavaScript footprint in the application. When working on a project that could require one of these two libraries, it might help to consider these strengths and weaknesses in order to determine which would be the best fit.

    References

    Weather application on Github

    Open-Meteo API

    Postcodes API

    Contex documentation

    Vega-Lite documentation

    Vega-Lite Elixir bindings documentation

    The post Creating a simple weather application with Phoenix LiveView appeared first on Erlang Solutions .

    • wifi_tethering open_in_new

      This post is public

      www.erlang-solutions.com /blog/creating-a-simple-weather-application-with-phoenix-liveview/

    • chevron_right

      Gajim: Gajim 1.7.2

      news.movim.eu / PlanetJabber • 9 March, 2023

    Gajim 1.7.2. brings many bug fixes and some useful improvements. Gajim now allows you to delete messages from your local chat history (in case of nasty spam messages). Furthermore, detection of WAV audio files has been improved and you can now click the waveform to skip to a specific timestamp within a voice message. Thank you for all your contributions!

    What’s New

    Many users voiced their interest in having a way to remove messages from their local chat history. This is now possible and lets you remove nasty spam messages, if moderators didn’t catch them in time.

    • Click the audio waveform to skip to specific timestamps within voice messages
    • Gajim’s Windows installer is now available in Polish, and it also looks better on High-DPI screens
    • When creating a new group chat, Gajim now automatically selects it
    • An issue with settings migration has been fixed
    • Infinite file size limit for file transfers is now recognized correctly
    • Nickname highlight in group chats has been improved

    Have a look at the changelog for a complete list.

    Gajim

    As always, don’t hesitate to contact us at gajim@conference.gajim.org or open an issue on our Gitlab .

    • wifi_tethering open_in_new

      This post is public

      gajim.org /post/2023-03-09-gajim-1.7.2-released/

    • chevron_right

      Isode: M-Guard 1.4 New Capabilities

      news.movim.eu / PlanetJabber • 7 March, 2023

    M-Guard 1.4 is a platform support update release for M-Guard Console and M-Guard Appliance. M-Guard Appliance has been updated to use UEFI instead of BIOS for key system services.

    Platform Support

    The M-Guard Appliance now supports running on Netgate 6100 and 6100 MAX appliance systems.

    M-Guard Appliance on Hyper-V now uses Generation 2 virtual machines.

    M-Guard Appliance on VirtualBox now uses EFI.

    Use of BIOS for booting is deprecated in favor of UEFI.

    Base Operation System Upgraded

    The M-Guard Appliance operating system is now powered by FreeBSD 13.1.

    Notice

    Upgrading earlier installations requires special steps.  Contact Isode support for assistance.

    • wifi_tethering open_in_new

      This post is public

      www.isode.com /company/wordpress/m-guard-1-4-new-capabilities/

    • chevron_right

      Erlang Solutions: Se explican las colas de Quorum de RabbitMQ: lo que necesita saber.

      news.movim.eu / PlanetJabber • 7 March, 2023 • 9 minutes

    Este tipo de cola es importante cuando RabbitMQ se usa en una instalación de clúster. Descubre más en este blog.


    Introducción a las Colas de Quorum

    En RabbitMQ 3.8.0 , una de las nuevas características más significativas fue la introducción de las Colas de Quorum. La Cola de Quorum es un nuevo tipo de cola que se espera que reemplace la cola por defecto (que ahora se llama classic) en el futuro, para algunos casos de uso. Este tipo de cola es importante cuando RabbitMQ se utiliza en una instalación en clúster, ya que proporciona una replicación de mensajes menos intensiva en la red mediante el protocolo Raft.

    Uso de las Colas de Quorum

    Una cola clásica tiene un maestro en algún lugar de un nodo en el clúster, mientras que los espejos se ejecutan en otros nodos. Esto funciona de la misma manera para las Colas de Quorum, donde el líder, por defecto, se ejecuta en el nodo al que estaba conectada la aplicación cliente que la creó, y los seguidores se crean en el resto de los nodos del clúster.

    En el pasado, la replicación de colas se especificaba mediante políticas en conjunción con las Colas Clásicas. Las colas de Quorum se crean de manera diferente, pero deberían ser compatibles con todas las aplicaciones cliente que permiten proporcionar argumentos al declarar una cola. Se debe proporcionar el argumento  x-queue-type  con el valor de quorum al crear la cola.

    Por ejemplo, utilizando el cliente AMQP de Elixir1, la declaración de una Cola de Quorum es la siguiente:

    Queue.declare(publisher_chan, "my-quorum-queue", durable: true, arguments: [ "x-queue-type": "quorum" ])
    

    Una diferencia importante entre las Colas Clásicas y las de Quorum es que las Colas de Quorum solo pueden declararse duraderas, de lo contrario, se generará el siguiente mensaje de error:

    :server_initiated_close, 406, "PRECONDITION_FAILED - invalid property 'non-durable' for queue 'my-quorum-queue'

    Después de declarar la cola, podemos observar que es de tipo quorum en la Interfaz de Administración:

    Podemos ver que una cola de Quorum tiene un líder, que sirve aproximadamente para el mismo propósito que el Maestro de la Cola Clásica. Toda la comunicación se enruta al Líder de la Cola, lo que significa que la localidad del líder de la cola tiene un efecto en la latencia y el ancho de banda de los mensajes, sin embargo, el efecto debería ser menor que en las Colas Clásicas.

    El consumo de una Cola de Quorum se hace de la misma manera que otros tipos de colas.

    Nuevas características de las Colas de Quorum

    Las Colas de Quorum vienen con algunas características y restricciones especiales. No pueden ser no duraderas, porque el registro de Raft siempre se escribe en el disco, por lo que nunca se pueden declarar como transitorias. Tampoco admiten, a partir de la versión 3.8.2, TTL de mensajes y prioridades de mensajes2.

    Dado que el caso de uso para las Colas de Quorum es la seguridad de los datos, tampoco se pueden declarar como exclusivas, lo que significaría que se eliminan tan pronto como el consumidor se desconecta.

    Como todos los mensajes en las Colas de Quorum son persistentes, la opción ‘delivery-mode’ de AMQP no tiene efecto en su funcionamiento.

    Consumidor Único Activo

    Esto no es exclusivo de las Colas de Quorum, pero es importante mencionarlo: aunque se perdió la función de Cola Exclusiva, ganamos una nueva función que es aún mejor en muchos aspectos y que se solicitaba con frecuencia.

    El Consumidor Único Activo te permite adjuntar múltiples consumidores a una cola, mientras que solo uno de ellos está activo. Esto te permite crear consumidores altamente disponibles al tiempo que te aseguras de que en cualquier momento solo uno de ellos recibe mensajes, algo que antes no era posible lograr con RabbitMQ.

    Un ejemplo de cómo declarar una cola con la función de Consumidor Único Activo en Elixir:

    Queue.declare(publisher_chan, "single-active-queue", durable: true, arguments: [ "x-queue-type": "quorum", "x-single-active-consumer": true ])
    
    
    

    La cola con la configuración de Consumidor Único Activo habilitada se marca como SAC. En la imagen anterior, podemos ver que dos consumidores están adjuntos a ella (dos canales ejecutaron Basic.consume en la cola). Al publicar en la cola, solo uno de los consumidores recibirá el mensaje. Cuando ese consumidor se desconecte, el otro debería tomar la propiedad exclusiva de la secuencia de mensajes.

    ' Basic.get'

    o la inspección del mensaje en la Interfaz de Gestión no se puede hacer con colas de Consumidor Único Activo.

    Haciendo un seguimiento de los reintentos, los mensajes envenenados

    Llevar un recuento de cuántas veces se rechazó un mensaje es una de las funciones más solicitadas para RabbitMQ , y finalmente ha llegado con las Colas de Quorum. Esto te permite manejar los llamados mensajes envenenados de manera más efectiva que antes, ya que las implementaciones anteriores a menudo sufrían por la incapacidad de renunciar a los reintentos en caso de que un mensaje se quedara atascado o tenían que llevar un registro de cuántas veces se entregó un mensaje en una base de datos externa.

    NOTA : Para las Colas de Quorum, es mejor práctica tener siempre algún límite en el número de veces que se puede rechazar un mensaje. Dejar que este recuento de rechazos de mensajes crezca para siempre puede llevar a un comportamiento erróneo de la cola debido a la implementación Raft.

    Cuando se usan las Colas Clásicas y se vuelve a encolar un mensaje por cualquier motivo, con la marca 'redelivered' establecida, lo que esta marca significa esencialmente es ‘el mensaje puede haberse procesado ya’. Esto te ayuda a verificar si el mensaje es un duplicado o no. La misma marca existe, pero se amplió con la cabecera 'x-delivery-count' , que lleva un registro de cuántas veces se ha vuelto a encolar.

    Podemos observar esta cabecera en la Interfaz de Gestión:

    Como podemos ver, la marca 'redelivered' está establecida y la cabecera 'x-delivery-count' es 2.

    Ahora tu aplicación está mejor equipada para decidir cuándo renunciar a los reintentos.

    Si eso no es suficiente, ahora puedes definir las reglas basadas en el recuento de entregas para enviar el mensaje a un intercambio diferente en lugar de volver a encolarlo. Esto se puede hacer directamente desde RabbitMQ, tu aplicación no tiene que saber acerca de la reintentación. ¡Permíteme ilustrarlo con un ejemplo!

    Ejemplo: ¡Re-enrutamiento de mensajes rechazados! Nuestro caso de uso es que recibimos mensajes que necesitamos procesar, de una aplicación que, sin embargo, puede enviarnos mensajes que no se pueden procesar. La razón podría ser porque los mensajes están mal formados, o porque la propia aplicación no puede procesarlos por alguna razón u otra, pero no tenemos una forma de notificar a la aplicación emisora de estos errores. Estos errores son comunes cuando RabbitMQ sirve como bus de mensajes en el sistema y la aplicación emisora no está bajo el control del equipo de la aplicación receptora.

    Luego declaramos una cola para los mensajes que no pudimos procesar:

    Y también declaramos un intercambio de fanout , que usaremos como intercambio de cola muerta:

    Y unimos la cola de unprocessable-messages a ella.

    Creamos la cola de aplicaciones llamada my-app-queue y la política correspondiente:

    Podemos usar asic.reject o Basic.nack para rechazar el mensaje, debemos usar la propiedad requeue establecida en verdadero.

    Aquí hay un ejemplo simplificado en Elixir:

    def get_delivery_count(headers) do case headers do :undefined -> 0 headers -> { _ , _, delivery_cnt } = List.keyfind(headers, "x-delivery-count", 0, {:_, :_, 0} ) delivery_cnt end end receive do {:basic_deliver, msg, %{ delivery_tag: tag, headers: headers} = meta } -> delivery_count = get_delivery_count(headers) Logger.info("Received message: '#{msg}' delivered: #{delivery_count} times") case msg do "reject me" -> Logger.info("Rejected message") :ok = Basic.reject(consumer_chan, tag) _ -> \ Logger.info("Acked message") :ok = Basic.ack(consumer_chan, tag) end end
    
    

    Primero publicamos el mensaje, “este es un buen mensaje”:

    13:10:15.717 [info] Received message: 'this is a good message' delivered: 0 times 13:10:15.717 [info] Acked message
    
    

    Luego publicamos un mensaje que rechazamos:

    13:10:20.423 [info] Received message: 'reject me' delivered: 0 times 13:10:20.423 [info] Rejected message 13:10:20.447 [info] Received message: 'reject me' delivered: 1 times 13:10:20.447 [info] Rejected message 13:10:20.470 [info] Received message: 'reject me' delivered: 2 times 13:10:20.470 [info] Rejected message
    

    Y después de ser entregado tres veces, se enruta a la cola de unprocessed-messages .

    Podemos ver en la Interfaz de gestión que el mensaje se enruta a la cola:

    Controlando los miembros del quórum

    Las colas de quórum no cambian automáticamente el grupo de seguidores / líderes. Esto significa que agregar un nuevo nodo al clúster no garantizará automáticamente que el nuevo nodo se esté utilizando para alojar colas de quórum. Las colas clásicas en versiones anteriores manejaban la adición de colas en nuevos nodos de clúster a través de la interfaz de políticas, sin embargo, esto podría plantear problemas a medida que se escalaban o reducían los tamaños de clúster. Una nueva característica importante en la serie 3.8.x para colas de quórum y colas clásicas, son las operaciones de reequilibrio de maestros de cola integradas. Anteriormente, esto solo era posible mediante scripts y complementos externos.

    Agregar un nuevo miembro al quórum se puede lograr usando el comando grow:

    rabbitmq-queues grow rabbit@$NEW_HOST all

    Eliminar un host obsoleto, por ejemplo, eliminado, de los miembros se puede hacer a través del comando shrink:

    rabbitmq-queues shrink rabbit@$OLD_HOST
    
    

    También podemos reequilibrar los maestros de la cola para que la carga sea equitativa en los nodos:

    rabbitmq-queues rebalance all

    Lo cual (en bash) mostrará una tabla agradable con estadísticas sobre el número de maestros en los nodos. En Windows, use la bandera --formatter json para obtener una salida legible.

    Resumen

    RabbitMQ 3.8.x viene con muchas características nuevas. Las Colas de Quórum son solo una de ellas. Proporcionan una implementación nueva y más comprensible, en algunos casos menos intensiva en recursos, para lograr colas replicadas y alta disponibilidad. Están construidos sobre Raft y admiten características diferentes a las Colas Clásicas, que fundamentalmente se basan en el protocolo de multidifusión garantizada personalizado3 (una variante de Paxos). Como este tipo y clase de colas todavía son bastante nuevos, solo el tiempo dirá si se convierten en el tipo de cola más utilizado y preferido para la mayoría de las instalaciones distribuidas de RabbitMQ en comparación con sus contrapartes, las Colas Espejadas Clásicas. Hasta entonces, use ambos según lo mejor se adapte a sus necesidades de Rabbit. 🙂

    ¿Necesitas ayuda con tu RabbitMQ?

    Nuestro equipo líder mundial en RabbitMQ ofrece una variedad de opciones para satisfacer sus necesidades. Tenemos todo, desde chequeos de salud hasta soporte y monitoreo, para ayudarlo a garantizar un sistema RabbitMQ eficiente y confiable.

    O, si desea tener una visibilidad completa de su sistema RabbitMQ desde un panel fácil de leer, ¿por qué no aprovechar nuestra prueba gratuita de WombatOAM ?”

    The post Se explican las colas de Quorum de RabbitMQ: lo que necesita saber. appeared first on Erlang Solutions .

    • wifi_tethering open_in_new

      This post is public

      www.erlang-solutions.com /blog/se-explican-las-colas-de-quorum-de-rabbitmq-lo-que-necesita-saber/

    • chevron_right

      Ignite Realtime Blog: HTTP File Upload v1.2.2 released!

      news.movim.eu / PlanetJabber • 5 March, 2023

    We’ve just released version 1.2.2 of the HTTP File Upload plugin for Openfire. This release includes Ukrainian language support, thanks to Yurii Savchuk (svais) and his son Vladislav Savchuk (Bruhmozavr), as well as a few updated translations for Portuguese, Russian and English.

    Grab it from the plugins page in your Openfire Admin Console, or download manually from the HTTP File Upload archive page, here .

    1 post - 1 participant

    Read full topic