<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Iván Corrales Solera on Medium]]></title>
        <description><![CDATA[Stories by Iván Corrales Solera on Medium]]></description>
        <link>https://medium.com/@ivan-corrales-solera?source=rss-e63f2d4657c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pQbZI3gLia7n7JxPW7aVtQ.jpeg</url>
            <title>Stories by Iván Corrales Solera on Medium</title>
            <link>https://medium.com/@ivan-corrales-solera?source=rss-e63f2d4657c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:17:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivan-corrales-solera/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Getting Started with OpenTelemetry in distributed Go Microservices]]></title>
            <link>https://medium.com/wesovilabs/getting-started-with-opentelemetry-in-distributed-go-microservices-192e7e21bd7c?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/192e7e21bd7c</guid>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 06:40:02 GMT</pubDate>
            <atom:updated>2024-01-26T06:40:02.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pKjJSt3h2fSVG5dV_PBVg.jpeg" /></figure><h3>Introduction</h3><p>In the ever-changing world of software development, microservices have become the go-to approach, offering scalability, flexibility, and easy maintenance. But, of course, only good comes with its fair share of challenges, especially in the observability department. As systems get more intricate, keeping tabs on the data flow through different services becomes a top priority for troubleshooting, optimizing performance, and ensuring reliability.</p><p>Enter OpenTelemetry, the superhero of observability. It’s an open-source framework designed to make collecting distributed traces and metrics from applications a breeze. With OpenTelemetry, developers can get a peek into how microservices interact, making it a breeze to spot bottlenecks, diagnose issues, and fine-tune the overall system performance.</p><p>Observability, in the microservices world, is like having a crystal ball for your system’s internal state based on what it’s showing on the outside. It’s the trio of tracing, metrics, and logging — essential for keeping a microservices architecture healthy and reliable.</p><p>So, buckle up as we dive into this tutorial, breaking down the essential concepts of OpenTelemetry in Go microservices. From getting the framework ready for your project to jazzing up your code with instruments, exporting and visualizing data, and sprinkling in some best practices, this guide is your roadmap to elevating the observability game in your microservices architecture.</p><p>Whether you’re a seasoned Go developer or just dipping your toes into the microservices pool, mastering OpenTelemetry can be a game-changer for the upkeep and performance of your distributed systems. Ready to unlock the superpowers of observability in Go microservices with OpenTelemetry? Let’s roll!</p><h3>Opentelemetry concepts</h3><h4>Tracing 🕵️‍♂️</h4><p>Tracing, a fundamental aspect of OpenTelemetry, involves tracking the flow of a request as it traverses through various components or services in a distributed system. OpenTelemetry provides a tracing API that allows developers to instrument their code and create spans, which represent units of work. These spans are then collected to form distributed traces, offering a visual representation of the journey a request takes through the microservices.</p><h4>Context Propagation 🌐</h4><p>In microservices, requests often span multiple services. Context propagation is a crucial aspect to ensure that information, such as trace context, is carried along with the request as it moves through different components. OpenTelemetry seamlessly instruments context propagation, allowing trace information to flow consistently across various services.</p><h4>Metrics 📊</h4><p>Metrics are quantitative measurements of system behavior over time. They provide insights into the performance, resource usage, and other aspects of the system. OpenTelemetry supports the instrumentation of code to collect and export metrics, including counters, gauges, and histograms. This capability enables developers to gain a quantitative understanding of how their microservices are behaving.</p><h4>Instrumentation 🎺</h4><p>Instrumentation involves adding code to an application to collect data for observability purposes. OpenTelemetry provides instrumentation libraries for various programming languages, making it easier for developers to integrate observability into their applications. This includes creating spans for tracing and emitting metrics and contributing to a comprehensive observability strategy.</p><h4>Exporter 🚚</h4><p>Exporters are components responsible for transmitting collected observability data, including spans and metrics, to external systems or backends for analysis. OpenTelemetry supports various exporters compatible with popular observability backends such as Jaeger, Prometheus, and more. This flexibility ensures interoperability across different components of a microservices ecosystem.</p><h4>Collector 🧲</h4><p>The OpenTelemetry Collector is an intermediate component that receives observability data from instrumented applications and forwards it to the desired backend or storage. It is configurable and extensible, providing a centralized point for processing and exporting traces and metrics.</p><h4>Sampling 🎰</h4><p>Sampling involves deciding which traces or spans to collect and export. This is crucial to balance the overhead of collecting data with the need for comprehensive observability. OpenTelemetry offers sampling options, allowing users to control the rate at which traces are collected, striking a balance between resource usage and observability granularity.</p><p>Understanding these foundational concepts is essential for effectively implementing OpenTelemetry in a microservices environment. This knowledge enhances observability and troubleshooting capabilities, contributing to the overall success of distributed systems.</p><h3>Setting Up OpenTelemetry in a Go Project</h3><p>This section will guide you through setting up OpenTelemetry in your Go microservices project. This involves installing the necessary packages, configuring basic settings, and choosing an appropriate exporter for sending traces and metrics to an external observability backend.</p><h4><strong>Installation</strong></h4><p>First, install the OpenTelemetry Go SDK using Go Modules. Open your terminal and run the following command:</p><pre>go get go.opentelemetry.io/otel</pre><p>This fetches the OpenTelemetry Go SDK and its dependencies, ensuring you have the latest version.</p><h4><strong>Configuring OpenTelemetry</strong></h4><p>Create a new Go file (e.g., main.go) and import the necessary OpenTelemetry packages. Configure the basic settings, such as the tracer provider and exporter. Below is a basic configuration snippet:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;time&quot;<br><br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/exporters/stdout/stdouttrace&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br> semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br> ctx := context.Background()<br> // Create the exporter - let&#39;s use a stdout exporter<br> traceExporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())<br> if err != nil {<br>  panic(err)<br> }<br><br> // Create the resource to be traced<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;MyService&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Configure the trace provider<br> traceProvider := trace.NewTracerProvider(<br>  trace.WithBatcher(traceExporter, trace.WithBatchTimeout(2*time.Second)),<br>  trace.WithResource(res),<br> )<br> defer func() { _ = traceProvider.Shutdown(ctx) }()<br> otel.SetTracerProvider(traceProvider)<br>}</pre><h4><strong>Choosing and Configuring an Exporter</strong></h4><p>Select an appropriate exporter based on your observability backend.</p><p>The project is actively developed, and the list of supported exporters is continuously expanded. To get the most up-to-date information, it’s recommended to check the official OpenTelemetry documentation or repository on GitHub. Some of the most popular exporters are enum below:</p><ol><li>Jaeger Exporter: Sends traces to Jaeger, an open-source, end-to-end distributed tracing system.</li><li>Zipkin Exporter: Exports traces to Zipkin, a distributed tracing system.</li><li>Prometheus Exporter: Allows exporting metrics to Prometheus, a monitoring and alerting toolkit.</li><li>OTLP Exporter: The OpenTelemetry Protocol (OTLP) exporter sends traces and metrics to services that support the OpenTelemetry protocol.</li><li>Logging Exporter: Exports trace and metric data as logs.</li><li>Honeycomb Exporter: Sends trace and metric data to Honeycomb, a service for observability.</li></ol><p>For example, you would choose the Jaeger exporter if you&#39;re using Jaeger. Adjust the configuration accordingly:</p><p>We would only need to replace the previous traceExporter definition as It’s shown:</p><pre><br>traceExporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())<br><br>// replace by <br><br>client := otlptracehttp.NewClient(otlptracehttp.WithEndpoint(&quot;http://localhost:14268/api/traces&quot;), otlptracehttp.WithInsecure(), otlptracehttp.WithCompression(otlptracehttp.NoCompression))<br>traceExporter, err := otlptrace.New(ctx, client)</pre><p>Adjust the collector endpoint based on your Jaeger setup.</p><p>With these snippets, you’ve initialized OpenTelemetry in your Go project, configured basic settings, and chosen an exporter.</p><h3>Instrumenting Go Code</h3><p>In this section, we’ll delve into the fundamental aspects of instrumenting your Go microservices code with OpenTelemetry. We’ll cover the basics of tracing, creating and managing traces, setting up context propagation, and incorporating metric instrumentation.</p><h4>Instrumentation Basics</h4><p>Instrumentation involves adding code to your application to capture relevant data for observability. In the context of OpenTelemetry, this includes creating and managing traces.</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;time&quot;<br><br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/attribute&quot;<br> &quot;go.opentelemetry.io/otel/exporters/stdout/stdouttrace&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br>  semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br> ctx := context.Background()<br> // Create the exporter - let&#39;s use a stdout exporter<br> traceExporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())<br> if err != nil {<br>  panic(err)<br> }<br><br> // Create the resource to be traced<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;MyService&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Configure the trace provider<br> traceProvider := trace.NewTracerProvider(<br>  trace.WithBatcher(traceExporter, trace.WithBatchTimeout(2*time.Second)),<br>  trace.WithResource(res),<br> )<br> defer func() { _ = traceProvider.Shutdown(ctx) }()<br> otel.SetTracerProvider(traceProvider)<br><br> // Create &amp; start the tracer<br> tracer := traceProvider.Tracer(&quot;MyService&quot;)<br> ctx, span := tracer.Start(context.Background(), &quot;hello-span&quot;)<br> span.SetAttributes(attribute.String(&quot;environment&quot;, &quot;staging&quot;))<br> defer span.End()<br><br> // Add events<br> span.AddEvent(&quot;startEvent&quot;)<br> // ...<br> span.AddEvent(&quot;endEvent&quot;)<br>}</pre><p>In this snippet, we use the OpenTelemetry tracer to start a new span, representing a unit of work. The defer span.End() ensures that the span is properly closed when the operation is completed.</p><h4>Tracing</h4><p>Tracing involves creating a sequence of spans to represent the flow of requests through your microservices. Here’s an example of tracing multiple operations across services:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br><br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/attribute&quot;<br> &quot;go.opentelemetry.io/otel/exporters/stdout/stdouttrace&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br>semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br> ctx := context.Background()<br> // Create the exporter - let&#39;s use a stdout exporter<br> traceExporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())<br> if err != nil {<br>  panic(err)<br> }<br><br> // Create the resource to be traced<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;MyService&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Configure the trace provider<br> traceProvider := trace.NewTracerProvider(<br>  trace.WithBatcher(traceExporter, trace.WithBatchTimeout(2*time.Second)),<br>  trace.WithResource(res),<br> )<br> defer func() { _ = traceProvider.Shutdown(ctx) }()<br> otel.SetTracerProvider(traceProvider)<br> var wg sync.WaitGroup<br> wg.Add(2)<br> go operationA(ctx, &amp;wg)<br> go operationB(ctx, &amp;wg)<br> wg.Wait()<br><br>}<br><br>func operationA(ctx context.Context, wg *sync.WaitGroup) {<br> defer wg.Done()<br> // Create &amp; start the tracer<br> tracer := otel.Tracer(&quot;MyService&quot;)<br> ctx, span := tracer.Start(context.Background(), &quot;operationA&quot;)<br> span.SetAttributes(attribute.String(&quot;environment&quot;, &quot;staging&quot;))<br> defer span.End()<br><br> for i := 0; i &lt; 5; i++ {<br>  // Add events<br>  span.AddEvent(&quot;iterate operationA&quot;)<br>  time.Sleep(1 * time.Second)<br> }<br><br>}<br><br>func operationB(ctx context.Context, wg *sync.WaitGroup) {<br> defer wg.Done()<br> // Create &amp; start the tracer<br> tracer := otel.Tracer(&quot;MyService&quot;)<br> ctx, span := tracer.Start(context.Background(), &quot;operationB&quot;)<br> span.SetAttributes(attribute.String(&quot;environment&quot;, &quot;staging&quot;))<br> defer span.End()<br><br> for i := 0; i &lt; 5; i++ {<br>  // Add events<br>  span.AddEvent(&quot;iterate operationB&quot;)<br>  time.Sleep(2 * time.Second)<br> }<br>}</pre><p>This example demonstrates how to create a trace that spans multiple operations within the same and different services.</p><h4>Metrics</h4><p>OpenTelemetry also supports metric instrumentation to collect quantitative data about your application’s performance. Below is a simple example of creating and exporting a custom metric:</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;time&quot;<br><br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/exporters/stdout/stdoutmetric&quot;<br> &quot;go.opentelemetry.io/otel/metric&quot;<br> api &quot;go.opentelemetry.io/otel/sdk/metric&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br> ctx := context.Background()<br> // Create the exporter - let&#39;s use a stdout exporter<br> metricExporter, err := stdoutmetric.New(stdoutmetric.WithPrettyPrint())<br><br> if err != nil {<br>  panic(err)<br> }<br><br> // Create the resource to be traced<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;MyService&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Configure the meter provider<br> meterProvider := api.NewMeterProvider(<br>  api.WithResource(res),<br>  api.WithReader(api.NewPeriodicReader(metricExporter,<br>   api.WithInterval(1*time.Second))),<br> )<br><br> defer func() { _ = meterProvider.Shutdown(ctx) }()<br> otel.SetMeterProvider(meterProvider)<br><br> meter := otel.Meter(&quot;wesovilabs-meter&quot;)<br> // Define a counter metric<br> counter, err := meter.Int64Counter(&quot;my_service.int_counter&quot;,<br>  metric.WithDescription(&quot;int_counter description&quot;))<br> if err != nil {<br>  panic(err)<br> }<br> for i := 0; i &lt; 10; i++ {<br>  // Record an occurrence of an event<br>  counter.Add(context.Background(), 1)<br>  time.Sleep(300 * time.Millisecond)<br> }<br>}</pre><p>In this snippet, we create a counter metric and record an occurrence of an event. This metric can be exported to an observability backend for further analysis.</p><p>With these snippets, you’ve first instrumented your Go code with OpenTelemetry for tracing and metric collection.</p><h3>Showcase: Observability for distributed microservices</h3><p>In this showcase, we delve into the seamless integration of OpenTelemetry within a microservices architecture, orchestrating communication between two distinct services while efficiently capturing metrics and traces. Our demonstration highlights the utilization of Prometheus for metric persistence, Grafana for visualizing these metrics, and Jaeger for tracing.</p><blockquote>Clone the repository from <a href="https://github.com/wesovilabs/getting-started-opentelemety-go">https://github.com/wesovilabs/getting-started-opentelemety-go</a></blockquote><h4>Ar<strong>chitecture Overview:</strong></h4><p><strong>Microservice Ping: </strong>This microservice, acting as the initiator, enables a single endpoint <em>/ping</em> that sends requests to the endpoint <em>/pong</em> in <em>microservice Pong.</em></p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br><br> &quot;github.com/prometheus/client_golang/prometheus/promhttp&quot;<br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/attribute&quot;<br> &quot;go.opentelemetry.io/otel/exporters/otlp/otlptrace&quot;<br> &quot;go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp&quot;<br> &quot;go.opentelemetry.io/otel/exporters/prometheus&quot;<br> &quot;go.opentelemetry.io/otel/metric&quot;<br> api &quot;go.opentelemetry.io/otel/sdk/metric&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br> semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br><br> pongEndpoint := os.Getenv(&quot;PONG_ENDPOINT&quot;)<br> address := os.Getenv(&quot;ADDRESS&quot;)<br> traceBackendEndpoint := os.Getenv(&quot;JAEGER_ADDRESS&quot;)<br> ctx := context.Background()<br><br> // Create the resource to be observed<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;Ping&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Tracing configuration<br><br> traceClient := otlptracehttp.NewClient(otlptracehttp.WithEndpoint(traceBackendEndpoint), otlptracehttp.WithInsecure(), otlptracehttp.WithCompression(otlptracehttp.NoCompression))<br> traceExporter, err := otlptrace.New(ctx, traceClient)<br> if err != nil {<br>  panic(err)<br> }<br> traceProvider := trace.NewTracerProvider(<br>  trace.WithBatcher(traceExporter, trace.WithBatchTimeout(2*time.Second)),<br>  trace.WithResource(res),<br> )<br> defer func() { _ = traceProvider.Shutdown(ctx) }()<br> otel.SetTracerProvider(traceProvider)<br><br> tracer := traceProvider.Tracer(&quot;Ping&quot;)<br><br> // Metric configuration<br><br> prometheusExporter, err := prometheus.New()<br> if err != nil {<br>  panic(err)<br> }<br> meterProvider := api.NewMeterProvider(<br>  api.WithResource(res),<br>  api.WithReader(prometheusExporter),<br> )<br> meter := otel.Meter(<br>  &quot;wesovilabs.com/tutorial/opentelemetry/ping/manual-instrumentation&quot;,<br>  metric.WithInstrumentationVersion(&quot;v0.0.1&quot;),<br> )<br> counter, err := meter.Int64Counter(<br>  &quot;request_count&quot;,<br>  metric.WithDescription(&quot;Incoming request count&quot;),<br>  metric.WithUnit(&quot;request&quot;),<br> )<br> if err != nil {<br>  log.Fatalln(err)<br> }<br> hist, err := meter.Float64Histogram(<br>  &quot;duration&quot;,<br>  metric.WithDescription(&quot;Incoming end to end duration&quot;),<br>  metric.WithUnit(&quot;milliseconds&quot;),<br> )<br> if err != nil {<br>  log.Fatalln(err)<br> }<br><br> defer func() { _ = meterProvider.Shutdown(ctx) }()<br> otel.SetMeterProvider(meterProvider)<br><br> // HTTP Endpoints<br> //Used to expose metrics in prometheus format<br> http.Handle(&quot;/metrics&quot;, promhttp.Handler())<br> // Endpoint to be observer<br> http.HandleFunc(&quot;/ping&quot;, func(w http.ResponseWriter, req *http.Request) {<br>  ctx, span := tracer.Start(context.Background(), &quot;ping-request&quot;)<br>  span.SetAttributes(attribute.String(&quot;environment&quot;, &quot;staging&quot;))<br>  defer span.End()<br>  span.AddEvent(&quot;Start request processing&quot;)<br>  requestStartTime := time.Now()<br>  span.AddEvent(&quot;Invoke external endpoint&quot;)<br>  if _, err := http.Get(fmt.Sprintf(&quot;http://%s/pong&quot;, pongEndpoint)); err != nil {<br>   span.AddEvent(&quot;Response with error&quot;)<br>   w.Write([]byte(err.Error()))<br>  } else {<br>   span.AddEvent(&quot;Response success&quot;)<br>   w.Write([]byte(&quot;ok&quot;))<br>  }<br>  elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond)<br>  // Record measurements<br>  attrs := metric.WithAttributes(attribute.String(&quot;remoteAddr&quot;, req.RemoteAddr), attribute.String(&quot;userAgent&quot;, req.UserAgent()))<br>  span.AddEvent(&quot;Update metrics&quot;)<br>  counter.Add(ctx, 1, attrs)<br>  hist.Record(ctx, elapsedTime, attrs)<br> })<br><br> http.ListenAndServe(address, nil)<br><br>}</pre><p><strong>Microservice Pong:</strong> The recipient microservice could receive requests from microservice Ping or be invoked directly.</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;time&quot;<br><br> &quot;github.com/prometheus/client_golang/prometheus/promhttp&quot;<br> &quot;go.opentelemetry.io/otel&quot;<br> &quot;go.opentelemetry.io/otel/attribute&quot;<br> &quot;go.opentelemetry.io/otel/exporters/otlp/otlptrace&quot;<br> &quot;go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp&quot;<br> &quot;go.opentelemetry.io/otel/exporters/prometheus&quot;<br> &quot;go.opentelemetry.io/otel/metric&quot;<br> api &quot;go.opentelemetry.io/otel/sdk/metric&quot;<br> &quot;go.opentelemetry.io/otel/sdk/resource&quot;<br> &quot;go.opentelemetry.io/otel/sdk/trace&quot;<br> semconv &quot;go.opentelemetry.io/otel/semconv/v1.24.0&quot;<br>)<br><br>func main() {<br> address := os.Getenv(&quot;ADDRESS&quot;)<br> traceBackendEndpoint := os.Getenv(&quot;JAEGER_ADDRESS&quot;)<br><br> ctx := context.Background()<br><br> // Create the resource to be observed<br> res, err := resource.Merge(<br>  resource.Default(),<br>  resource.NewWithAttributes(<br>   semconv.SchemaURL,<br>   semconv.ServiceName(&quot;Pong&quot;),<br>   semconv.ServiceVersion(&quot;v0.0.1&quot;),<br>  ),<br> )<br> if err != nil {<br>  panic(err)<br> }<br><br> // Tracing configuration<br><br> traceClient := otlptracehttp.NewClient(otlptracehttp.WithEndpoint(traceBackendEndpoint), otlptracehttp.WithInsecure(), otlptracehttp.WithCompression(otlptracehttp.NoCompression))<br> traceExporter, err := otlptrace.New(ctx, traceClient)<br> if err != nil {<br>  panic(err)<br> }<br> traceProvider := trace.NewTracerProvider(<br>  trace.WithBatcher(traceExporter, trace.WithBatchTimeout(2*time.Second)),<br>  trace.WithResource(res),<br> )<br> defer func() { _ = traceProvider.Shutdown(ctx) }()<br> otel.SetTracerProvider(traceProvider)<br><br> tracer := traceProvider.Tracer(&quot;Pong&quot;)<br><br> // Metric configuration<br><br> prometheusExporter, err := prometheus.New()<br> if err != nil {<br>  panic(err)<br> }<br> meterProvider := api.NewMeterProvider(<br>  api.WithResource(res),<br>  api.WithReader(prometheusExporter),<br> )<br> meter := otel.Meter(<br>  &quot;wesovilabs.com/tutorial/opentelemetry/pong/manual-instrumentation&quot;,<br>  metric.WithInstrumentationVersion(&quot;v0.0.1&quot;),<br> )<br> counter, err := meter.Int64Counter(<br>  &quot;request_count&quot;,<br>  metric.WithDescription(&quot;Incoming request count&quot;),<br>  metric.WithUnit(&quot;request&quot;),<br> )<br> if err != nil {<br>  log.Fatalln(err)<br> }<br> hist, err := meter.Float64Histogram(<br>  &quot;duration&quot;,<br>  metric.WithDescription(&quot;Incoming end to end duration&quot;),<br>  metric.WithUnit(&quot;milliseconds&quot;),<br> )<br> if err != nil {<br>  log.Fatalln(err)<br> }<br><br> defer func() { _ = meterProvider.Shutdown(ctx) }()<br> otel.SetMeterProvider(meterProvider)<br><br> // HTTP Endpoints<br> //Used to expose metrics in prometheus format<br> http.Handle(&quot;/metrics&quot;, promhttp.Handler())<br> // Endpoint to be observer<br> http.HandleFunc(&quot;/pong&quot;, func(w http.ResponseWriter, req *http.Request) {<br>  ctx, span := tracer.Start(context.Background(), &quot;pong-request&quot;)<br>  span.SetAttributes(attribute.String(&quot;environment&quot;, &quot;staging&quot;))<br>  defer span.End()<br>  requestStartTime := time.Now()<br>  span.AddEvent(&quot;Response success&quot;)<br>  _, _ = w.Write([]byte(&quot;pong&quot;))<br><br>  elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond)<br><br>  // Record measurements<br>  span.AddEvent(&quot;Update metrics&quot;)<br>  attrs := metric.WithAttributes(attribute.String(&quot;remoteAddr&quot;, req.RemoteAddr), attribute.String(&quot;userAgent&quot;, req.UserAgent()))<br>  counter.Add(ctx, 1, attrs)<br>  hist.Record(ctx, elapsedTime, attrs)<br> })<br><br> http.ListenAndServe(address, nil)<br><br>}</pre><h4>Observability</h4><p>Opentelemetry integration allows for the automatic instrumentation of these services, capturing critical metrics and traces without manual intervention.</p><p><strong>Metrics Persistence: </strong>Prometheus, a widely used monitoring system, is employed to persist metrics collected by OpenTelemetry. Prometheus efficiently stores time-series data, enabling detailed analysis and system performance monitoring over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*pvgUka2lWlNQSOEu.png" /></figure><p><strong>Metrics Visualization: </strong>Grafana, a powerful visualization and monitoring platform, is leveraged to provide insightful visualizations of the metrics stored in Prometheus. Grafana’s flexible dashboarding capabilities enable the creation of customized dashboards, offering real-time insights into system behavior and performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GcVvQEuzqsnEnX3u.png" /></figure><p><strong>Tracing Management: </strong>Jaeger, an open-source distributed tracing system, manages traces generated by OpenTelemetry. Jaeger provides end-to-end visibility into the flow of requests between <em>microservice Ping </em>and <em>microservice Pong</em>, facilitating the identification of latency bottlenecks and performance optimizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PWvXurBeOQqdNa5j.png" /></figure><h4>Demonstration Flow</h4><ol><li><strong>Initiation</strong>: <em>microservice Ping </em>initiates a request to <em>microservice Pong</em>, triggering a series of interactions between the two services.</li><li><strong>Metrics Collection</strong>: OpenTelemetry automatically collects metrics related to the request processing, including latency, error rates, and resource utilization.</li><li><strong>Metrics Persistence:</strong> The collected metrics are persisted in Prometheus, ensuring that historical data is available for analysis and monitoring purposes.</li><li><strong>Metrics Visualization</strong>: Grafana retrieves metrics from Prometheus and presents them through intuitive dashboards, providing stakeholders real-time insights into system performance.</li><li><strong>Tracing Analysis</strong>: Jaeger captures traces of the request flow between <em>microservice Ping</em> and <em>microservice Pong</em>, allowing for in-depth analysis of request paths and identification of potential performance optimizations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-CnQTn6W6PrExxEm7RldQ.jpeg" /></figure><h4>Launch the services</h4><p>To simplify the deployment of this showcase, we will use the below docker-compose.yml</p><pre>services:<br><br>  ping:<br>    container_name: ping<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    environment:<br>      ADDRESS: 0.0.0.0:8081<br>      PONG_ENDPOINT: pong:8082<br>      JAEGER_ADDRESS: jaeger:4318<br>    entrypoint: [&quot;ping&quot;]<br>    ports:<br>      - 8081:8081<br>  <br>  pong:<br>    container_name: pong<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    environment:<br>      ADDRESS: 0.0.0.0:8082<br>      JAEGER_ADDRESS: jaeger:4318<br>    entrypoint: [&quot;pong&quot;]<br>    ports:<br>        - 8082:8082<br><br>  jaeger:<br>    image: jaegertracing/all-in-one:1.53<br>    container_name: jaeger<br>    environment:<br>      COLLECTOR_ZIPKIN_HOST_PORT: :9411<br>    ports:<br>      - 6831:6831/udp<br>      - 6832:6832/udp<br>      - 5778:5778 <br>      - 16686:16686 <br>      - 4317:4317 <br>      - 4318:4318 <br>      - 14250:14250<br>      - 14268:14268<br>      - 14269:14269<br>      - 9411:9411<br>  <br>  prometheus:<br>    image: prom/prometheus:v2.49.1<br>    container_name: prometheus<br>    volumes:<br>      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml<br>    ports:<br>      - 9090:9090<br>  <br>  grafana:<br>    image: grafana/grafana:9.5.15<br>    container_name: grafana<br>    volumes:<br>      - ./grafana/grafana.ini:/etc/grafana/grafana.ini<br>      - ./grafana/provisioning/:/etc/grafana/provisioning/<br>    ports:<br>      - 3000:3000</pre><p>This file is found in the root of the repository, and we need to launch all the services we rundocker-compose up</p><h4>Test the services</h4><p>Keep running as many requests as you want to generate some traffic (metrics &amp; traces)</p><pre>&gt;&gt; curl http://localhost:8081/ping<br>&gt;&gt; curl http://localhost:8082/pong</pre><p>Metrics can be checked in Grafana — <a href="http://localhost:3000/">http://localhost:300</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f46z_VBdz6FmnS6BH8YQcg.jpeg" /></figure><p>Traces/Spans can be examined in Jaeger — <a href="http://localhost:16686/">http://localhost:16686/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6HPRngifbCFL6iFKg16zA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb60rJwrEflv_utZ8iCNbQ.jpeg" /></figure><h3>Conclusion</h3><p>In this tutorial, we’ve embarked on a journey to enhance the observability of Go microservices using OpenTelemetry. From the initial setup to instrumenting code, propagating context, exporting traces and metrics, and visualizing data, we’ve explored the key aspects of integrating OpenTelemetry into your microservices architecture.!</p><p>Source code can be found at <a href="https://github.com/wesovilabs/getting-started-opentelemety-go">https://github.com/wesovilabs/getting-started-opentelemety-go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192e7e21bd7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wesovilabs/getting-started-with-opentelemetry-in-distributed-go-microservices-192e7e21bd7c">Getting Started with OpenTelemetry in distributed Go Microservices</a> was originally published in <a href="https://medium.com/wesovilabs">Wesovi Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minikube on a VPS from scratch]]></title>
            <link>https://ivan-corrales-solera.medium.com/minikube-on-a-vps-from-scratch-c776496ceb08?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c776496ceb08</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 12:41:47 GMT</pubDate>
            <atom:updated>2022-12-05T12:53:26.957Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s not rocket science to set up a Kubernetes (k8s) cluster on your <strong>local</strong> machine with <strong>minikube. </strong>On the other hand, It’s not straightforward when you want to set up minikube on a remote server. So, in this tutorial, I will share some learning after setting up my personal development environment in a VPS.</p><h3>Configure access to the remote machine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*drdKZaePgNhwDqWZ.png" /></figure><p>By default, you will be provided with root credentials to access the machine. I hardly encourage you to perform the following 2 steps (and the 3rd is up to you)</p><ol><li>Add your user account to the Server. Visit the following link if you need some help <a href="https://www.cyberciti.biz/faq/add-new-user-account-with-admin-access-on-linux/">https://www.cyberciti.biz/faq/add-new-user-account-with-admin-access-on-linux/</a></li><li>Enable ssh key-based authentication for the user created in the previous step. It’s a properer access mechanism than using a user password. <a href="https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server">https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server</a></li><li>Create a subdomain (or a domain) for your remote machine. It’s always easier to recall a name than an IP with 12 digits. We just need to configure a custom <em>DNS record of type A</em>. See below my own configuration:</li></ol><ul><li><strong>Hostname</strong>: k8s.ivancorrales.com</li><li><strong>Type</strong>: A</li><li><strong>TTL</strong>: 1h</li><li><strong>Data</strong>: 173.249.xxx.xxx (The public IP of your server)</li></ul><p>Once you have completed the above steps you should be able to login into the remote machine as below:</p><pre>ssh &lt;user&gt;@subdomain.domain (-i path_to_private_key)<br># You don&#39;t need to pass the arg -i when using <br># the default key (~/.ssh/id_rsa)<br><br># ssh icorrales@k8s.ivancorrales.com - </pre><h3>Install minikube on the remote machine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*Mtc1LCEztlbA7UXT.jpeg" /></figure><p>Follow the installation guide <a href="https://minikube.sigs.k8s.io/docs/start/">https://minikube.sigs.k8s.io/docs/start/</a></p><p>Let’s create our first cluster as shown below [<strong>replace k8s.ivancorrales.com with the name of your own server]</strong></p><pre>minikube start --memory 8192 --cpus 4  \<br>  --insecure-registry=&quot;k8s.ivancorrales.com:5000&quot;</pre><blockquote>We will launch a private docker registry to push our docker images, which will be deployed onto our k8s cluster. That’s the reason why we pass the flag --insecure-registry</blockquote><p>Let’s install the addon registry</p><pre>minikube addons enable registry</pre><p>We will use the registry addons to set up our private docker registry that will host the docker images that will be deployed in our k8s cluster.</p><p>Once minikube is running we can check the status of our cluster with minikube status.</p><pre>minikube status<br><br>minikube<br>type: Control Plane<br>host: Running<br>kubelet: Running<br>apiserver: Running<br>kubeconfig: Configured</pre><h3>Install kubectl on both remote machines &amp; local machine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*kou6cf2krBQA7Uu0.png" /></figure><p>Follow the instructions at <a href="https://kubernetes.io/docs/tasks/tools/">https://kubernetes.io/docs/tasks/tools/</a></p><h3>SSH Tunneling</h3><p>To minimize risks and avoid security risks we try to expose a less number of ports to the rest of the world. Therefore, we will use our ssh connection to create a tunnel to communicate with our k8s cluster that is running on the remote machine. From a simplistic point of view, we can sum up that a tunnel allows us to establish the connections that we could do from the remote machine.</p><p>If we run minikube with the docker driver (default behavior) we can run the command docker ps to verify the ports that are exposed from the container.</p><pre>127.0.0.1:49212-&gt;22/tcp, <br>127.0.0.1:49211-&gt;2376/tcp, <br>127.0.0.1:49210-&gt;5000/tcp, <br>127.0.0.1:49209-&gt;8443/tcp,  # API Endpoint<br>127.0.0.1:49208-&gt;32443/tcp</pre><p>To figure the cluster IP out we just need to run the following:</p><pre>&gt;&gt; minikube ip<br>192.168.49.2</pre><p>In this tutorial, we will exclusively focus on the port 8443 , the one that is used by the tools to communicate with a k8s cluster via API.</p><p>So we need to work out how to communicate with the private IP 192.168.49.2 on port 8443 from our local machine.</p><p>The following command creates a tunnel that enables us to access ports 8443 ( k8s API ) through port 18443 in our local machine</p><pre>ssh -N -p 22 icorrales@k8s.ivancorrales.com \<br> -L 18443:192.168.49.2:8443 # k8s cluster</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ziav4PIBsChO9fVYbHkZEw.png" /></figure><p>If we open <a href="https://localhost:18443/">https://localhost:18443</a> on our browser we will see a forbidden error message (Don’t panic, that error makes sense since this communication must be established using the certificates that we will download from the remote server in the following step.</p><p>The following image represents how the communication is established from our local machine to the k8s cluster through the tunnel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbAwaRfhgqZuJb0BkZ2h3w.png" /></figure><h3>Set the k8s cluster connection</h3><p>In our local machine, we need to edit the config file in path <strong>~/.kube/config</strong></p><ul><li>First of all, we need to download the minikube cluster certificates from the remote machines to our local machine. We can use thescp command to copy the certificates from the server to our local machine. [Replace the values with tour our username and server name]</li></ul><pre>mkdir -p ~/k8s.ivancorrales.com<br>cd ~/k8s.ivancorrales.com<br>scp icorrales@k8s.ivancorrales.com:/home/icorrales/.minikube/ca.crt .<br>scp icorrales@k8s.ivancorrales.com:/home/icorrales/.minikube/profiles/minikube/client.crt .<br>scp icorrales@k8s.ivancorrales.com:/home/icorrales/.minikube/profiles/minikube/client.key .</pre><ul><li>Secondly, we need to add the k8s configuration in the file <strong>~/.kube/config</strong>. This file is used to manage different k8s clustered, so you could have already defined others. Let’s see only the</li></ul><pre># This file continas 3 blocks: cluster , contexts and user..<br>apiVersion: v1<br>clusters:<br> - cluster:<br>      # Path to the ca.crt downloaded previously from the server<br>      certificate-authority: /Users/icorrales/k8s.ivancorrales.com/ca.crt<br>      # Port open in out local machine thorugh the tunnel<br>      server: https://127.0.0.1:18443<br>    name: k8s.ivancorrales.com<br>contexts:<br>  - context:<br>      # The value of the property cluster must match <br>      # one of the defined users in the above block clusters<br>      cluster: k8s.ivancorrales.com<br>      namespace: default<br>      # The value of the property user must match <br>      # one of the defined users in the below block users<br>      user: admin@k8s.ivancorrales.com<br>    name: minikube@k8s.ivancorrales.com<br># Default context<br>current-context: minikube@k8s.ivancorrales.com<br>kind: Config<br>preferences: {}<br>users:<br>  - name: admin@k8s.ivancorrales.com<br>    user:<br>      # Path to the client.crt downloaded previously from the server<br>      client-certificate: /Users/icorrales/k8s.ivancorrales.com/client.crt<br>      # Path to the client.key downloaded previously from the server<br>      client-key:  /Users/icorrales/k8s.ivancorrales.com/client.key<br><br></pre><p>Assuming that we have defined the value of. current-context with the new context that we have defined, we can verify that everything is correctly configured using the kubectl tool that we previously installed on our machine.</p><pre>&gt;&gt; kubectl cluster-info<br>Kubernetes control plane is running at https://127.0.0.1:18443<br>CoreDNS is running at https://127.0.0.1:18443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy</pre><h3>Admin the cluster remotely</h3><p>Now that we have correctly created the communication we can manage our k8s cluster from our local machine.</p><p><em>For instance, we can create a namespace in our cluster</em></p><pre>&gt;&gt; kubectl create namespace demo<br>namespace/demo created<br>&gt;&gt; kubectl delete namespace demo<br>namespace &quot;demo&quot; deleted</pre><h3>Dashboard</h3><p>To launch the k8s dashboard we need to run the below command from the remote machine</p><pre># From remote machine<br>minikube dashboard</pre><p>and launch a proxy from the local machine</p><pre># local machine<br>kubectl proxy --address=&#39;0.0.0.0&#39; --disable-filter=true<br>....<br>Starting to serve on [::]:8001<br>....</pre><p>The address <a href="http://localhost:8001/">http://localhost:8001/</a> displays the different endpoints that we navigate to</p><pre>{<br>  &quot;paths&quot;: [<br>    &quot;/.well-known/openid-configuration&quot;,<br>    &quot;/api&quot;,<br>    &quot;/api/v1&quot;,<br>    &quot;/apis&quot;,<br>    .....<br>   ]<br>}</pre><p>The dashboard can be accessed by clicking on the link <a href="http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/">http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/</a></p><h3>Publish a docker image</h3><h4>Build a Docker image</h4><p>At the beginning of this article, we enabled the addon registry</p><p>Let’s tag any docker image that we want to display in the k8s cluster. Alternatively, you could use the docker ivancorrales/hello-world:tutorial that launch an HTTP server on port 3030 that displays hello world! when you access to /</p><p>We need to <strong>tag the image</strong> to be hosted in our Docker registry.</p><pre>docker tag ivancorrales/hello-world:tutorial \<br>  k8s.ivancorrales.com:5000/hello-world:0.0.1</pre><h4>Check the docker registry logs</h4><p>The docker registry is a docker container that runs in the namespace kube-system . We can check the logs as shown below</p><pre>kubectl logs --namespace kube-system service/registry -f</pre><h4>Make the Docker registry accessible from your local machine</h4><p>Run the following command from the remote machine</p><pre>kubectl port-forward --namespace kube-system service/registry 5000:80 \<br>  --address 0.0.0.0</pre><p>Let’s open the following URL (don’t forget to replace k8s.ivancorrales.com with your own subdomain) <a href="http://k8s.ivancorrales.com:5000/v2/_catalog">http://k8s.ivancorrales.com:5000/v2/_catalog</a> and we can check the response from the registry</p><pre>{&quot;repositories&quot;:[]}</pre><p>Before pushing any docker image we need to add the URL k8s.ivancorrales.com:5000 as an insecure registry in our docker configuration.</p><pre>{<br>  <br>  &quot;insecure-registries&quot;: [<br>    &quot;k8s.ivancorrales.com:5000&quot;<br>  ]<br>}</pre><h4>Publish the docker image</h4><p>We can publish the Docker image that we created previously.</p><pre>docker push k8s.ivancorrales.com:5000/hello-world:0.0.1</pre><h3>Install our service with Helm</h3><p>To complete this tutorial we will use Helm to deploy an application.</p><h4>Install Helm in tour local machine</h4><p>Follow the instructions here, <a href="https://helm.sh/docs/intro/install/">https://helm.sh/docs/intro/install/</a></p><h4>Write your Helm Chart</h4><p>Learning to write a Helm Chart is out of the scope of this tutorial, so you can clone <a href="https://github.com/ivancorrales/k8s-remote-tutorial">this repository</a> and replace the values in the variables with the ones that work for you. The Chart is under folder hello-world</p><h4>Install the application</h4><p>If you decided to clone the repository, from the root directory you just need to run</p><pre>helm install my-hello-worl-app hello-world --namespace minikube-demo \<br>  --create-namespace --debug</pre><p>and check that the chart was installed correctly.</p><pre>&gt;&gt; helm  list --namespace minikube-demo<br>...<br>&gt;&gt; kubectl logs deployment/myapp-deployment --namespace minikube-demo <br>&gt; docker-hello-world@1.0.0 start<br>&gt; node index.js<br><br>Listening on port 3030</pre><h4>Check the service</h4><p>We just need to port-forwarding the deployment port from our local machine</p><pre>kubectl port-forward deployment/myapp-deployment \<br>  --namespace minikube-demo 3030:3030</pre><p>So let’s open <a href="http://localhost:3030/">http://localhost:3030</a> to check our beautiful hello world!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*ffmvgN2nRjAui8d-umFkaw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c776496ceb08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the right programming language]]></title>
            <link>https://ivan-corrales-solera.medium.com/choosing-the-right-programming-language-2d7a80033945?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7a80033945</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-language-2022]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 16:27:18 GMT</pubDate>
            <atom:updated>2022-09-06T16:27:18.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aJXr40ysbvt8Bosp.jpg" /></figure><p>There’s not a silver bullet to state the properest programming language for each project. On the other hand, there are some languages that will provide a better solution for specific problems.</p><blockquote>There may be multiple programming languages right for each project, but there’s only a single right way to build Software though.</blockquote><h3>Common approaches</h3><p>In my over 15 years of career, I’ve been fortunate to work with a bunch of programming languages and also play with others else in my side projects. Most companies follow one of the following approaches:</p><ul><li>Same language for all the projects</li><li>Freedom to choose the language for each project.</li></ul><p>Regarding these two approaches, I consider that It’s important understand both the pros and cons of both of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*t4BNz8wD7sljiZWP.jpg" /></figure><h4>Same language for all the projects</h4><p><strong>pros</strong></p><ul><li>Re-usable code through the usage of core libraries.</li><li>Generic CI / CD pipelines and testing strategies.</li></ul><p><strong>cons</strong></p><ul><li>Software lovers don’t have fun. As a consequence of this, some of them could leave the project after a few months or years.</li><li>Sometimes, the language is a really bad fit for the project that needs to be built.</li><li>Usually, this decision is taken by people in a leadership role who are not up-to-date and they are not in line with the leading edge technologies.</li></ul><h4>Freedom to choose the language for each project</h4><p><strong>pros</strong></p><ul><li>The people in your team will have more fun, especially those people who love coding.</li><li>Team members are more committed since they develop an ownership feeling over the projects and the company.</li></ul><p><strong>cons</strong></p><ul><li>Code is harder to maintain. The possibility to homogenize practices and the code is almost impossible.</li><li>CI (continuous integration) and CD (continuous deployment) pipelines become complex and harder to follow.</li><li>There is no possibility to reuse code or share core libraries between projects.</li></ul><h3>Choosing the right (or discarding the wrong) language for each project</h3><p>There are some factors or requirements that must be having into account to choose the right language for each project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZaJDB0GiRv5d-Yx5.jpg" /></figure><h4>Technical requirements</h4><p>There are some technical requirements or architectural concerns that will determine whether one programming language fits better our project or not. Let’s go through some examples below:</p><p><strong>Technical requirements</strong></p><ul><li><strong>Performance: </strong>Sometimes improving the performance of a product is a MUST and not only a NICE TO HAVE. In my humble opinion, the best strategy is to write some PoC’s (proof of concepts) to figure out the language that performs best.</li><li><strong>Integrations:</strong> We need to integrate an external library. For instance, let’s imagine that we need to use a Graphical component that is written in C. Or we need to implement a new module for an existing database engine.</li></ul><p><strong>Architectural concerns</strong></p><ul><li><strong>GraphQL API</strong>: I would bet on NodeJS on the backend side. I have built GraphQL API’s with NodeJS, Java, Go, and Python, and even though there is a wide range of languages that can be used to do it, I consider that NodeJS is the right candidate.</li><li><strong>Artificial Intelligence (AI) and Data projects: </strong>Python is the right candidate when we need to work with big matrixes and make calculus with them. As a consequence of this, most AI libraries are implemented with Python.</li><li><strong>Web assembly: </strong>We can use several languages to build web assembly components, but Rust is meant to be the best one for this kind of project though.</li></ul><h4>Non-Technical requirements</h4><p>Apart from the technical requirements, we must take into account anon-technical ones. I will enum a few of them:</p><ul><li>The skills of the people in our team and the learning curve to introduce a new language. We could consider Scala, Kotlin, or even Dart If our team is experienced working with Java but It will be harder if the people in our team are used to coding with non-typed languages such as NodeJS or Python.</li><li>The budget to increase headcount. The cost of hiring specialists will vary depending on the programming language. For instance, hiring specialists in Java will be less expensive than hiring specialists in Elixir or. Rust</li><li>The maturity of the language and the activity of the community around the language on the Internet. This could not be a handicap for R&amp;D (research and development) teams but It will be for sure for those small teams with a limited budget working on projects with an agred go-live date.</li></ul><h3>What really matters</h3><p>Apart from the above-pointed requirements and factors, I will enum the point that really matters to me to decide which programming language I will use for my next project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*B74jHaCUKzT6AP3M.png" /></figure><ul><li>The code that we write can be run and tested locally.</li><li>There’re good linters for the chosen programming language. There are guidelines of best practices and we follow them.</li><li>There’s a big or growing community tsupporting the programming language.</li><li>We chose the programming language that best fits the architecture and not the opposite.</li><li>We can quickly perform upgrades of the language compiler or apply new releases with security patches.</li><li>We can rely on the existing CI pipelines for projects that are built with this language.</li></ul><p>Do you have a project in your mind and you need to outsource someone to build it? Or, do you need someone to lead the project? Don’t hesitate to contact me. You can reach me at <a href="/service/mailto:hello@ivancorrales.com">hello@ivancorrales.com</a>. Additionally, you could find more info about my services at <a href="https://www.ivancorrales.com/">https://www.ivancorrales.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7a80033945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webassembly: Running Go code in the browser.]]></title>
            <link>https://itnext.io/webassembly-running-go-code-in-the-browser-916d87456e5f?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/916d87456e5f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 05:55:04 GMT</pubDate>
            <atom:updated>2022-04-30T06:07:51.666Z</atom:updated>
            <content:encoded><![CDATA[<p>Webassembly (WASM) is one of the most disruptive technologies at this moment. WASM enables us to run programs in the browser that was written in programming languages not supported by the own browser. We can do it because some programming languages can be compiled into WASM and WASM is supported by all the browsers.</p><blockquote>For instance, we can write Rust or Go code and execute it as we do with Javascript.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zgmF61ZC8PPkqXgn.png" /><figcaption>Image source<a href="https://tecnologiandroid.com/que-es-webassembly-wasm/">https://tecnologiandroid.com/que-es-webassembly-wasm/</a></figcaption></figure><p>The most common uses of WASM are:</p><ul><li>Images optimization compression.</li><li>Harvest old code that was written in the past and bring it into the modern web world.</li><li>Encryption.</li><li>Game development.</li></ul><h3>WASM vs Javascript</h3><h4>Performance</h4><p>The main difference with Javascript (JS) is that <strong>JS is a dynamic language</strong>. It means that the process to execute a piece of JS on a browser looks like the below:</p><ol><li>The browser pulls down the JS from the server</li><li>It starts parsing all the JS</li><li>It converts the downloaded JS code into abstract syntax trees.</li><li>It does a sort of compilation into bytecode.</li></ol><p>On the other hand, <strong>WASM is a static language </strong>and the code that is executed has been compiled in advance so we just need to pull down the WASM</p><h4>Interoperability</h4><p>The usage of WAS becomes very interoperable. We can write code in both JS and WAS and then we can make calls between pieces of code written in a different language.</p><blockquote>WAS code can call JS functions and vice-versa, JS code can call WAS functions.</blockquote><h3>Learning by doing</h3><p>In this tutorial, we will learn to compile Go code to WASM and execute it in the browser.</p><p>We will learn to implement a JSON Beautifier Online service. This service will be implemented in Go and It will be executed in the Browser. (It sounds great, doesn’t it?)</p><p>Trying to implement the full problem from scratch could be hard to follow it. Thus, we will go step by step through different examples before doing the final solution.</p><h3>Prerequisites</h3><ul><li>Let’s clone the code</li></ul><pre>&gt; git clone <a href="/service/mailto:git@github.com">git@github.com</a>:ivancorrales/wasm-tutorial-go.git<br>&gt; cd wasm-tutorial-go</pre><p>The only Software that you need to have installed on your computer is <a href="https://www.docker.com/">Docker</a> Don’t worry If you don’t have the Go compiler in your system, we will take advantage of Docker.</p><h4>The code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*SdH6-HgyZJubufS9CO4pGQ.png" /><figcaption>Code organization for this tutorial</figcaption></figure><p>The tutorial is composed of 7 steps. That’s the reason why you will find 7 HTML files at the root of the repository (sample[N].html, N=1…7) and 7 subfolders under wasm. The folders under wasm contain the Go code that will be compiled to WASM.</p><p>At the root of the repository, you will find a styles.css (commons CSS styles used in the different samples), load_wasm.js (this file is used to import the files compiled to wasm format) and, main.go which is a program used to serve static content (the HTML pages).</p><p>We will use the multistage Dockerfile at the root of the repository to build and run the samples. Although we’re not going to explain how this Docker works, feel free to reach me If you have any questions or suggestions.</p><h4>STEP 0 — Launch the server</h4><p>Execute the below commands to create the docker image and make it run. This will launch a static server on port 3000. If this port is busy, you just need to update the mapped port in the Makefile</p><pre>&gt; make build<br>&gt; make run</pre><h4>STEP 1 — Sending messages to the output console</h4><p>This is the most basic scenario. We will write a message in Go that will be sent to the output console in the browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fceee3dcd89c446e7cece0919dbdd67/href">https://medium.com/media/6fceee3dcd89c446e7cece0919dbdd67/href</a></iframe><p>This code is <a href="https://github.com/ivancorrales/wasm-tutorial-go/blob/main/Dockerfile#L5">compiled</a> into a WASM file and loaded from the <a href="https://github.com/ivancorrales/wasm-tutorial-go/blob/main/sample1.html#L11-L18">HTML page </a>as It’s shown below. The way that we import the WASM file will be exactly the same for all the samples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5c3776895f8dd8954ca4a5d32f16ea7/href">https://medium.com/media/d5c3776895f8dd8954ca4a5d32f16ea7/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample1.html">http://127.0.0.1:3000/sample1.html</a> to check the sample 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tdw72B5OXNmYGarUy_rm-g.png" /><figcaption>Webassembly tutorial- Sample 1</figcaption></figure><p>If we open the Dev Tools in the browser we will see the message “Hello my friend” that was printed in the main.go file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*0COxU_yfNPRsNU_8YhTIWw.png" /><figcaption>Webassembly tutorial- Sample 1 , Dev Tools</figcaption></figure><h4>STEP 2— Modifying the HTML</h4><p>In this step, we will learn to modify the content of the page from Go. What we‘ll do is to add text to the page dynamically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d95c1aa4ff9763447b48a1b3dee1f3/href">https://medium.com/media/48d95c1aa4ff9763447b48a1b3dee1f3/href</a></iframe><p>In this case, we have an empty H2 element, whose content will be populated from the Go code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1531349bc0ef65a1d8a91718966a455d/href">https://medium.com/media/1531349bc0ef65a1d8a91718966a455d/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample2.html">http://127.0.0.1:3000/sample2.html </a>to check the sample 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*JOr5u_ZMYopRTxPTzsz3-Q.png" /><figcaption>Webassembly tutorial- Sample 2</figcaption></figure><h4>STEP 3— Appending HTML elements</h4><p>In the previous step, we learned to modify the value of an HTML element. In this one, we will learn to create a new element.</p><p>Instead of populating the value for the element H”, we will create the element from the Go code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f1d31a2117494ee45b81d22769b759/href">https://medium.com/media/e2f1d31a2117494ee45b81d22769b759/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58ec8f4ce83ddd22489a5b878961e2cc/href">https://medium.com/media/58ec8f4ce83ddd22489a5b878961e2cc/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample3.html">http://127.0.0.1:3000/sample3.html </a>to check the sample 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exPmxJOFykxTFY8oRmvcJA.png" /><figcaption>Webassembly tutorial- Sample 3</figcaption></figure><h4>STEP 4— Modifying the classes of an HTML element</h4><p>We will learn to change the class of an HTML element. We do both removing and adding new classes to the HTML element. This step will update the class of an H3 element every 2 seconds.</p><p>We will replace the class of the element with the id simpleText</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d84135cffee6f117703fe6feb41ad97/href">https://medium.com/media/7d84135cffee6f117703fe6feb41ad97/href</a></iframe><p>The class of the H2 will be changed every 2 seconds from .green to .pink and vice-versa.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1daf28ab025c8407503a4bca0a0ce018/href">https://medium.com/media/1daf28ab025c8407503a4bca0a0ce018/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample4.html">http://127.0.0.1:3000/sample4.html </a>to check the sample 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*q-MPkHFkhoYinjTsJuB8cA.gif" /></figure><h4>STEP 5— Modifying properties of the HTML elements</h4><p>This step could look similar to the previous one, but they’re completely different each other. In this step will be interacting with the properties of the HTML elements. Concretely, we will modifying the style property of an H2. We will update the display value from block to none and vice-versa. This will make that the text, in the H2 element, blinks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/968530844392b3359e1f2be62f51a83b/href">https://medium.com/media/968530844392b3359e1f2be62f51a83b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44a4154401a759367657924223a9971a/href">https://medium.com/media/44a4154401a759367657924223a9971a/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample5.html">http://127.0.0.1:3000/sample5.html</a> to check the sample 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*km9nB5K6xjJ_0emZ_Om7YQ.gif" /></figure><h4>STEP 6 — Reading the HTML content from Go</h4><p>We will learn to read the content of the text of an H2 element, then we will convert the text to uppercase and finally we will display the converted text in the page.</p><p>The text in the HTML element with id description will be uppercased and displayed in element with id descriptionUppercase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d265398c5d5bebddf3087804a35e77c1/href">https://medium.com/media/d265398c5d5bebddf3087804a35e77c1/href</a></iframe><p>The code in Go is not rocket science as you can see below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43501befba9fb2f2536816c7f93ff0cb/href">https://medium.com/media/43501befba9fb2f2536816c7f93ff0cb/href</a></iframe><p>Visit the URL <a href="http://127.0.0.1:3000/sample6.html">http://127.0.0.1:3000/sample6.html</a> to check the sample 6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*YS7ybPir4rrxuto8QlFTrA.png" /></figure><h4>STEP 7— Final step</h4><p>We already have all the required knowledges to write, in Go, our own JSON Beautifier Online service.and make it run in the browser.</p><p>Our page will contain two textarea fields, one with the input text and the second one will display the text in a pretty mode. We will play with the HTML events onblur and onfocus to apply some styles to the input textarea field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be98c6f60dbeed64d1e9334d208b340/href">https://medium.com/media/9be98c6f60dbeed64d1e9334d208b340/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f89933f8282aab404b0520e0df15dc15/href">https://medium.com/media/f89933f8282aab404b0520e0df15dc15/href</a></iframe><ul><li>Line 11: This is the way to open an alert from Go.</li><li>Line 45: We will display the error in the Dev Tools of the browser.</li><li>Lines 57–58: The first value in function Set will be name used to register our Global function.</li></ul><p>Visit the URL<a href="http://127.0.0.1:3000/sample7.html"> http://127.0.0.1:3000/sample7.html</a> to play with our JSON Beautifier online service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*F5CsbHn9zPQmKH2ktLYnkQ.gif" /></figure><blockquote>I hope you enjoyed the tutorial as much as I did writing it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916d87456e5f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/webassembly-running-go-code-in-the-browser-916d87456e5f">Webassembly: Running Go code in the browser.</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own DSL with Go & HCL]]></title>
            <link>https://blog.devgenius.io/build-your-own-dsl-with-go-hcl-602c92ce24c0?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/602c92ce24c0</guid>
            <category><![CDATA[hashicorp]]></category>
            <category><![CDATA[automation-tools]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[dsl]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 20:23:53 GMT</pubDate>
            <atom:updated>2022-03-04T11:55:15.245Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>DSL stands for Domain Specific Language</blockquote><p>The main goal of tools such as Kubernetes, Docker compose, Jenkins CI, Gitlab CI, or Ansible, among others, is that their behavior can be customized by configuration. They‘re like a black box that depending on the input (YAML/JSON descriptors), will generate different output.</p><p>Other tools which belong to HashiCorp, such as Terraform, Vault, or Nomad use HCL instead of YAML and JSON. <strong>HCL stands for HashiCorp Configuration Language</strong> and It’s <strong>more powerful than JSON or YAML</strong> because It provides mechanisms. to implement dynamic configuration files as we will see it later. Some of the advantages of HCL are enum below:</p><ul><li>It is easy to read (and to write) even for non-technical people.</li><li>Implementing a custom DSL, as we will do, is not rocket science because parsing, validation, and plenty of things are provided out of the box.</li><li>A bunch of existing functions are already provided.</li><li>A well-known corporation like HashiCorp is under this project and great products such Terraform, Nomad and Vault use HCL. That implies that the Ops community is used to working with this syntax.</li></ul><p>On the other hand, to implement a custom DSL based on HCL you will be <strong>required to have knowledge of Go.</strong> But I assume that If you’re reading this article you have the required knowledge.</p><h3>How does HCL look?</h3><p>The three columns in the figure-1 represent the same information. This is an example of K8s configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9H6KCFSZZgSzbZE8gIjHA.png" /><figcaption>Figure 1 — The same K8s configuration in HCL, JSON. and YAML</figcaption></figure><p>After looking at figure 1, we can establish that the best syntax is the one provided by YAML because this file is the shortest one. But… keep in mind that the K8s is a dynamic tool but its configuration is static. What I mean is that the configuration of Kubernetes needs to be written in a very specific format and there’s no margin to create dynamic configurations.</p><h3>HCL by example</h3><p>I thought that a good showcase would be a DSL used to define the Continuous Integration (CI) or Continuous Deployment pipelines. Let’s see the following HCL script.</p><p>example.hcl</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*blmkHH7PAFWhWVWRMjOoig.png" /><figcaption>Figure 2 — Example of usage of our DSL</figcaption></figure><p>Even though you haven’t seen this DSL before, you suppose the purpose of this script, right? The pipeline contains a couple of jobs: The first one seems to run a Python script and the second one seems to run a Python script and later It sends a notification via Slack. There are certain parts in an HCL script that we must identify. The intention of figure 3 is to help us to identify these parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsLZE_oK8DK-i3tqebUpZA.png" /><figcaption>Figure 3¡Identification of parts in a HCL script</figcaption></figure><ul><li><strong>Vars:</strong> The variables are included in the HCL context. The HCL context is used to evaluate the value of other variables and the value of the attributes in a block.</li><li><strong>Blocks: </strong>A block is composed of a name (required), labels (optional), attributes(optional), and subblocks (optional).</li><li><strong>Attributes: </strong>There are optional and required attributes and they’re always defined inside of a block.</li><li><strong>(Custom) function:</strong> A function enables us to assign the result of a programmatic operation to a variable. Although there are already several functions provided by default and we learn how to implement new ones.</li></ul><p>In regard to the DSL of our example, we can state the following:</p><ul><li>There are 3 blocks: job , python and slack</li><li>The block job can contain subblocks of type python and slack .</li><li>The block job has two labels: The first label is used to define the name of the job and the second one to add a brief description.</li><li>The block python has only one label that is the name of the python script to be executed.</li><li>The block python has an optional attribute root_dir .</li><li>The block slack has 2 attributes: channel and message .</li></ul><h3>Coding</h3><p>First of all, we need to define the HCL schemas that match our desired DSL. We will follow a bottom-up approach. That means that we will start with the blocks that don’t contain other subblocks. For each block, we need to define the block ID (the name of the block), an array with the labels, and the BodySchema (the attributes and the blocks that can contain)</p><h4>dsl/schema.go</h4><p><a href="https://github.com/ivancorrales/hcl-by-example/blob/main/dsl/schema.go">Source code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*7HHQaH6XovOoi66gRFPtfg.png" /><figcaption>Figure 4 — Schema definition for the blocks</figcaption></figure><p>The HCL definitions are used to parser the input file to internal HCL structures (generic structures) and They will be used to validate the parsed files.</p><p>Don’t forget about the random(10) function that appears in the example above. The implementation of this function is shown in figure 5.</p><h4>dsl/functions.go</h4><p><a href="https://github.com/ivancorrales/hcl-by-example/blob/main/dsl/functions.go">Source code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*6soMZZdGYVwh54oS1J3YNg.png" /><figcaption>Figure 5— Implementation of a custom function, random(int)</figcaption></figure><p>Visit <a href="https://github.com/wesovilabs/orion/tree/master/functions">this link</a> If you want to see more implementations of custom functions. I created a few ones when I built <a href="https://wesovilabs.github.io/orion/spec/actions/print/">Orion</a>.</p><p>We just defined the schemas (HCL structs), but we should model our own DSL into a more friendly structure. Moreover, we want to execute the content in the scripts and not only parse them. Looking at the following code in figure 6, you will realize that all the structs implement a method with the following signature Run(*hcl.context) error. The executions of the scripts will follow a top-down approach. The reason why there’s an interface Step is that we need to keep the order of the steps in the block job (It can contain python and slack`)</p><h4>dsl/model.go</h4><p><a href="https://github.com/ivancorrales/hcl-by-example/blob/main/dsl/model.go">Source code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*28TinsJUEwVGIUnVJmyAAw.png" /><figcaption>Figure 6 — Model implementation for the blocks</figcaption></figure><p>We are almost done, we just need to implement the code that will convert the HCL structure into our implementation.</p><h4>dsl/decoder.go</h4><p><a href="https://github.com/ivancorrales/hcl-by-example/blob/main/dsl/decoder.go">Source code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*p9AprtC2NuygD4AGZeP7gQ.png" /><figcaption>Figure 7— Decoder for the root file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*W-N6LTQKO6f7-K2ymK8MgQ.png" /><figcaption>Figure 8 — Decoder for blocks job, python and slack</figcaption></figure><p>To run the code, we can implement a basic main function as It’s shown in the figure 9.</p><h4>main.go</h4><p><a href="https://github.com/ivancorrales/hcl-by-example/blob/main/main.go">Source code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*EaGsyVHVc8f0MQMr1SDdeQ.png" /><figcaption>Figure 9 — main function</figcaption></figure><p>To run the example you just need to pass the example file.</p><blockquote>go run main.go</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNK2mya1YhYk2VartXjAwQ.png" /><figcaption>Figure 10 — Output of</figcaption></figure><p>There are several tools that take advantage of HCL but the point is that you can create your own DSL and build great things like Terraform or Nomad.</p><p>I also encourage you to have a look at <a href="https://github.com/wesovilabs/orion">Orion</a>. It’s a personal project that I created and I learned a lot about HCL.</p><p><a href="https://github.com/ivancorrales/hcl-by-example">The full code of this repository can be downloaded from Github</a></p><p><a href="https://github.com/ivancorrales/hcl-by-example">GitHub - ivancorrales/hcl-by-example</a></p><figure><a href="https://www.buymeacoffee.com/ivancorrales"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602c92ce24c0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/build-your-own-dsl-with-go-hcl-602c92ce24c0">Build your own DSL with Go &amp; HCL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BERT: Understanding the Null response threshold in QA systems]]></title>
            <link>https://ivan-corrales-solera.medium.com/bert-understanding-the-null-response-threshold-in-qa-systems-b6cf55a4b8ec?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6cf55a4b8ec</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 19:56:53 GMT</pubDate>
            <atom:updated>2022-02-03T04:13:33.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*qFl4k2SCosQmWTjb.jpeg" /></figure><p>Building a robust Questions Answering system (QA) implies that the system will provide an answer only when this can be found in the context. That means, that when we build a QA system we must consider two types of questions</p><ul><li>Questions with one (or more) valid answers (<strong>Positive questions)</strong></li><li>Questions with nonvalid answers (<strong>Negative questions)</strong></li></ul><blockquote>At times It’s better to say nothing than to say nonsense</blockquote><h4>Example: Positive &amp; Negative questions</h4><p>Let’s have a look at the following text</p><blockquote>“Maria Salomea Skłodowska, also known as Marie Curie, was the first woman to win a Nobel Prize, the first person and the only woman to win the Nobel Prize twice, and the only person to win the Nobel Prize in two scientific fields”</blockquote><p><strong>A) Positive question</strong></p><ul><li><strong>Question: </strong>who was the first person to win the Nobel Prize twice?</li><li><strong>Answers: </strong>There are two valid answers to the above question: “Maria Salomea Sklodowska” and “Marie Curie”.</li></ul><p><strong>B) Negative question</strong></p><ul><li><strong>Question: </strong>Who was the first man to win the Nobel Prize in two scientific fields?</li><li><strong>Answer: </strong>We don’t have enough information to answer the above question.</li></ul><h3>Make predictions</h3><p>The models based on BERT focused on QA tasks don’t predict the answer to a question but they provide a score for each possible answer.</p><p>Our challenge is to decide the prediction (or predictions) for a given question with a context. I say a challenge because not all the questions won’t be able to be answered.</p><h4>Tokenization</h4><p>First of all, we need to tokenize the question (and the context) as this will be the input data for our model. In the following example we will use the tokenizer deepset/roberta-base-squad2 , but feel free to take the one that you most like. Have a look at <a href="https://huggingface.co/models">https://huggingface.co/models</a>, to check the available models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UaT4jDbAIHHkD_lZZS_lQ.png" /></figure><p>The tokenizer function returns a dictionary. . By default, this dictionary contains two keys: attention_mask and input_ids . We could request other information but that’s out of the scope of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENtqVs3Bc8oKaRBarx-s7g.png" /></figure><p>I want you to have a look at the tokenized message above. Question and context are separated by a special token &lt;/s&gt; . It’s necessary to identify which part is the question and which one belongs to the context because the answer shouldn’t be taken from the own question. By the way, we can take advantage of the method `sequence_ids` to identify which token belongs to the question or (it’s represented with 0) or to the context (represented with 1) . The special characters ( &lt;s&gt; or &lt;/s&gt; are represented with None)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKwQVQRLkvNcnUd0If1htQ.png" /></figure><h4>Execute the model</h4><p>We can have a look at the available pre-trained models. This time is important we take a model that has been trained for doing Question Answering. Actually, the model that we’re using was trained with a dataset squadv2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXTz1jhUZvg8mY57Ltyspg.png" /></figure><p>To execute the model we only need to pass a couple of tensors (more parameters can be passed but they’re not required)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2v4cfK9NobDmuI7oyjtfzg.png" /></figure><p>The returned value from the model is a dictionary that contains two tensors: start_logits and end_logits .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvVPISrAVYVTPa6sRNmyLA.png" /></figure><p>These two tensors contain float values: positive and negative values. These values inform about the “probability” that the token, in the same position, is the first or the last token in the answer.</p><h4>Make the prediction</h4><p>It’s time to make the predictions and we already have all the needed information. So let’s enum the premises that we need to follow to make the prediction</p><ul><li>All the tokens in the answer must be extracted from the context but not from the question. They must be represented with a value 1 in the sequence_ids</li><li>The index of the last token in the answer must be greater than the index of the first token in the answer. The index in start_logits must be lower than the index in end_logits</li><li>The predicted answer should be the one with a higher score. The value of start_logits[start_index] + end_logits[end_index] must be the maximum possible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_gXMRsMdBy2gVXkE4ywiQ.png" /></figure><p>The variable predictions is a list that contains. all the possible combinations that match the above premises. The predictions are sorted by the score. Thus the prediction in position 0 will be one with the highest probability to be successful. However, the model could be able to obtain more than one valid answer… Let’s see the 5 predictions with the highest probability</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEWoToqFe9wmrKOkMf_dVQ.png" /></figure><p>Apparently, all the above questions could be correct… well we could discard the fifth in the ranking. Answers #2 and #3 could be considered the same. Actually, we will normalize them when we want to obtain the metrics.</p><p>We can create a function in Python to simplify the following examples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1KC85ILwkOcAAso0eV1wg.png" /></figure><p>So It looks great, we build a system able to make good predictions, but… What’s about negative questions?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv5Zz4IoqpThMp8mZiXsMQ.png" /></figure><p>Our system can answer any question, even though the question can’t be answered. You could have realized that the score, in this case, is negative and we could use that value as a threshold (The null response threshold) but sometimes our model will return positive scores for questions that don’t have a possible answer, for example, the below question…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uY79hRFq255J6bppiceE9w.png" /></figure><p>To sum up, we know that we need to establish a threshold. If we didn’t find any prediction with a score higher than <strong>the null response threshold</strong> our prediction would be that we can’t make a prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDn9885zjq44WDJYR_HHTw.png" /></figure><p>We add a new param in the function prediction. This value is the thresholdand It’s used to identify when an answer is not valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCCHcTfpL3TcJ2Mswdcw0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WLBTUsdPsdDH5BYI7YSfw.png" /></figure><p>I will publish a new article in which I will explain how to obtain the optimal threshold for the null responses.</p><p>The Notebook with the code can be found <a href="https://colab.research.google.com/drive/1KgE1oZRyf2J9XJ-SGRlIyP8IR8QFwDVn?usp=sharing">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6cf55a4b8ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers for Natural Language Processing (NLP)]]></title>
            <link>https://ivan-corrales-solera.medium.com/transformers-for-natural-language-processing-nlp-b5c47aee4d65?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5c47aee4d65</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 06:28:14 GMT</pubDate>
            <atom:updated>2021-11-03T06:28:14.175Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you’re an experienced Artificial Intelligence (AI) developer or you’re a newbie in this world, this post will provide you with the required knowledge to <strong>build your own Transformers implementations for resolving Natural Language Processing (NLP)</strong> challenges.</p><h3>Natural Language Processing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/0*g5bjNyS7RcR0H3OJ.png" /><figcaption>Figure 1: Natural Language Processing</figcaption></figure><p>Natural Language Processing (NLP) is one of the major fields in AI. NLP is not only a subfield of AI but also of linguistics and computer sciences. The NLP is concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data.</p><p>NLP provides mechanisms to solve a large number of challenges. For instance, Named Entity Recognition, text translation, sentiment analysis, text generation, question answering systems or documents classification among others.</p><blockquote>In this article, we will address a multi-label text classification problem.</blockquote><h3>What do the Transformers do?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sDt_gA8XS7EbxvU-.png" /><figcaption>Figure 2: Attention mechanism (Source: <a href="https://medium.com/deep-learning-with-keras/sequence-to-sequence-learning-c8be6cd34848">https://medium.com/deep-learning-with-keras/sequence-to-sequence-learning-c8be6cd34848</a> )</figcaption></figure><p>The transformers are a Deep Learning (DL) model that adopts the mechanism of attention. This mechanism was introduced in the paper <a href="https://arxiv.org/pdf/1706.03762.pdf">“Attention is all you need”</a> (Vaswani, Ashish &amp; Shazeer, Noam &amp; Parmar, Niki &amp; Uszkoreit, Jakob &amp; Jones, Llion &amp; Gomez, Aidan &amp; Kaiser, Lukasz &amp; Polosukhin, Illia. (2017))[1]. This paper supposed great improvements for the Transformers. In these years dozens of Transformers have emerged, being the most well-known GPT-2, GPT-3, or Bert. There are variants of these transformers, for instance, Beto provides a Bert implementation of the Spanish language.</p><blockquote>We will use Bert to implement our solution</blockquote><p>Before the emerging of Transformer, most of the models used in NLP were based on Recurrent Neural Networks (RNN). The usage of RNN’s was not really efficient in handling long sequences of text. These models tend to forget the content of the initial words of the text to make decisions.</p><p>Transformer avoids recursion by processing sentences as whole using attention mechanisms and positional embeddings.</p><h3>The architecture of Transformers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*5OLD03JwT2JihpAJ.jpeg" /><figcaption>Figure 3: The Transformer — Model architecture (Source: <a href="https://arxiv.org/abs/1706.03762)">https://arxiv.org/abs/1706.03762)</a></figcaption></figure><p>There are many articles on the Internet in which the architecture of Transformers is explained, thus I’m not going to spend time doing the same. See below a list of my favorite ones:</p><ul><li><a href="https://towardsdatascience.com/a-deep-dive-into-the-transformer-architecture-the-development-of-transformer-models-acbdf7ca34e0">A Deep Dive Into the Transformer Architecture — The Development of Transformer Models</a></li><li><a href="https://jalammar.github.io/illustrated-transformer/">The Illustrated Transformer</a></li><li><a href="https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/">How do Transformers Work in NLP? A Guide to the Latest State-of-the-Art Models</a></li></ul><h3>Showcase: Quotes classification</h3><p>As was mentioned above, we will take advantage of the Transformers for addressing a multilabel text classification problem.</p><p>In this post, we will use the dataset “Quotes Dataset”, provided by Amit Mittal. This dataset is hosted on <a href="https://www.kaggle.com/akmittal/quotes-dataset">https://www.kaggle.com/akmittal/quotes-dataset</a>. This is a &gt;22MB dataset in JSON format and each quote contains the author, the tags, popularity, and the category.</p><pre>{<br>  &quot;Quote&quot;: &quot;Don&#39;t cry because it&#39;s over, smile because it happened.&quot;,<br>  &quot;Author&quot;:&quot;Dr. Seuss&quot;,<br>  &quot;Tags&quot;:[ &quot;attributed-no-source&quot;,  &quot;cry&quot;,  &quot;crying&quot;, ...],<br>  &quot;Popularity&quot;: 0.15566615566615566,<br>  &quot;Category&quot;:&quot;life&quot;<br>}</pre><p>Our goal will be to predict the tags for a given quote, so we can omit the other attributes.</p><p>In our implementation, we will use <a href="https://pytorch.org/">PyTorch</a>. PyTorch is an open-source machine learning library based on the Torch library.</p><p>Next, we will go through the different parts of our Notebook. The full Notebook can be downloaded <a href="https://github.com/ivancorrales/colab-notebooks/blob/main/Quotes_classification.ipynb">here</a></p><h3>Install and import libraries</h3><p>Install the dependencies</p><pre>!pip install torch<br>!pip install numpy<br>!pip install pandas<br>!pip install matplotlib<br>!pip install seaborn<br>!pip install sklearn<br>!pip install transformers<br>!pip install pytorch-lightning</pre><p>Import requerided dependencies</p><pre><em># Import all libraries</em><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>re</strong><br><strong>import</strong> <strong>os</strong><br><br><em># Huggingface transformers</em><br><strong>import</strong> <strong>transformers</strong><br><strong>from</strong> <strong>transformers</strong> <strong>import</strong> BertModel,BertTokenizer,AdamW, get_linear_schedule_with_warmup<br><br><strong>import</strong> <strong>torch</strong><br><strong>from</strong> <strong>torch</strong> <strong>import</strong> nn ,cuda<br><strong>from</strong> <strong>torch.utils.data</strong> <strong>import</strong> DataLoader,Dataset,RandomSampler, SequentialSampler<br><br><strong>import</strong> <strong>pytorch_lightning</strong> <strong>as</strong> <strong>pl</strong><br><strong>from</strong> <strong>pytorch_lightning.callbacks</strong> <strong>import</strong> ModelCheckpoint<br><br><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> train_test_split<br><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> accuracy_score, precision_recall_fscore_support<br><br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>from</strong> <strong>pylab</strong> <strong>import</strong> rcParams<br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> rc<br>%matplotlib inline<br><br>is_gpu_available = torch.cuda.is_available()<br>device = torch.device(&quot;cuda:0&quot; <strong>if</strong> is_gpu_available <strong>else</strong> &quot;cpu&quot;)<br><strong>if</strong> is_gpu_available:<br>  !nvidia-smi</pre><h3>Download the dataset</h3><p>We will make use of a dataset that is hosted on Kaggle. We need to follow the steps below to download and use Kaggle data within Google Colab:</p><ol><li>Sign in to <a href="https://kaggle.com/">https://kaggle.com/</a>, then click on your profile picture on the top right and select “My Account” from the menu.</li><li>Scroll down to the “API” section and click “Create New API Token”. This will download a file kaggle.json.</li><li>Upload the downloaded kaggle.json file in the next cell.</li></ol><pre><em>&quot;&quot;&quot;The Kaggle dataset path&quot;&quot;&quot;</em><br>KAGGLE_DATASET =&#39;akmittal/quotes-dataset&#39;<br><br>!pip install -q kaggle<br><strong>from</strong> <strong>google.colab</strong> <strong>import</strong> files<br>files.upload()<br><br>!pip install -q kaggle<br>!mkdir -p ~/.kaggle<br>!mv kaggle.json ~/.kaggle/<br>!ls ~/.kaggle<br>!chmod 600 /root/.kaggle/kaggle.json<br>!kaggle datasets download &quot;<strong>{KAGGLE_DATASET}</strong>&quot;<br>!mkdir  /content/dataset<br>!unzip -q /content/quotes-dataset.zip -d /content/dataset<br>!ls /content/dataset</pre><h3>Load dataset</h3><p>Load the JSON file into a Pandas DataFrame</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><br>df = pd.read_json(&#39;/content/dataset/quotes.json&#39;)<br><em># Take only the required attributes and discard the others</em><br>df = df[[&#39;Quote&#39;,&#39;Tags&#39;]]<br><em># Drop the duplicates records into our dataset</em><br>df = df.drop_duplicates([&#39;Quote&#39;])<br>print(f&#39;The data frame contains <strong>{</strong>len(df)<strong>}</strong> records.&#39;)<br>df.head(6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*mwiBuxC-R85BBHSFritReQ.png" /></figure><h3>Normalize dataset</h3><p>In this step, we will normalize the tags (to lowercase, remove empty blanks). Additionally, we will work only with the 15 most used tags.</p><pre>df.Tags = df.Tags.transform(<strong>lambda</strong> tags: [tag.lower().strip() <strong>for</strong> tag <strong>in</strong> tags])<br><br>tags = [element <strong>for</strong> list_ <strong>in</strong> df.Tags <strong>for</strong> element <strong>in</strong> list_]<br>tags = [tag.lower().strip() <strong>for</strong> tag <strong>in</strong> tags]<br><br>print(f&#39;There are <strong>{</strong>len(tags)<strong>}</strong> tags.&#39;)</pre><pre># There are 215664 tags.</pre><p>As we can observe in the above cell, there are more than 200k tags. As this Notebook has mainly educational purposes we will discard the other tags and clean the dataset.</p><pre>classes = pd.Series(tags).value_counts()[:15].index<br>classes = list(set(classes))<br>classes.sort()<br>df[&#39;Tags&#39;] = df.Tags.transform(<strong>lambda</strong> tags: list(set(tags).intersection(classes)))<br>df = df[df.Tags.transform(<strong>lambda</strong> tags: len(tags)&gt;0)]<br><br>print(f&#39;We will only consider the following tags: <strong>{</strong>classes<strong>}</strong>.&#39;)<br>print(f&#39;The data frame contains <strong>{</strong>len(df)<strong>}</strong> records with one or more tags.&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*0mz-Xva-bpPd1qQBS9buOA.png" /></figure><p>To work on our multi-label tag classification we will convert the field ‘Tags’ (with arrays of tags) into 15 columns (one per tag) with binary values.</p><pre><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> MultiLabelBinarizer<br>mlb = MultiLabelBinarizer()<br>df = df.join(pd.DataFrame(mlb.fit_transform(df.pop(&#39;Tags&#39;)),<br>                          columns=mlb.classes_,<br>                          index=df.index))<br>df.head(n=6)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*WgeoMyxRywjGVskWXshSUA.png" /></figure><h3>Splitting dataset into train, test, and validation data</h3><p>We have more than 20k records in our data frame. Our intention is purely educational, so let’s take a subset with “only” 2k records to work with.</p><pre>df = df[:2000]</pre><p>70% of our records will be used for training the model and the other 30% will be distributed between test and validation.</p><pre>RANDOM_STATE = 167<br><br>train_data,temp_data = train_test_split(<br>    df,<br>    test_size=.3, <br>    random_state=RANDOM_STATE,<br>    shuffle=<strong>True</strong>,<br>)<br><br><br>test_data, val_data = train_test_split(<br>    temp_data, <br>    test_size=0.5, <br>    random_state=RANDOM_STATE, <br>    shuffle=<strong>True</strong>,<br>)<br>print(f&#39; - dataset for training model: <strong>{</strong>train_data.shape[0]<strong>}</strong>.&#39;)<br>print(f&#39; - dataset for validate trained model: <strong>{</strong>val_data.shape[0]<strong>}</strong>.&#39;)<br>print(f&#39; - dataset for test the model <strong>{</strong>test_data.shape[0]<strong>}</strong>.&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*ioxATG7p6VpDl7Rsni3z1A.png" /></figure><h3>Preparing the Dataset and DataModule</h3><pre><strong>class</strong> <strong>QuoteTagDataset</strong> (Dataset):<br>  <strong>def</strong> __init__(self, data, tokenizer, max_len):<br>      self.tokenizer = tokenizer<br>      self.data      = data<br>      self.max_len   = max_len<br>      <br>  <strong>def</strong> __len__(self):<br>      <strong>return</strong> len(self.data)<br>  <br>  <strong>def</strong> __getitem__(self, item_idx):<br>      item   = self.data.iloc[item_idx]<br>      quote  = item[&#39;Quote&#39;]<br>      labels = item[classes]<br><br>      inputs = self.tokenizer.encode_plus(<br>          quote,<br>          <strong>None</strong>,<br>          max_length= self.max_len,<br>          padding = &#39;max_length&#39;,<br>          add_special_tokens=<strong>True</strong>,<br>          return_token_type_ids= <strong>False</strong>,<br>          return_attention_mask= <strong>True</strong>,<br>          truncation=<strong>True</strong>,<br>          return_tensors = &#39;pt&#39;<br>        )<br>      <br>      input_ids = inputs[&#39;input_ids&#39;].flatten()<br>      attn_mask = inputs[&#39;attention_mask&#39;].flatten()<br>      <br>      <strong>return</strong> {<br>          &#39;input_ids&#39;: input_ids ,<br>          &#39;attention_mask&#39;: attn_mask,<br>          &#39;label&#39;: torch.tensor(labels, dtype=torch.float)    <br>      }</pre><pre><strong>class</strong> <strong>QuoteTagDataModule</strong> (pl.LightningDataModule):<br>    <br>    <strong>def</strong> __init__(self, train_data, val_data, test_data,tokenizer,train_batch_size=8, val_batch_size=8, test_batch_size=8, max_token_len=150):<br>        super().__init__()<br>        self.train_data = train_data<br>        self.test_data  = test_data<br>        self.val_data   = val_data<br>        self.tokenizer = tokenizer<br>        self.train_batch_size = train_batch_size<br>        self.test_batch_size = test_batch_size<br>        self.val_batch_size = val_batch_size<br>        self.max_token_len = max_token_len<br><br>    <strong>def</strong> setup(self):<br>        self.train_dataset = QuoteTagDataset(data=self.train_data, tokenizer=self.tokenizer,max_len = self.max_token_len)<br>        self.val_dataset  = QuoteTagDataset(data=self.val_data,tokenizer=self.tokenizer,max_len = self.max_token_len)<br>        self.test_dataset  = QuoteTagDataset(data=self.test_data,tokenizer=self.tokenizer,max_len = self.max_token_len)<br>        <br>        <br>    <strong>def</strong> train_dataloader(self):<br>        <strong>return</strong> DataLoader (self.train_dataset, batch_size = self.train_batch_size, shuffle = <strong>True</strong> , num_workers=0)<br><br>    <strong>def</strong> val_dataloader(self):<br>        <strong>return</strong> DataLoader (self.val_dataset,batch_size=self.val_batch_size)<br><br>    <strong>def</strong> test_dataloader(self):<br>        <strong>return</strong> DataLoader (self.test_dataset,batch_size=self.test_batch_size)</pre><pre><em># Initialize the Bert tokenizer</em><br>BERT_MODEL_NAME = &#39;bert-base-cased&#39;<br>Bert_tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_NAME)<br><br><em># Initialize the parameters that will be use for training</em><br>TRAIN_BATCH_SIZE = 8<br>TEST_BATCH_SIZE  = 8<br>VAL_BATCH_SIZE   = 8<br>MAX_LEN          = 128<br><br><em># Instantiate and set up the data_module</em><br>data_module = QuoteTagDataModule(train_data,val_data,test_data,Bert_tokenizer,TRAIN_BATCH_SIZE,VAL_BATCH_SIZE,TEST_BATCH_SIZE,MAX_LEN)<br>data_module.setup()</pre><h3>Train the Model</h3><pre><strong>class</strong> <strong>QuoteTagClassifier</strong>(pl.LightningModule):<br>    <br>    <strong>def</strong> __init__(self, n_classes=15, steps_per_epoch=<strong>None</strong>, n_epochs=3, lr=2e-5 ):<br>        super().__init__()<br><br>        self.bert = BertModel.from_pretrained(BERT_MODEL_NAME, return_dict=<strong>True</strong>)<br>        self.classifier = nn.Linear(self.bert.config.hidden_size,n_classes) <em># outputs = number of labels</em><br>        self.steps_per_epoch = steps_per_epoch<br>        self.n_epochs = n_epochs<br>        self.lr = lr<br>        self.criterion = nn.BCEWithLogitsLoss()<br>        <br>    <strong>def</strong> forward(self,input_ids, attn_mask):<br>        output = self.bert(input_ids = input_ids ,attention_mask = attn_mask)<br>        output = self.classifier(output.pooler_output)<br>        <strong>return</strong> output<br>    <br>    <br>    <strong>def</strong> training_step(self,batch,batch_idx):<br>        input_ids = batch[&#39;input_ids&#39;]<br>        attention_mask = batch[&#39;attention_mask&#39;]<br>        labels = batch[&#39;label&#39;]<br>        <br>        outputs = self(input_ids,attention_mask)<br>        loss = self.criterion(outputs,labels)<br>        self.log(&#39;train_loss&#39;,loss , prog_bar=<strong>True</strong>,logger=<strong>True</strong>)<br>        <br>        <strong>return</strong> {&quot;loss&quot; :loss, &quot;predictions&quot;:outputs, &quot;labels&quot;: labels }<br><br><br>    <strong>def</strong> validation_step(self,batch,batch_idx):<br>        input_ids = batch[&#39;input_ids&#39;]<br>        attention_mask = batch[&#39;attention_mask&#39;]<br>        labels = batch[&#39;label&#39;]<br>        <br>        outputs = self(input_ids,attention_mask)<br>        loss = self.criterion(outputs,labels)<br>        self.log(&#39;val_loss&#39;,loss , prog_bar=<strong>True</strong>,logger=<strong>True</strong>)<br>        <br>        <strong>return</strong> loss<br><br>    <strong>def</strong> test_step(self,batch,batch_idx):<br>        input_ids = batch[&#39;input_ids&#39;]<br>        attention_mask = batch[&#39;attention_mask&#39;]<br>        labels = batch[&#39;label&#39;]<br>        outputs = self(input_ids,attention_mask)<br>        loss = self.criterion(outputs,labels)<br>        self.log(&#39;test_loss&#39;,loss , prog_bar=<strong>True</strong>,logger=<strong>True</strong>)<br>        <strong>return</strong> loss<br>    <br>    <br>    <strong>def</strong> configure_optimizers(self):<br>        optimizer = AdamW(self.parameters() , lr=self.lr)<br>        warmup_steps = self.steps_per_epoch//3<br>        total_steps = self.steps_per_epoch * self.n_epochs - warmup_steps<br>        scheduler = get_linear_schedule_with_warmup(optimizer,warmup_steps,total_steps)<br>        <strong>return</strong> [optimizer], [scheduler]</pre><pre>N_EPOCHS   = 20<br>LR         = 2e-05<br>steps_per_epoch = len(train_data)//TRAIN_BATCH_SIZE<br><br>model = QuoteTagClassifier(n_classes=len(classes), steps_per_epoch=steps_per_epoch,n_epochs=N_EPOCHS,lr=LR)</pre><blockquote>This belos step could take long as It’s the part in which we train our model</blockquote><pre><em># Instantiate the Model Trainer</em><br>trainer = pl.Trainer(max_epochs = N_EPOCHS , gpus = 1, progress_bar_refresh_rate = 20)<br><em># Train the Classifier Model</em><br>trainer.fit(model, data_module)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*9_zuogNVruyXVFj7UrRDGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*jKzU4xbeCTwCkN8TAGknYg.png" /></figure><pre><em># Evaluate the model performance on the test dataset</em><br>trainer.test(model,datamodule=data_module)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*pB-CZ6nyQNvI_QCao2iGyQ.png" /></figure><h3>Evaluate Model Performance on Test Set</h3><pre><strong>from</strong> <strong>torch.utils.data</strong> <strong>import</strong> TensorDataset<br><br><em># Tokenize all quotes in test_data</em><br>input_ids = []<br>attention_masks = []<br><br><br><strong>for</strong> quote <strong>in</strong> test_data.Quote:<br>    encoded_quote =  Bert_tokenizer.encode_plus(<br>      quote,<br>      <strong>None</strong>,<br>      add_special_tokens=<strong>True</strong>,<br>      max_length= MAX_LEN,<br>      padding = &#39;max_length&#39;,<br>      return_token_type_ids= <strong>False</strong>,<br>      return_attention_mask= <strong>True</strong>,<br>      truncation=<strong>True</strong>,<br>      return_tensors = &#39;pt&#39;      <br>    )<br>    <br>    input_ids.append(encoded_quote[&#39;input_ids&#39;])<br>    attention_masks.append(encoded_quote[&#39;attention_mask&#39;])<br>    <br><em># Now convert the lists into tensors.</em><br>input_ids = torch.cat(input_ids, dim=0)<br>attention_masks = torch.cat(attention_masks, dim=0)<br>labels = torch.tensor(test_data[classes].values)<br><br><em># Create the DataLoader.</em><br>pred_data = TensorDataset(input_ids, attention_masks, labels)<br>pred_sampler = SequentialSampler(pred_data)<br>pred_dataloader = DataLoader(pred_data, sampler=pred_sampler, batch_size=TEST_BATCH_SIZE)</pre><pre>flat_pred_outs = 0<br>flat_true_labels = 0</pre><pre><em># Put model in evaluation mode</em><br>model = model.to(device) <em># moving model to cuda</em><br>model.eval()<br><br><em># Tracking variables </em><br>pred_outs, true_labels = [], []<br><em>#i=0</em><br><em># Predict </em><br><strong>for</strong> batch <strong>in</strong> pred_dataloader:<br>    <em># Add batch to GPU</em><br>    batch = tuple(t.to(device) <strong>for</strong> t <strong>in</strong> batch)<br>  <br>    <em># Unpack the inputs from our dataloader</em><br>    b_input_ids, b_attn_mask, b_labels = batch<br> <br>    <strong>with</strong> torch.no_grad():<br>        pred_out = model(b_input_ids,b_attn_mask)<br>        pred_out = torch.sigmoid(pred_out)<br>        pred_out = pred_out.detach().cpu().numpy()<br>        label_ids = b_labels.to(&#39;cpu&#39;).numpy()<br><br>    pred_outs.append(pred_out)<br>    true_labels.append(label_ids)</pre><pre>flat_pred_outs = np.concatenate(pred_outs, axis=0)<br>flat_true_labels = np.concatenate(true_labels, axis=0)</pre><h3>Predictions of Tags in the Test set</h3><p>First of all, we need to identify the threshold that performs the best for the test dataset</p><pre>threshold  = np.arange(0.4,0.51,0.01)<br>threshold</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*PtxGwQm1o37RzFPLoUjE9A.png" /></figure><p>Let’s define a function that takes a threshold value and uses it to convert probabilities into 1 or 0.</p><pre><em># convert probabilities into 0 or 1 based on a threshold value</em><br><strong>def</strong> classify(pred_prob,thresh):<br>    y_pred = []<br><br>    <strong>for</strong> tag_label_row <strong>in</strong> pred_prob:<br>        temp=[]<br>        <strong>for</strong> tag_label <strong>in</strong> tag_label_row:<br>            <strong>if</strong> tag_label &gt;= thresh:<br>                temp.append(1) <br>            <strong>else</strong>:<br>                temp.append(0)<br>        y_pred.append(temp)<br><br>    <strong>return</strong> y_pred</pre><pre><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> metrics<br>scores=[] <em># Store the list of f1 scores for prediction on each threshold</em><br><br><em>#convert labels to 1D array</em><br>y_true = flat_true_labels.ravel() <br><br><strong>for</strong> thresh <strong>in</strong> threshold:<br>    <br>    <em>#classes for each threshold</em><br>    pred_bin_label = classify(flat_pred_outs,thresh) <br><br>    <em>#convert to 1D array</em><br>    y_pred = np.array(pred_bin_label).ravel()<br><br>    scores.append(metrics.f1_score(y_true,y_pred))</pre><pre><em># find the optimal threshold</em><br>opt_thresh = threshold[scores.index(max(scores))]<br>print(f&#39;Optimal Threshold Value = <strong>{</strong>opt_thresh<strong>}</strong>&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*jR8qt07gzN2V5fAKVPJ-Sw.png" /></figure><h3>Performance Score Evaluation</h3><pre><em>#predictions for optimal threshold</em><br>y_pred_labels = classify(flat_pred_outs,opt_thresh)<br>y_pred = np.array(y_pred_labels).ravel() <em># Flatten<br></em>print(metrics.classification_report(y_true,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*m-HisWGLDTkE1Aaolq-GpQ.png" /></figure><pre><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> MultiLabelBinarizer<br><br>mlb = MultiLabelBinarizer()<br>yt = mlb.fit_transform([classes])<br>yt.shape<br><br>y_pred = mlb.inverse_transform(np.array(y_pred_labels))<br>y_act = mlb.inverse_transform(flat_true_labels)<br><br>df = pd.DataFrame({&#39;Body&#39;:test_data[&#39;Quote&#39;],&#39;Actual Tags&#39;:y_act,&#39;Predicted Tags&#39;:y_pred})<br>df.sample(40)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*NAzoxO5dfxQz5CdItmh5rg.png" /></figure><h3>Conclusions</h3><p>The performance score is not the best but we didn’t work on fine tunning (This would be covered in another post). Moreover, the example was run with free instances provided by Google and as consequence, this has multiple limitations, like the batch size.</p><p>Understanding how the Transformers work could be tricky but ¡implementing a showcase is not rocket science at all</p><h3>References</h3><ul><li>*Wikipedia contributors. (2021, October 30). Natural language processing. In Wikipedia, The Free Encyclopedia. Retrieved 07:27, November 2, 2021, from <a href="https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1052735380">https://en.wikipedia.org/w/index.php?title=Natural_language_processing&amp;oldid=1052735380</a></li><li>Maher. (2021, October 19). Five contemporary natural language processing problems pushed forward by DL. Medium. Retrieved November 2, 2021, from <a href="https://heartbeat.comet.ml/five-contemporary-natural-language-processing-problems-pushed-forward-by-dl-61989682cad5">https://heartbeat.comet.ml/five-contemporary-natural-language-processing-problems-pushed-forward-by-dl-61989682cad5</a>.</li><li>Muñoz, E. (2021, February 11). Attention is all you need: Discovering the transformer paper. Medium. Retrieved November 2, 2021, from <a href="https://towardsdatascience.com/attention-is-all-you-need-discovering-the-transformer-paper-73e5ff5e0634">https://towardsdatascience.com/attention-is-all-you-need-discovering-the-transformer-paper-73e5ff5e0634</a>.</li><li>Goled, S. (2021, March 16). Why transformers are increasingly becoming as important as RNN and CNN? Analytics India Magazine. Retrieved November 2, 2021, from <a href="https://analyticsindiamag.com/why-transformers-are-increasingly-becoming-as-important-as-rnn-and-cnn">https://analyticsindiamag.com/why-transformers-are-increasingly-becoming-as-important-as-rnn-and-cnn/</a>.</li><li>Transformers in NLP: State-of-the-art-models. Analytics Vidhya. (2021, July 23). Retrieved November 2, 2021, from <a href="https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/">https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/</a>.</li><li>Montantes, J. (2020, July 21). A deep dive into the transformer architecture — the development of Transformer models. Medium. Retrieved November 2, 2021, from <a href="https://towardsdatascience.com/a-deep-dive-into-the-transformer-architecture-the-development-of-transformer-models-acbdf7ca34e0">https://towardsdatascience.com/a-deep-dive-into-the-transformer-architecture-the-development-of-transformer-models-acbdf7ca34e0</a>.</li><li>Alammar, J. (n.d.). The illustrated transformer. The Illustrated Transformer — Jay Alammar — Visualizing machine learning one concept at a time. Retrieved November 2, 2021, from <a href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer/</a>.</li><li>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł. &amp; Polosukhin, I. (2017). Attention is all you need. Advances in Neural Information Processing Systems (p./pp. 5998–6008), <a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a>.</li><li>Mittal, A. (2018, March 18). Quotes dataset. Kaggle. Retrieved November 2, 2021, from <a href="https://www.kaggle.com/akmittal/quotes-dataset">https://www.kaggle.com/akmittal/quotes-dataset</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c47aee4d65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orion in Action: Testing a Real API]]></title>
            <link>https://ivan-corrales-solera.medium.com/orion-in-action-testing-a-real-api-a780244141a2?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a780244141a2</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 08:06:32 GMT</pubDate>
            <atom:updated>2021-02-17T08:06:32.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, we will learn how to automate acceptance tests for a REST API. This API provides endpoints to <strong>register</strong> and <strong>authenticate</strong> users (sign up/in). Additionally provides a secure endpoint to fetch data of a user. The service persists and fetches data in a <strong>mongo database</strong>.</p><p>The below flow diagram represents how the service works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*Jlh9I2BaGMgYaHnUpl47DQ.png" /><figcaption>API Flow diagram</figcaption></figure><h3>Prerequisites</h3><p>Clone the <a href="https://github.com/ivancorrales/orion-test-api">Git repository</a> that contains the</p><pre>git clone <a href="/service/mailto:git@github.com">git@github.com</a>:ivancorrales/orion-test-api.git</pre><p>Additionally, you should have <a href="https://docs.docker.com/get-docker/">Docker</a> and <a href="http://www.wesovilabs.com/orion/gettingstarted/installation/">Orion</a> installed on your computer.</p><h3>orion-test-api</h3><p>We’ll go through the different files and folders in the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*kssPJMGW1zZoQru5tIBtMA.png" /><figcaption>repository content</figcaption></figure><h4>docker-compose.yml</h4><p>Specification for service and mongo database.</p><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    image: ivancorrales/demo-api-mongo:0.0.1<br>    environment:<br>      MONGODB_URI: mongodb://root:secret@mongodb:27017/admin<br>    ports:<br>      - 3000:3000<br>  mongodb:<br>    image: mongo:latest<br>    environment:<br>      MONGO_INITDB_ROOT_USERNAME: root<br>      MONGO_INITDB_ROOT_PASSWORD: secret<br>    ports:<br>      - 27017:27017<br>    volumes:<br>      - mongodb_data_container:/data/db<br>volumes:<br>  mongodb_data_container:</pre><p>Let’s execute docker-compose up to launch the service and the mongo containers.</p><h4>.env</h4><p>It contains environment variables to be passed to Orion.</p><h4>.includes</h4><p>Files <strong>api.hcl </strong>and <strong>database.hcl </strong>in folder <strong>includes/*</strong> contain reusable <a href="http://www.wesovilabs.com/orion/spec/features/functions/">functions</a> to deal with both API and database.</p><h4>main.hcl</h4><p>This file will be used as an entrypoint to execute all the scenarios.</p><h4>happyPath.hcl</h4><p>The scenario that covers the happy path.</p><h4>signIn-failures.hcl / signUp-failures.hcl / showProfile-failures.</h4><p>Set of scenarios to cover the unhappy paths.</p><h3>Let’s do it!</h3><p>First of all, we launch the docker-compose with command docker-compose up. Service API is running on localhost:3000 and mongo on localhost:27017. Keep in mind that authentication is required to connect to mongo (<strong>root/secret).</strong></p><p>Acceptance tests can be executed with command:</p><pre>orion run --input main.hcl --vars env/local.hcl</pre><p>but…. let’s deep dive into the Orion files!</p><h4>includes/api.hcl</h4><p>It contains the functions to consume the API endpoints. These functions are invoked from the scenarios.</p><p>Actually, It’s very straightforward to read what the functions do. As you will realize showProfile function needs to pass the header x-access-token since this is a secure endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02ec12e700a622ac18b1ce66c2131d0/href">https://medium.com/media/b02ec12e700a622ac18b1ce66c2131d0/href</a></iframe><p>Learn more about <a href="http://www.wesovilabs.com/orion/spec/features/vars/">vars</a>, <a href="http://www.wesovilabs.com/orion/spec/features/args/">input arguments,</a> <a href="http://www.wesovilabs.com/orion/spec/features/functions/">functions</a> and action <a href="http://www.wesovilabs.com/orion/spec/actions/http/">http</a></p><h4>includes/database.hcl</h4><p>It contains a function that will be used from the scenarios to clean the database before executing the scenarios. We define default values for database and collection input arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5277ecaef7e0a69e7c2d01309194c99/href">https://medium.com/media/f5277ecaef7e0a69e7c2d01309194c99/href</a></iframe><p>Learn more about <a href="http://www.wesovilabs.com/orion/spec/features/vars/">vars</a><a href="http://www.wesovilabs.com/orion/spec/features/args/">,</a> <a href="http://www.wesovilabs.com/orion/spec/features/functions/">functions</a>, and action <a href="http://localhost:4000/spec/actions/mongo/">mongo</a></p><h4>happyPath.hcl</h4><p>The happy path must verify that a user is registered, authenticated and then she/he can fetch her/his profile details.</p><p>You will realize that argument baseApi is not passed when we call functions in include/api.hcl . That‘s due to baseApi will be a global variable in the main.hcl ..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9419147e4618c5997f5cdd6d14010fc2/href">https://medium.com/media/9419147e4618c5997f5cdd6d14010fc2/href</a></iframe><p>Learn more about <a href="http://www.wesovilabs.com/orion/spec/features/scenarios/">scenarios</a>, and actions <a href="http://www.wesovilabs.com/orion/spec/actions/call/">call</a> and <a href="http://www.wesovilabs.com/orion/spec/actions/assert/">assert</a>.</p><h4><strong>main.hcl</strong></h4><p>This file is used as an entry point to run all the scenarios. It’s the responsible to include the other hcl files. Besides this, we use this file to define the global hooks and define the input arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25f6fb1c5695295a5555f05b48a4d0e/href">https://medium.com/media/a25f6fb1c5695295a5555f05b48a4d0e/href</a></iframe><p>Learn more about <a href="http://www.wesovilabs.com/orion/spec/features/hooks/">hooks</a> definitions, <a href="http://www.wesovilabs.com/orion/spec/features/args/">input arguments</a> and <a href="http://www.wesovilabs.com/orion/spec/features/includes/">includes</a></p><h4>signUp-failures.hcl</h4><p>We write two scenarios: “A user cannot be registered because input data is not valid” or “there’s already a user with this email”.</p><p>To represent the first scenario in which the request is bad, we will take advantage of scenarios with examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1aa5eaa669e7f39fde9966972f3c74c/href">https://medium.com/media/b1aa5eaa669e7f39fde9966972f3c74c/href</a></iframe><h4><strong>signIn-failures.hcl / showProfile.hcl</strong></h4><p>These files are empty… I encourage you to try to implement the scenarios on your own. Practicing is the only way I know to learn something… and of course, <strong>let me know if you need any help!</strong></p><h3>Links of interest</h3><ul><li><a href="https://github.com/ivancorrales/orion-test-api">Source code of the example</a></li><li><a href="https://github.com/wesovilabs/orion">Orion source code</a></li><li><a href="http://www.wesovilabs.com/orion/gettingstarted/installation/">Orion documentation</a></li><li><a href="https://ivan-corrales-solera.medium.com/orion-a-next-generation-automation-testing-tool-4ea53eeb2517">Orion: A next-generation automation testing tool</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a780244141a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orion: A next-generation automation testing tool]]></title>
            <link>https://ivan-corrales-solera.medium.com/orion-a-next-generation-automation-testing-tool-4ea53eeb2517?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea53eeb2517</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 07:22:35 GMT</pubDate>
            <atom:updated>2021-02-17T08:31:00.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*fE7KzdG4sf8kk-H-.jpg" /><figcaption><a href="https://wesovilabs-tools.github.io/orion/">https://wesovilabs-tools.github.io/orion</a></figcaption></figure><p>Orion is born to help us to write and automate our acceptance tests. It provides a DSL inspired by Gherkin and based in HCL.</p><blockquote>The goal of Orion, is to provide people without technical skills a tool to write acceptance tests.</blockquote><p>In this article, we will go through some real scenarios to learn how to deal with Orion.</p><h3>Setup Orion</h3><p>To follow the article I highly recommend you to get Orion installed on your computer. It will take you less than a minute</p><p><a href="http://www.wesovilabs.com/orion/gettingstarted/installation/">Installation</a></p><h3>Showcase I: math operations</h3><p>We will write acceptance tests to verify that operation addand subtractwork correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*k_3befQIF7aFIURA.png" /></figure><h4>Initial approach</h4><p>We will write a couple of scenarios to verify the below:</p><ul><li>10 + 5 = 15</li><li>10 -5 = 5</li></ul><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>scenario &quot;operation add&quot; {<br>   given &quot;the variables x and y&quot; {<br>      set x {<br>         value = 10<br>      }<br>      set y{<br>         value = 5<br>      }<br>   }<br>   when &quot;values are added&quot; {<br>      set result {<br>         value = x + y<br>      }<br>      print {<br>         msg = &quot;${x} + ${y} is ${result}&quot;<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==15<br>      }<br>   }<br>}</pre><pre>scenario &quot;operation substract&quot; {<br>   given &quot;variables x and y&quot; {<br>      set x {<br>         value = 10<br>      }<br>      set y{<br>         value = 5<br>      }<br>   }<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>      }<br>      print {<br>         msg = &quot;${x} - ${y} is ${result}&quot;<br>     }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==5<br>      }<br>   }<br>}</pre><p>Let’s executeorion run --input feature-math-operations.hcl</p><h4>Hooks</h4><p>Hooks allow us to write a reusable set of actions that can be executed before or after the scenarios. Visit the <a href="http://www.wesovilabs.com/orion/spec/features/hooks/">Hooks documentation</a></p><p>We’ll use the special hook <strong>after each</strong> to print the operation result. As a consequence, we can remove the action printin the section when from the scenarios. The hook will be executed after any scenario is completed.</p><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>after each {<br>   print {<br>      msg = &quot;the output of this operation is ${result}&quot;<br>   }<br>}</pre><pre>scenario &quot;operation add&quot; {<br>   given &quot;the variables x and y&quot; {<br>      set x {<br>         value = 10<br>      }<br>      set y{<br>         value = 5<br>      }<br>   }<br>   when &quot;values are added&quot; {<br>      set result {<br>         value = x + y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==15<br>      }<br>   }<br>}</pre><pre>scenario &quot;operation substract&quot; {<br>   given &quot;variables x and y&quot; {<br>      set x {<br>         value = 10<br>      }<br>      set y{<br>         value = 5<br>      }<br>   }<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==5<br>      }<br>   }<br>}</pre><p>Let’s executeorion run --input feature-math-operations.hcl</p><h4>Input variables</h4><p>A better approach is to execute the same scenarios with different data. We can do this with block input. Visit the <a href="http://www.wesovilabs.com/orion/spec/features/args/">Input arguments Documentation</a></p><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>input {<br>   arg x {<br>      default = 10<br>   }<br>   arg y {<br>      default = 5    <br>   }<br>   arg sumResult {<br>      default = 15    <br>   }<br>   arg subResult {<br>      default = 5    <br>   }<br>}</pre><pre>after each {<br>   print {<br>      msg = &quot;the output of this operation is ${result}&quot;<br>   }<br>}</pre><pre>scenario &quot;operation add&quot; {<br>   when &quot;values are added&quot; {<br>      set result {<br>         value = x + y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==sumResult<br>      }<br>   }<br>}</pre><pre>scenario &quot;operation substract&quot; {<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==subResult<br>      }<br>   }<br>}</pre><p>Since we defined default values for all the args we could just run the features as usual:orion run --input feature-math-operations.hcl</p><p>On the other hand, we can set values for variables, as’s shown below</p><pre># variables-math-operations.hcl</pre><pre>x = 54<br>y = 46<br>sumResult = 100<br>subResult = 8</pre><p>Let’s executeorion run --input feature-math-operations.hcl --vars vars-math-operations.hcl</p><h4>Skip scenarios</h4><p>Attribute ignore permits us to skip the execution of a scenario. For example, we can establish that the second scenario is ignored when x&gt;10.</p><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>input {<br>   arg x {<br>      default = 10<br>   }<br>   arg y {<br>      default = 5    <br>   }<br>   arg sumResult {<br>      default = 15    <br>   }<br>   arg subResult {<br>      default = 5    <br>   }<br>}</pre><pre>after each {<br>   print {<br>      msg = &quot;the output of this operation is ${result}&quot;<br>   }<br>}</pre><pre>scenario &quot;operation add&quot; {<br>   when &quot;values are added&quot; {<br>      set result {<br>         value = x + y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==sumResult<br>      }<br>   }<br>}</pre><pre>scenario &quot;operation substract&quot; {<br>   ignore = x &gt; 10<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==subResult<br>      }<br>   }<br>}</pre><p>If we don’t pass the variables file both scenarios will be executed because the default value of x is 10. On the other hand, if we pass the variables file, the second scenario won’t be executed because x is 54.</p><h4>Includes</h4><p>We can split the content of our file into several files, and reuse them for different features. Visit the <a href="http://www.wesovilabs.com/orion/spec/features/includes/">Includes Documentation.</a> To put into practice this, we will move the scenarios to separated files.</p><pre># scenario-sum.hcl<br>scenario &quot;operation add&quot; {<br>   when &quot;values are added&quot; {<br>      set result {<br>         value = x + y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==sumResult<br>      }<br>   }<br>}</pre><pre># scenario-sub.hcl<br>scenario &quot;operation substract&quot; {<br>   ignore = x &gt; 10<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==subResult<br>      }<br>   }<br>}</pre><p>and then, we just make use of attribute includes</p><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>input {<br>   arg x {<br>      default = 10<br>   }<br>   arg y {<br>      default = 5    <br>   }<br>   arg sumResult {<br>      default = 15    <br>   }<br>   arg subResult {<br>      default = 5    <br>   }<br>}</pre><pre>after each {<br>   print {<br>      msg = &quot;the output of this operation is ${result}&quot;<br>   }<br>}</pre><pre>includes = [<br>   &quot;scenario-sum.hcl&quot;, <br>   &quot;scenario-sub.hcl&quot;<br>]</pre><p>Let’s executeorion run --input feature-math-operations.hcl</p><h4>Conditional actions</h4><p>The attribute when allows us to define if the action is executed or not. All the actions have this optional attribute. We make the following change in the second scenario: x-y when x&gt;y, and y-x otherwise</p><pre># scenario-sub.hcl<br>scenario &quot;operation substract&quot; {<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>         when = x &gt; y     <br>      }<br>      set result {<br>         value = y - x<br>         when = x &lt;= y     <br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==subResult<br>      }<br>   }<br>}</pre><p>if we swap the values of x and y in file vars-math-operations.hcl</p><pre># variables-math-operations.hcl</pre><pre>x = 46 <br>y = 54<br>sumResult = 100<br>subResult = 8</pre><p>the execution of our scenarios will be successful</p><p>Let’s executeorion run --input feature-math-operations.hcl --vars vars-math-operations.hcl</p><h4>Multiple cases</h4><p>If you’re experienced working with Cucumber, this will remember to the <strong>scenario outline. </strong>We just need to define a set of input data in attribute examples in the scenario. For example, we will provide examples for the second scenario.</p><pre># scenario-sub.hcl<br>scenario &quot;operation substract&quot; {   <br>   examples = [<br>      { x = 20, y = 10, subResult= 10},<br>      { x = 10, y = 20, subResult= 10},<br>      { x = 5, y = 5, subResult= 0},<br>   ]<br>   when &quot;subtract y to x&quot; {<br>      set result {<br>         value = x - y<br>         when = x &gt; y     <br>      }<br>      set result {<br>         value = y - x<br>         when = x &lt;= y     <br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==subResult<br>      }<br>   }<br>}</pre><p>if we execute Orion, the above scenario will be executed three times.</p><p>Let’s executeorion run --input feature-math-operations.hcl</p><h4>Special action: block</h4><p>Let’s implement a new scenario to demonstrate how multiplication works. Initially, we could go for something like this</p><pre># scenario-mult.hcl<br>scenario &quot;operation multiplication&quot; {<br>    examples = [<br>      { x = 20, y = 10, multResult= 10},<br>      { x = -1, y = -2, multResult= 2},<br>      { x = 5, y = 5, multResult= 25},<br>      { x = 5, y = 0, multResult= 0},   <br>   ]<br>   when &quot;multiply y by x&quot; {<br>      set result {<br>         value = x * y<br>      }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==multResult<br>      }<br>   }<br>}</pre><p>but I want to show you how the special action <strong>block </strong>(<a href="http://www.wesovilabs.com/orion/spec/actions/block/">Documentation here)</a> works. This action is used to group a set of actions. And additionally, we will make use of an attribute count that permits iterate from 0 to count-1.</p><pre># scenario-mult.hcl<br>scenario &quot;operation multiplication&quot; {<br>    examples = [<br>      { x = 20, y = 10, multResult= 200},<br>      { x = -1, y = -2, multResult= 2},<br>      { x = 5, y = 5, multResult= 25},<br>      { x = 5, y = 0, multResult= 0},   <br>   ]   <br>   given &quot;initialie result&quot; {<br>      set result {<br>         value = 0<br>      }<br>   }<br>   when &quot;multiply y by x&quot; {<br>      block {<br>         set result {<br>            value = result + x<br>         }<br>         print {<br>            msg = &quot;${x} * ${_.index+1} is ${result}&quot;<br>         }<br>         count = y<br>         when = x&gt;0 &amp;&amp; y&gt;0      <br>     } <br>     set result {<br>        value = x * y     <br>        when = x&lt;0 || y&lt;0<br>     }<br>   }<br>   then &quot;the result of the operation is the expected&quot; {<br>      assert {<br>         assertion = result==multResult<br>      }<br>   }<br>}</pre><p>And of course, we need to add this file in the include block.</p><pre># feature-math-operations.hcl</pre><pre>description = &lt;&lt;EOF<br>   This feature is used to demonstrate that both add and subs<br>   operations work as expected.<br>EOF</pre><pre>input {<br>   arg x {<br>      default = 10<br>   }<br>   arg y {<br>      default = 5    <br>   }<br>   arg sumResult {<br>      default = 15    <br>   }<br>   arg subResult {<br>      default = 5    <br>   }<br>}</pre><pre>after each {<br>   print {<br>      msg = &quot;the output of this operation is ${result}&quot;<br>   }<br>}</pre><pre>includes = [<br>   &quot;scenario-sum.hcl&quot;, <br>   &quot;scenario-sub.hcl&quot;,<br>   &quot;scenario-mult.hcl&quot;<br>]</pre><p>Let’s executeorion run --input feature-math-operations.hcl</p><p>Beside of when and count there are other special attributes. See the full list <a href="http://www.wesovilabs.com/orion/spec/actions/block/">here</a>.</p><p>Orion is still in beta, hence your suggestions and feedback will be very appreciated!</p><h4>Links of interests</h4><ul><li><a href="https://github.com/ivancorrales/orion-test-maths">Source code of examples</a></li><li><a href="http://www.wesovilabs.com/orion/">Orion documentation.</a></li><li><a href="https://github.com/wesovilabs/orion">Orion source code</a></li><li><a href="https://ivan-corrales-solera.medium.com/orion-in-action-testing-a-real-api-a780244141a2">Orion in actions: Testing a real API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea53eeb2517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 days playing with Rust (and I love it!)]]></title>
            <link>https://ivan-corrales-solera.medium.com/3-days-playing-with-rust-and-i-love-it-2f11f7246a36?source=rss-e63f2d4657c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f11f7246a36</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Iván Corrales Solera]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 06:01:50 GMT</pubDate>
            <atom:updated>2020-08-02T04:34:31.473Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is mainly focused for those developers who haven’t tried Rust yet or they are starting to play with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9KlIljzq-j45otD.jpg" /></figure><blockquote>It has been written after 3 days playing with Rust .So please… don’t be so hard with me! I’m a beginner &amp; self-though guy that just wants to share with others what is learning!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*nejwJBxKElpZSGzz.jpg" /></figure><h3>About this article</h3><p>In this article we will build a program that retrieves a csv file as input (available shows in Netflix) and it performs some queries to the dataset.</p><p>In addition to this, I’ll go through the most interesting things that I’ve learnt these days; you will also find some useful links.</p><h3>Why Rust?</h3><p>Because I want to do some researches on IoT. Embedded systems can be programmed with Rust easily.</p><h3>Setup the environment</h3><p>It’s very straightforward, just follow the below links:</p><ul><li><a href="https://www.rust-lang.org/tools/install">https://www.rust-lang.org/tools/install</a></li><li><a href="https://hoverbear.org/blog/setting-up-a-rust-devenv/">https://hoverbear.org/blog/setting-up-a-rust-devenv/</a></li></ul><h3>Cargo</h3><p>Basically Cargo is the Rust packages manger. <strong>Cargo</strong> is for Rust like <strong>Maven</strong> is for Java, <strong>Npm</strong> for Node. or <strong>sbt</strong> for Scala</p><p>There’s a <strong>Cargo.toml</strong> in the root of any Rust project. This file could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJCOH_qT6-6UyqpsDIjLjw.png" /><figcaption>Cargo.toml</figcaption></figure><p>We could have several <strong>executables programs,</strong> and they must be defined in the <strong>bin section. </strong>Have a look at the below link to know about how cargo works.</p><ul><li><a href="https://doc.rust-lang.org/cargo/getting-started/index.html">https://doc.rust-lang.org/cargo/getting-started/index.html</a></li></ul><h3>OOP</h3><p><strong>Objects</strong> are defined with keyword <strong>struct</strong>. By default, the structs and attributes visibility is private. To make them public we just need to set the keyword <strong>pub.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9jlFrK2dikbXqksx6VAcQ.png" /><figcaption>Struct definition used to load each row in our csv file</figcaption></figure><p><strong>Methods:</strong> Methods implementations are in an <strong>impl </strong>block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEO_-4dIO78UlljynEYXIA.png" /><figcaption>how_old method used to know the years since a show was released</figcaption></figure><ul><li>Each statement <strong>ends with semicolon</strong>. If the last statement in a function doesn’t end with semicolon, it will be interpreted like the return of the function. The both following examples are the same.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsJ-5ucRyF_7pnskaynB0g.png" /><figcaption>return keyword can be omitted</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgW1jqAK72suRtnvuwWaPA.png" /><figcaption>use return keyword</figcaption></figure><ul><li><strong>self</strong> keyword permits access to the object attributes and methods.</li><li>By default, the <strong>variables are inmutables.</strong> To make them <strong>mutables</strong> we need to use the keyword <strong>mut</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ7m6AC5otx7Y3MgsJ0RNQ.png" /><figcaption>error: cannot borrow `items` as mutable, as it is not declared as mutable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSfme9TL3mVynsB7aennbw.png" /><figcaption>Correct definition of variable items</figcaption></figure><p><strong>Types: </strong>We can easily define new types (or alias)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vT_gL0fGVk7yUhysyJeNg.png" /><figcaption>Alias used to name a vector of shows</figcaption></figure><p><strong>Traits: </strong>Similar to interfaces in some points, but they provides extra functionality.</p><p>The traits contains the signature of the methods to be implemented. On the other hand default implementation can be defined in the trait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmS1IWhKFhR97LwxOHQ1mg.png" /><figcaption>Parser trait to be implemented by csv parser</figcaption></figure><p>On the other hand, we can also provide traits implementations for existing types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dy7i9QLZgDtIgBvtQ6lYOw.png" /><figcaption>String variables could use this new function to_vector</figcaption></figure><p><strong>Generics: </strong>Generics are supported in Rust (<em>Golang… you’re so late). </em>This permits as build more <strong>reusable code. </strong>The last example in section Traits contains a use case.</p><h3>Imports</h3><p>We can import modules by making use of keyword <strong>use. </strong>Syntax to import modules in Rust is powerful</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26gRh3i8fiqTH5dzEkNoXQ.png" /><figcaption>We can define mods, structs or just functions</figcaption></figure><h3>Custom errors</h3><p>Writing our own business error is useful to write code easy to read. To do this, we just need to implement the traits Display and Error for our struct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ScVA7KYSLCN-Xtl5zB7XA.png" /><figcaption>FileNotFound error definition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXsTf9snTPjJMWYLrr0bYg.png" /><figcaption>Throwing our own errors</figcaption></figure><h3>Closures</h3><p>Closures in Rust, also called lambda expressions or lambdas, are functions that can capture the enclosing environment. For example, a closure that captures the x variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLkY2hb0zSPFIn4LjNaVFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6E8BfH7z0NBjSg9KV0lQiQ.png" /></figure><h3>Code organization</h3><p>As in many other languages you’ll find several articles about which one is the best way to organize a rust project.</p><p>Interesting link:</p><ul><li><a href="https://dev.to/ghost/rust-project-structure-example-step-by-step-3ee">https://dev.to/ghost/rust-project-structure-example-step-by-step-3ee</a></li></ul><h3>Macros</h3><p>I haven’t done any research on this yet, but It’s something that I want to try as soon as possible. I guess It works like in other languages such as Elixir or Ruby.</p><blockquote>Meta programming is so powerful.</blockquote><h3>Functional programming</h3><p><strong>Rust</strong> provides <strong>Higher Order Functions</strong> (HOF). These are <strong>functions</strong> that take one or more <strong>functions</strong> and/or produce a more useful <strong>function</strong>. HOFs and lazy iterators give <strong>Rust</strong> its functional flavor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMQb-mOn-4735p-VaJS_Og.png" /><figcaption>Sample of use in Rust</figcaption></figure><p>Interesting link:</p><ul><li><a href="http://blog.madhukaraphatak.com/functional-programming-in-rust-part-2/">http://blog.madhukaraphatak.com/functional-programming-in-rust-part-2/</a></li></ul><h3>Source code</h3><p>The code of the program can be cloned from here</p><p><a href="https://github.com/wesovilabs/rust_introduction/tree/master">https://github.com/wesovilabs/rust_introduction/tree/master</a></p><p>Clone the repository and once the Rust environment is ready jrun the below command</p><p><strong>cargo run resources/nextflix.csv</strong></p><p>The output should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*q4T6ARTsyitaxmbR7RLVFA.png" /></figure><blockquote>I encourage you to implement JSonLoader or XMLLoader to put in practice what you learnt in this article. Code can be easily extensible.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qT0YLhv4qQf25AcPjXVzuQ.png" /></figure><ul><li>Documentation of crate <strong>serde</strong> (used to serialize the domain) can be found here <a href="https://serde.rs/">https://serde.rs/</a></li></ul><h3>What can you do next?</h3><p>Books &amp; articles are fine to get an idea about technology, but actually you only learn if you put it into practice what you read.</p><ul><li>Create a new executable file. (Modify Cargo.toml and create a new file in bin directory)</li></ul><p><strong>cargo run — bin mydemo resources/nextflix.csv</strong></p><ul><li>Print the title (in uppercase) of the shows whose release date is lees than 3 years.(and any other query that you want to try).</li><li>Code an implementation for loading the file netflix.json in resources directory. The command should be</li></ul><p><strong>cargo run resources/nextflix.json</strong></p><h3>Must read articles &amp; tutorials</h3><ul><li><a href="https://doc.rust-lang.org/book/">https://doc.rust-lang.org/book/</a></li><li><a href="https://learning-rust.github.io/">https://learning-rust.github.io/</a></li><li><a href="http://blog.madhukaraphatak.com/functional-programming-in-rust-part-1/">http://blog.madhukaraphatak.com/functional-programming-in-rust-part-1/</a></li><li><a href="https://blog.thoughtram.io/string-vs-str-in-rust/">https://blog.thoughtram.io/string-vs-str-in-rust/</a></li></ul><h3>My feeling</h3><p>Rust looks so great and It provides excellent mechanisms to build Software. I wish I could learn fast and being able to go through the embedded programming tutorials soon.</p><p>Even the documentation is so great, and the language takes the best of several programming languages, I’m afraid its success will depend on how many frameworks to build commercial Software appear in upcoming years.</p><p>Sadly the Rust community is not so big, and to be honest, I don’t know companies which want to bet for this kind of challenges…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f11f7246a36" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>