<?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 SphericalKat on Medium]]></title>
        <description><![CDATA[Stories by SphericalKat on Medium]]></description>
        <link>https://medium.com/@sphericalkat?source=rss-23aeacd38998------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PPyvSfi3HvEY53yFTmJzug.png</url>
            <title>Stories by SphericalKat on Medium</title>
            <link>https://medium.com/@sphericalkat?source=rss-23aeacd38998------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:28:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sphericalkat/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[Static Analysis in Go: First Steps]]></title>
            <link>https://medium.com/goalist-blog/static-analysis-in-go-first-steps-68f4b07a0b78?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f4b07a0b78</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 05:36:50 GMT</pubDate>
            <atom:updated>2023-09-06T05:36:50.331Z</atom:updated>
            <content:encoded><![CDATA[<p>A gentle introduction to static analysis in Go</p><p><strong><em>Static Analysis</em></strong>. The art of analyzing programs without executing them, often to look for unwanted behaviour and unidiomatic code.</p><p>Most IDEs and LSPs come with some form of static analysis. Many of the code linters out there perform some kind of static analysis. Code quality tools like Sonarqube rely on static analysis to find issues with your code.</p><p>With that in mind, it’s apparent that knowing how these work is a useful skill to have, and it’s not even that difficult to get started with!</p><p>In this post, we’ll use the Go programming language to build a simple analzyer.</p><h3>But, before we begin…</h3><p>Let’s lay down the groundwork . These are just some of the things you should know before you embark on this endeavour. First, let’s learn about ASTs.</p><h4>Abstract Syntax Trees</h4><p>One of the things you’ll become intimately familiar with when working with analyzers is the <strong>AST</strong> (Abstract Syntax Tree).</p><p>Abstract Syntax Trees (ASTs) are a way of representing the structure of code or data in a program. They are used by compilers and interpreters to transform source code into executable code, or to analyze data structures.</p><p>An AST is a tree-like data structure that represents the syntactic structure of the code or data, without including information about the specific characters used to write the code. Instead, it captures the essential structure of the code, including the relationships between different parts of the code and the order in which they appear.</p><p>The main job of any static analysis tool is to traverse the AST and find problems.</p><figure><img alt="A graph visualization of an Abstract Syntax Tree" src="https://cdn-images-1.medium.com/max/1024/0*Y2lTd7akaTbDI3ra" /><figcaption>Visualization of a Go program’s AST</figcaption></figure><p>For a quick peek to dive into ASTs, you can check out <a href="https://astexplorer.net/">https://astexplorer.net/</a>, which supports multiple languages.</p><h4>Why Go?</h4><p>You might be wondering why we picked Go, of all languages. One of the reasons is that Go has a well-maintained suite of analysis tools built by the Go team, available under the package <a href="https://pkg.go.dev/golang.org/x/tools/go/analysis">analysis</a>.</p><p>The other is that it’s a popular language with a decent amount of features that we can write lints for.</p><p>With that out of the way, let’s begin.</p><h3>Our first linter</h3><p>Our first linter is going to do something very simple. We want to detect and report if the cancel function returned by context.WithCancelis unused.</p><pre>package main<br><br>import &quot;context&quot;<br><br>func main() {<br> ctx, _ := context.WithCancel(context.Background())<br><br> // just to discard ctx<br> _ = ctx<br>}</pre><p>Since what we want to analyze (a context.WithCancel call) will always be inside a function, we can focus on this part of the AST on <a href="https://astexplorer.net/#/gist/1d7b291676388d2d81a8c1f0d48f777b/ac6e92f77315e72f41c605fd5d9afe6cb5a154a8">astexplorer</a>.</p><p>We can see that the AST contains a list of statements inside a BlockStmt. One of these statements is an AssignStmt, and on its RHS (Right Hand Side) is a CallExpr, which is our WithCancel call.</p><h4>Setting up the project</h4><p>Let’s create a directory structure similar to the following. Feel free to follow something else if you like it better.</p><pre>├── go.mod<br>├── linters<br>│   └── ignored_cancel<br>│       └── ignored_cancel.go<br>├── main.go<br>└── testdata<br>    └── ignored_cancel.go</pre><p>testdata contains our test files for verifying our analyzer. linters contain our current linter (and any future ones we may write.</p><p>To get started, let’s focus on ignored_cancel.go. We’ll define our analyzer by declaring a type like the following:</p><pre>import (<br>   &quot;golang.org/x/tools/go/analysis&quot;<br>   &quot;golang.org/x/tools/go/analysis/passes/inspect&quot;<br>)<br><br>var IgnoredCancelAnalyzer = &amp;analysis.Analyzer{<br>   Name: &quot;ignoredcancel&quot;, // name of our analyzer<br>   Doc: &quot;linter for detecting ignored cancel function returned from context.CancelFunc&quot;,<br>   Run: func(p *analysis.Pass) (interface{}, error) {<br>    // write our logic here<br>   }, // the logic for our analyzer<br>   Requires: []*analysis.Analyzer{inspect.Analyzer}, // declare analyzers that ours is dependent on<br>}</pre><p>Most of these fields are self-explanatory, but let’s look at what Requires does. According to the documentation, it takes in analyzers which are treated as dependencies to the one we’re declaring, and should be run before ours runs. Here, we pass in a very interesting analyzer, inspect.Analyzer.</p><p>What inspect.Analyzer does, is that it parses the code into an AST, and provides the result to us in the Run function through the analysis.Pass argument. Let’s see how we can access it.</p><pre>func(p *analysis.Pass) (interface{}, error) {<br>    i, ok := p.ResultOf[inspect.Analyzer].(*inspector.Inspector)<br>    if !ok {<br>     return nil, errors.New(&quot;analyzer is not of type *inspector.Inspector&quot;)<br>    }<br><br>    return nil, nil<br>}</pre><p>Here, we try and assert that the result of the analyzer is of type *inspector.Inspector. This type provides access to the nodes of the AST. If we’re not successful, we return an error.</p><p>Now, let’s start traversing the AST. We only want AssignStmt nodes, so let’s write a filter for them, and use the convenient Preorder function on the *inspector.Inspector to perform a Depth-First Search of the AST.</p><pre>func(p *analysis.Pass) (interface{}, error) {<br>    i, ok := p.ResultOf[inspect.Analyzer].(*inspector.Inspector)<br>    if !ok {<br>       return nil, errors.New(&quot;analyzer is not of type *inspector.Inspector&quot;)<br>    }<br>  <br>    // dfs of AST<br>    filter := []ast.Node{(*ast.AssignStmt)(nil)}<br>    i.Preorder(filter, func(n ast.Node) {<br>       // logic<br>    })<br>  <br>    return nil, nil<br> }</pre><p>Now, let’s start writing the core logic for figuring out if the cancelFunc is ignored or not. First, we confirm that the node is indeed an *ast.AssignStmt, and then inspect it.</p><pre>i.Preorder(filter, func(n ast.Node) {<br>   foundIgnoredCancel := false // flag<br>  <br>   // confirm node is indeed an AssignStmt<br>   node, ok := n.(*ast.AssignStmt)<br>   if !ok {<br>      return<br>   }<br>  <br>   // DFS on the node&#39;s children<br>   ast.Inspect(node, func(n ast.Node) bool {<br>      // len(RHS) can only be 1 if it&#39;s a multi-return function<br>      // ignore all other cases<br>      if len(node.Rhs) &gt; 1 {<br>         return false<br>      }<br>    <br>      // assert that the RHS is a function call expression<br>      e, ok := node.Rhs[0].(*ast.CallExpr)<br>      if !ok {<br>         return false<br>      }<br>    <br>      // assert that the function call is a selector expression<br>      fExpr, ok := e.Fun.(*ast.SelectorExpr)<br>      if !ok {<br>         return false<br>      }<br>    <br>      // assert that the expression in selector is an identifier<br>      // because it is an import of &quot;context&quot;<br>      sExpr, ok := fExpr.X.(*ast.Ident)<br>      if !ok {<br>         return false<br>      }<br>    <br>      // if the function signature matches<br>      if sExpr.Name != &quot;context&quot; || fExpr.Sel.Name != &quot;WithCancel&quot; {<br>         return false<br>      }<br>    <br>      // if lhs has more or less variables, something is very wrong<br>      if len(node.Lhs) != 2 {<br>         return false<br>      }<br>    <br>      // assert that the lhs is just an identifier<br>      lExpr, ok := node.Lhs[1].(*ast.Ident)<br>      if !ok {<br>         return false<br>      }<br>    <br>      if lExpr.Name == &quot;_&quot; {<br>         foundIgnoredCancel = true<br>         return false<br>      }<br>    <br>      return true<br>   })<br>   if foundIgnoredCancel {<br>      p.Reportf(n.Pos(), &quot;found ignored cancelFunc on context.WithCancel&quot;)<br>   }<br>})</pre><p>Let’s break this down.</p><ul><li>First we assert that the node is indeed, an AssignStmt .</li><li>Next, we check if the the RHS has more than 1 expressions. In a multi-function return, there can only be one expression on the RHS. Essentially, we’re checking if context.WithCancel was called at all.</li><li>If the expression on the RHS was a CallExpr, we proceed further and check what kind of function call it was.</li><li>Go makes a distinction between functions that are part of the language, and functions that are imported. A function that is part of the language will be represented by an Ident expr. An imported function will be represented by a SelectorExpr, which represents a selection of a particular field of an expression. For example, selection of a field on a struct instance.</li><li>In this case, the expression (X) will be the package name, and the selector (Sel) will be the function name.</li><li>Finally, we check if the expression (package name) is equal to “context” and the selector name (function name) is equal to “WithCancel”. If yes, we check if the 2nd element of the LHS is equal to “_”, which indicates an ignored return value. We set a flag, foundIgnoredCancel if this is the case.</li><li>Finally, we report the position of the lint using p.Reportf.</li></ul><h4>Running the linter</h4><p>Let’s wire up the analyzer in main.go.</p><p>We ensure that the linter will be executed by adding it to the multichecker.Main function.</p><pre>package main<br><br>import (<br>   ignoredcancel &quot;analyzer/linters/ignored_cancel&quot;<br>  <br>   &quot;golang.org/x/tools/go/analysis/multichecker&quot;<br>)<br><br>func main() {<br>   multichecker.Main(ignoredcancel.IgnoredCancelAnalyzer)<br>}</pre><p>We can run the analyzer on a sample file containing an ignored cancel statement using the following statement:</p><pre>go run main.go -- testdata/ignored_cancel.go<br><br># output<br>&lt;path&gt;/testdata/ignored_cancel.go:6:2: found ignored cancelFunc on context.WithCancel<br>exit status 3</pre><p>It works!</p><h3>Conclusions and beyond</h3><p>We demonstrated how simple it is to write your own analyzer for Go. This was a very simple analyzer, but the principles apply nonetheless.</p><p>You should note that this implementation is a bit naive, and does not capture all of the possible edge cases. For example, if the “context” package was imported under a different name, our lint would ignore it. The mitigation for this is left as an exercise for the reader :)</p><p>Finally, I highly recommend checking out the rest of what the <a href="https://pkg.go.dev/golang.org/x/tools/go/analysis">analysis</a> package can do. It’s quite powerful and convenient to use.</p><p>The accompanying code can be found <a href="https://github.com/sphericalkat/go-static-analyzer">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f4b07a0b78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/static-analysis-in-go-first-steps-68f4b07a0b78">Static Analysis in Go: First Steps</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to parser-combinators]]></title>
            <link>https://medium.com/goalist-blog/a-gentle-introduction-to-parser-combinators-c35a1779ed50?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/c35a1779ed50</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 03:14:34 GMT</pubDate>
            <atom:updated>2023-08-01T03:14:34.128Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover the fundamentals of parser-combinators, offering a gentle introduction to the art of parsing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qAOZS29bHNsbakE2lk2cA.png" /></figure><p>Hang around programmers long enough, and you’ll often hear of <em>parsers</em> or <em>parsing</em>. Let’s find out what it is and what we use it for.</p><p>Parsers are programs that can analyze and process input, typically text, according to a set of rules. They are commonly used for tasks such as validating user input, interpreting programming languages, or extracting data from structured text.</p><p>Naturally, parsing is the act of running a parser over input. For example, a JSON parser will accept text and output an object.</p><p>With that out of the way, let’s design a parser.</p><blockquote><strong><em>Note</em></strong><em>: All code will be written in Rust for the purposes of this article.</em></blockquote><h3>Parser Combinators</h3><p>Parser combinators are a way of building parsers by combining smaller parsers into larger ones. Each parser combinator takes one or more parsers as input and returns a new parser as output.</p><p>By chaining together parser combinators, we can create more complex parsers that can handle a wider range of inputs. This approach is often used in functional programming languages, such as Haskell, where parsers are represented as functions that can be composed together.</p><p>You might ask; but why use Parser Combinators? Surely you can write a parser by hand instead of chaining multiple parsers together?</p><h3>Why use Parser Combinators?</h3><p>Parser combinators offer several advantages over hand-written parsers.</p><p>They are often easier to read and understand. By breaking down the parser into smaller, composable parts, it becomes easier to reason about each part of the parsing process.</p><p>Parser combinators are often more modular and reusable than hand-written parsers. Once a set of parser combinators has been defined, it can be used to parse many different inputs.</p><p>Parser combinators often result in shorter, more concise code. This is because they allow complex parsing logic to be expressed in a more declarative style, rather than a procedural style.</p><p>It is also difficult and time-consuming to write parsers with good error recovery mechanisms. It requires understanding the intricacies of the recursive descent algorithm and then implementing recovery strategies on top of them.</p><p>If you’re writing a programming language, there will almost certainly be changes in the syntax and grammar in the process, which can cause time-consuming and painful refactoring. Parser combinators solve both error recovery and refactoring by providing an easy-to-use API that allows for rapid prototyping.</p><p>Parser combinators are an excellent choice for domain-specific languages that lack an existing parser. With a reliable and fault-tolerant parser combinator library, what would have taken several days to accomplish can be achieved in as little as half an hour.</p><h3>Abstract Syntax Trees</h3><p>Abstract Syntax Trees (ASTs) are a way of representing the structure of code or data in a program. They are used by compilers and interpreters to transform source code into executable code or to analyze data structures.</p><p>An AST is a tree-like data structure that represents the syntactic structure of the code or data, without including information about the specific characters used to write the code. Instead, it captures the essential structure of the code, including the relationships between different parts of the code and the order in which they appear. ASTs are often used in conjunction with parser combinators to build parsers for programming languages or other structured data formats.</p><p>An example AST for a parsed JSON file is shown here:</p><pre>Some(<br>    Object(<br>        {<br>            &quot;acres&quot;: Str(<br>                &quot;home&quot;,<br>            ),<br>            &quot;leaving&quot;: Object(<br>                {<br>                    &quot;front&quot;: Str(<br>                        &quot;college&quot;,<br>                    ),<br>                    &quot;origin&quot;: Num(<br>                        981339097.0,<br>                    ),<br>                    &quot;cowboy&quot;: Num(<br>                        -355139449.0,<br>                    ),<br>                    &quot;fed&quot;: Num(<br>                        -283765067.9149623,<br>                    ),<br>                    &quot;tail&quot;: Array(<br>                        [<br>                            Num(<br>                                -2063823378.8597813,<br>                            ),<br>                            Bool(<br>                                true,<br>                            ),<br>                            Null,<br>                            Num(<br>                                -153646.6402,<br>                            ),<br>                            Str(<br>                                &quot;board&quot;,<br>                            ),<br>                        ],<br>                    ),<br>                    &quot;although&quot;: Num(<br>                        -794127593.3922591,<br>                    ),<br>                },<br>            ),<br>            &quot;activity&quot;: Str(<br>                &quot;value&quot;,<br>            ),<br>            &quot;noise&quot;: Bool(<br>                false,<br>            ),<br>            &quot;office&quot;: Num(<br>                -342325541.1937506,<br>            ),<br>        },<br>    ),<br>)</pre><h3>Our first parser</h3><p>We’re going to write a simple CLI tool to parse JSON and generate an AST (Abstract Syntax Tree) called bourne. We will write it in Rust, and use the chumsky parser-combinator library.</p><p>Note that our parser will not handle the full JSON specification, such as escape characters or exponential numbers, but it should handle most common JSON, such as nested arrays, objects, numbers, strings, booleans, and null values.</p><h3>Creating the project</h3><p>Create a simple rust binary project using cargo:</p><pre>cargo new bourne<br>cd bourne/</pre><p>Add the chumsky and ariadne libraries to Cargo.toml</p><p>We’ll be using ariadne for effective error recovery and reporting.</p><pre>[package]<br>name = &quot;bourne&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>ariadne = &quot;0.3.0&quot;<br>chumsky = {git = &quot;https://github.com/zesterer/chumsky&quot;, rev = &quot;3b1ab31&quot;}</pre><h3>Read a JSON file from stdin</h3><p>To parse some JSON, we first have to read it into memory. For this purpose, we’ll take a file path through stdin and read it.</p><pre>use std::{env, fs};<br><br>fn main() {<br> let src = fs::read_to_string(env::args().nth(1).expect(&quot;Expected file argument&quot;))<br>        .expect(&quot;Failed to read file&quot;);<br>}</pre><h3>Define the AST model</h3><p>We will define a recursive AST based on the JSON value type as a Rust enum.</p><pre>use std::{collections::HashMap, env, fs};<br><br>#[derive(Clone, Debug)]<br>enum Json {<br>    Invalid, // invalid node<br>    Null, // null node<br>    Bool(bool), // boolean node with its value<br>    Str(String), // string node with value<br>    Num(f64), // number node with value<br>    Array(Vec), // array node with values<br>    Object(HashMap), // nested object with child key value pairs<br>}<br><br>fn main() ...</pre><h3>Build a parser function</h3><p>Finally, let’s build a parser() function that will return a recursive parser that can take in string input and return the built AST and any errors that might be encountered.</p><pre>use ariadne::{Color, Label, Report, ReportKind, Source}; use chumsky::prelude::*; #[derive(Clone, Debug)] enum Json {... fn parser() -&gt; impl Parser&gt;&gt; { recursive(|value| { }) } fn main() { ... let (json, errs) = parser().parse(src.trim()).into_output_errors(); println!(&quot;{:#?}&quot;, json); errs.into_iter().for_each(|e| { Report::build(ReportKind::Error, (), e.span().start) .with_message(e.to_string()) .with_label( Label::new(e.span().into_range()) .with_message(e.reason().to_string()) .with_color(Color::Red), ) .finish() .print(Source::from(&amp;src)) .unwrap() }); }use ariadne::{Color, Label, Report, ReportKind, Source};<br>use chumsky::prelude::*;<br><br>#[derive(Clone, Debug)]<br>enum Json {...<br><br>fn parser&lt;&#39;a&gt;() -&gt; impl Parser&lt;&#39;a, &amp;&#39;a str, Json, extra::Err&lt;Rich&lt;&#39;a, char&gt;&gt;&gt; {<br> recursive(|value| {<br> })<br>}<br><br>fn main() {<br> ...<br> let (json, errs) = parser().parse(src.trim()).into_output_errors();<br>    println!(&quot;{:#?}&quot;, json);<br>    errs.into_iter().for_each(|e| {<br>        Report::build(ReportKind::Error, (), e.span().start)<br>            .with_message(e.to_string())<br>            .with_label(<br>                Label::new(e.span().into_range())<br>                    .with_message(e.reason().to_string())<br>                    .with_color(Color::Red),<br>            )<br>            .finish()<br>            .print(Source::from(&amp;src))<br>            .unwrap()<br>    });<br>}</pre><p>Let’s break down all the changes here.</p><p>First, we defined a function called parser that returns an implementation of the Parser trait defined by chumsky. This trait takes in a few type parameters, which are described below:</p><ol><li>The first type parameter (i.e: ignoring the lifetime parameter) of the [Parser] trait is the input type. Inputs must implement the [Input] trait. Examples of inputs include strings, slices, arrays, [Stream]s, and much more. For now we are specifying that this parser can only operate upon string slices: but it is also possible to introduce the input type as a generic type parameter like I: Input&lt;&#39;src&gt; instead if you want your parser to be generic across more than just string slices.</li><li>The second type parameter of the [Parser] trait is the output type. This is the type of the value that the parser will eventually give you, assuming that parsing was successful. Here, we use the output type of [Json], i.e: the enum we just defined to represent our AST.</li></ol><p>Next, we returned the value returned by the recursive function, which takes in a callback where we will actually construct the parser. There are a few things worth paying attention to here:</p><ol><li>recursive allows us to define a parser recursively in terms of itself by giving us a copy of it within the closure&#39;s scope.</li><li>You might ask, why do we need a recursive parser? It’s because we want to be able to handle nested JSON nodes, such as arrays and objects.</li></ol><p>Finally, we call Parser::parse() on the parser returned by the parser() function we just defined. This takes in the input and returns the output and errors encountered during parsing. We then print the returned output and errors.</p><p>Note that since we’re using a Rich error, we&#39;ll get a lot of helpful information about what went wrong for free from chumsky!</p><h3>Building the parser</h3><p>Let’s get down to the meat and potatoes, actually building the parser! Parser combinators allow us to declaratively build parsers and combine them to build larger parsers.</p><h4>Let’s start off by extracting all numbers.</h4><pre>recursive(|value| {<br>   let number = just(&#39;-&#39;)<br>              .or_not()<br>              .then(text::int(10))<br>              .map_slice(|s: &amp;str| s.parse::().unwrap());<br>})</pre><p>Here, we define a parser for numbers which is composed of smaller parsers. Let’s break it down:</p><ul><li>The just() primitive parser recognises a specific token or an exact ordered sequence of tokens. Here, we combine it with the or_not() combinator, which attempts to parse a pattern, always succeeding with either [Some(...)] or [None] depending on whether parsing was successful. We use it here to optionally parse a negative number beginning with -</li><li>The then() combinator parses one pattern and then another, producing a tuple of the two parsers outputs as an output. We use it to chain the actual number parser, which is text::int(). It is provided by chumsky, and lets us parse integers with any radix. Here we specify radix 10 .</li></ul><h4>Now, let’s build a parser for strings.</h4><pre>recursive(|value| {<br> ...<br><br> let string = none_of(&quot;\\\&quot;&quot;)<br>            .repeated()<br>            .collect::()<br>            .delimited_by(just(&#39;&quot;&#39;), just(&#39;&quot;&#39;));<br>})</pre><p>Let’s break this down as well.</p><ul><li>First, we use the none_of() parser, which parses a single token that is <em>not</em> part of a given sequence of tokens. Here, we use it to parse all tokens except \&quot;, which is the opening and closing double quotes character.</li><li>Next, we call repeated() to repeatedly parse the none_of() pattern.</li><li>Then, we collect the result of the repeated parsing into a String. Note that this is possible because each token parsed by repeated() is a char.</li><li>Finally, we apply a combinator delimited_by(), which parses the above pattern, delimited by two other patterns on either side. Most often used to parse parenthesiesed expressions, blocks, or arrays.</li></ul><p>You might wonder why we need this combinator when we’re already ignoring &quot;. The reason is, the parser will not match the first token of the string, &quot; unless we specify something to consume it. There are other ways to consume this character, for example, we could consume it using just(&#39;&quot;&#39;), and then chain another just(&#39;&quot;&#39;) after the none_of() pattern, like the following, but using the delimited_by() combinator just looks cleaner.</p><pre>just(&#39;&quot;&#39;)<br>    .ignore_then(none_of(&quot;\\\&quot;&quot;).repeated().collect::())<br>    .then_ignore(just(&#39;&quot;&#39;));</pre><h4>Now, let’s build a parser for members, i.e anything after the colon (:) in JSON</h4><pre>recursive(|value| {<br> ...<br><br> let member = string.clone()<br>       .then_ignore(just(&#39;:&#39;).padded()).then(value.clone());<br>})</pre><p>There are several interesting things going on here, let’s break them down.</p><ul><li>First, notice that we call clone() on the string parser. That&#39;s because the logic for parsing a JSON key is the same as a string, since a JSON key is indeed, a string. Thus, we can reuse the string parser for the first part of a member.</li><li>Next, we read and ignore the :, it doesn&#39;t give us any useful values so we just consume it and ignore the token. Note that the parser for this has a .padded() call. This also consumes any whitespace around the :.</li><li>Finally, we chain it to value. This can seem a little confusing. What exactly is value here? We know it&#39;s the argument provided to us by the recursive() callback. That is a hint as to its function.</li><li>value is a reference to the top level parser, which allows us to recursively call our top level parser on child values. In this case, we chain it to the member because the &quot;value&quot; part of JSON can be a number, string, object or array, so we have to call the top level parser again to parse those. This is what we mean by a recursive parser.</li></ul><h4>Next, let’s write a parser for arrays.</h4><pre>recursive(|value| {<br> ...<br><br> let array = value<br>      .clone()<br>      .separated_by(just(&#39;,&#39;).padded().recover_with(skip_then_retry_until(<br>          any().ignored(),<br>          one_of(&quot;,]&quot;).ignored(),<br>      )))<br>      .allow_trailing()<br>      .collect::&lt;Vec&lt;Json&gt;&gt;()<br>      .padded()<br>      .delimited_by(<br>          just(&#39;[&#39;),<br>          just(&#39;]&#39;)<br>            .ignored()<br>            .recover_with(via_parser(end()))<br>            .recover_with(skip_then_retry_until(any().ignored(), end())),<br>      );<br>})</pre><p>Whoa, there’s a lot going on here, let’s break it down as usual.</p><ul><li>First, you’ll notice that we start off with a clone of value. This is because array&#39;s children can be any of the valid JSON types, namely numbers, strings, objects, and yes, more arrays.</li><li>Next, we chain it to separated_by(). This behaves just like repeated(), except it requires the values to be separated by a sequence. Here, we separate by a comma , (along with whitespace).</li><li>You’ll notice a curious new function, recover_with() being used here. This is one of chumsky&#39;s powerful error recovery combinators. Here, our strategy is to skip any erroring elements (i.e, elements that do not successfully match any of the defined parsers) until we get either a , or a closing ], which naturally corresponds to the next item, or the end of the array.</li><li>In simple terms, skip any erroring tokens until the next item or end of array.</li><li>Next, we chain allow_trailing(). This is a useful combinator that allows a trailing separator for the separated_by() combinator. In simple terms, this will allow trailing commas in arrays.</li><li>Next, we collect() the parsed elements into a Vec&lt;Json&gt;. Naturally, this corresponds to an array of JSON nodes. Also we append padded() for good measure to gobble up any trailing whitespace.</li><li>Finally, we chain it to delimited_by(), which we use to mark the array as being surrounded by []. Note that we also perform error recovery here. The exact strategy for error recovery here is left as an exercise for the reader 😇</li></ul><h4>We’re in the home stretch here! We just need to write the parser for objects and then we’re done! Let’s get to it.</h4><pre>recursive(|value| {<br>     ...<br>    <br>     let object = member<br>        .clone()<br>        .separated_by(just(&#39;,&#39;).padded().recover_with(skip_then_retry_until(<br>            any().ignored(),<br>            one_of(&quot;,}&quot;).ignored(),<br>        )))<br>        .collect::&lt;HashMap&lt;String, Json&gt;&gt;()<br>        .padded()<br>        .delimited_by(<br>            just(&#39;{&#39;),<br>            just(&#39;}&#39;)<br>                .ignored()<br>                .recover_with(via_parser(end()))<br>                .recover_with(skip_then_retry_until(any().ignored(), end())),<br>        );<br>    })</pre><p>After breaking down the array parser, this should be straightforward to understand. Let’s understand what’s happening here.</p><ul><li>First, we chain to the member parser, since JSON objects can be at the root, or as members.</li><li>Next, we again chain the separated_by() combinator, just like arrays, but with slightly different error recovery (} instead of ]). Note that we don&#39;t accept a trailing separator here because the JSON specification does not allow trailing commas after values.</li><li>We collect() all these values into a HashMap&lt;String, Json&gt;. You might be wondering how we can get both the JSON key and value from this parser; this is due to the .then() combinator on the member parser. .then() combinators return a tuple of the parsed data, of which the first element here is the JSON key, and the chained value is the JSON value.</li><li>Finally, we chain it to delimited_by() again, with similar error recovery as the array parser.</li></ul><p>Now, you might be wondering, we haven’t actually returned any of these values in the parser. Good catch! We will now combine all these parsers into a final one.</p><pre>choice((<br>        just(&quot;null&quot;).to(Json::Null),<br>        just(&quot;true&quot;).to(Json::Bool(true)),<br>        just(&quot;false&quot;).to(Json::Bool(false)),<br>        number.map(Json::Num),<br>        string.map(Json::Str),<br>        array.map(Json::Array),<br>        object.map(Json::Object),<br>    ))<br>  .padded()</pre><ul><li>Here, we use another useful combinator called choice. It simply takes in a tuple of parsers, and returns the output generated by the first one to match. We chain it with padded() for good measure to gobble up any whitespace.</li></ul><p>And that’s it! Our parser is ready.</p><p>Create a file called sample.json with some test JSON data, and run the parser like below:</p><pre>cargo run -- sample.json</pre><p>You should be able to see the output AST similar to this:</p><pre>Some(<br>    Object(<br>        {<br>            &quot;batters&quot;: Object(<br>                {<br>                    &quot;batter&quot;: Array(<br>                        [<br>                            Object(<br>                                {<br>                                    &quot;type&quot;: Str(<br>                                        &quot;Regular&quot;,<br>                                    ),<br>                                    &quot;id&quot;: Str(<br>                                        &quot;1001&quot;,<br>                                    ),<br>                                },<br>                            ),<br>                            Object(<br>                                {<br>                                    &quot;id&quot;: Str(<br>                                        &quot;1002&quot;,<br>                                    ),<br>                                    &quot;type&quot;: Str(<br>                                        &quot;Chocolate&quot;,<br>                                    ),<br>                                },<br>                            ),<br>                        ],<br>                    ),<br>                },<br>            ),<br>            &quot;type&quot;: Str(<br>                &quot;donut&quot;,<br>            ),<br>            &quot;id&quot;: Str(<br>                &quot;0001&quot;,<br>            ),<br>            &quot;name&quot;: Str(<br>                &quot;Cake&quot;,<br>            ),<br>            &quot;ppu&quot;: Num(<br>                55.0,<br>            ),<br>        },<br>    ),<br>)</pre><h3>Conclusion</h3><p>I hope this article has demystified parser combinators and given you a taste of how powerful they can be. If you’re interested in learning more, I encourage you to check out <a href="https://github.com/zesterer/chumsky">chumsky</a>, the parser combinator library used in this article, as well as other parser combinator libraries like <a href="https://github.com/rust-bakery/nom">nom</a> and <a href="https://github.com/Marwes/combine">combine</a>.</p><p>That’s all for now, happy learning!</p><p><em>Originally published at </em><a href="https://kat.bio/blog/parser-combinators"><em>https://kat.bio</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c35a1779ed50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/a-gentle-introduction-to-parser-combinators-c35a1779ed50">A gentle introduction to parser-combinators</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Real with RTP and RTCP]]></title>
            <link>https://medium.com/dyte/getting-real-with-rtp-and-rtcp-177b60cf8610?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/177b60cf8610</guid>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[vidéo]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 13:36:55 GMT</pubDate>
            <atom:updated>2023-03-27T14:54:13.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VcCb0pE67u81TuV5oQg7g.png" /></figure><h3>Introduction</h3><p>Real-time communication over the internet has become increasingly popular in recent years, and WebRTC has emerged as one of the leading technologies for enabling it over the web. WebRTC uses a variety of protocols, including Real-Time Transport Protocol (RTP) and Real-Time Control Protocol (RTCP).</p><p>RTP is responsible for transmitting audio and video data over the network, while RTCP is responsible for monitoring network conditions and providing feedback to the sender. RTP and RTCP communicate over the same network, with RTP using even-numbered ports and RTCP using odd-numbered ports. This allows both protocols to use the same network resources without interfering with each other.</p><p>In this post, we will discuss what RTP and RTCP are and how they work together to enable real-time communication in WebRTC.</p><p>This is the third part of our ongoing WebRTC 102 blog series — in the second one we covered <a href="https://dyte.io/blog/understanding-libwebrtc/">libWebRTC</a> and in the first one, <a href="https://dyte.io/blog/webrtc-102-demystifying-ice/">we tackled ICE</a> and understood how those work under the hood.</p><p>Let’s dive in!</p><p>Real-Time Transport Protocol (RTP)</p><p>Real-Time Transport Protocol (RTP) is a protocol designed for transmitting audio and video data over the internet. RTP is used to transport media streams, such as voice and video, in real-time.</p><p>RTP is responsible for packetizing media data into small packets and transmitting it over the network. Each RTP packet contains a <em>sequence number</em> and <em>timestamp</em>, which are used to ensure that the packets are delivered in the correct order and at the correct time. RTP packets are transmitted over UDP, which provides low latency and is ideal for real-time communication.</p><h4>Real-Time Control Protocol (RTCP)</h4><p>Real-Time Control Protocol (RTCP) is a protocol designed to provide feedback on the quality of service (QoS) of RTP traffic. RTCP is used to monitor network conditions, such as packet loss and delay, and to provide feedback to the sender. RTCP packets are sent periodically to provide feedback on the quality of the RTP stream. They contain statistical information about the RTP stream, including the number of packets sent and received, the number of packets lost, and the delay between packets. This information can be used to adjust the RTP stream to improve the quality of the audio or video.</p><h3>Understanding video compression</h3><p>We will not delve deeply into video compression, but we will cover enough to understand why RTP is designed as it is. Video compression encodes video into a new format that requires fewer bits to represent the same video.</p><h4>Lossy and Lossless Compression</h4><p>Video can be encoded to be lossless (no information is lost) or lossy (information may be lost). RTP usually uses lossy compression to prevent high latency streams and more dropped packets, even if the video quality is not as good.</p><h4>Intra and Inter-Frame Compression</h4><p>Video compression comes in two types: intra-frame and inter-frame. Intra-frame compression reduces the bits used to describe a single video frame. The same techniques are used to compress still pictures, like the JPEG compression method. On the other hand, inter-frame compression looks for ways to not send the same information twice, since video is made up of many pictures.</p><h4>Inter-Frame types</h4><p>There are three frame types in inter-frame compression:</p><ul><li><strong>I-Frame</strong> — A complete picture that can be decoded without anything else.</li><li><strong>P-Frame</strong> — A partial picture that contains only changes from the previous picture.</li><li><strong>B-Frame</strong> — A partial picture that is a modification of previous and future pictures.</li></ul><p>The following is a visualization of the three frame types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CAxMsypsXV35nLvV.png" /></figure><p>It is clear that video compression is a stateful process, posing challenges when transferred over the internet. It leads us to wonder, what happens if part of an I-Frame is lost? How does a P-Frame determine what to modify? As video compression methods become more intricate, these issues become even more pressing. Nonetheless, there is a solution offered by RTP and RTCP.</p><h3>RTP packet structure</h3><p>Every RTP packet has the following structure, as defined in the <a href="https://www.rfc-editor.org/info/rfc3550">RFC</a></p><pre>0                   1                   2                   3<br> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|V=2|P|X|  CC   |M|     PT      |       sequence number         |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|                           Timestamp                           |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|           Synchronization Source (SSRC) identifier            |<br>+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+<br>|            Contributing Source (CSRC) identifiers             |<br>|                             ....                              |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|                            Payload                            |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+</pre><p>The Version is always set to 2.</p><h4>Padding (P)</h4><p>Padding is a boolean that determines whether the payload has padding or not.</p><p>The last byte of the payload indicates the number of padding bytes that were added.</p><h4>Extension (X)</h4><p>If set, the RTP header will contain extensions.</p><h4>CSRC Count (CC)</h4><p>The CSRC Count refers to the number of CSRC identifiers following the SSRC and preceding the payload.</p><h4>Marker</h4><p>The Marker bit has no predetermined meaning and can be used as desired by the user.</p><p>In some cases, it may indicate when a user is speaking, or it may denote a keyframe.</p><h4>Payload Type (PT)</h4><p>The Payload Type is a unique identifier for the codec being carried by this packet.</p><p>For WebRTC, the Payload Type is dynamic, meaning that the Payload Type for VP8 in one call may differ from that of another. The offerer in the call determines the mapping of Payload Types to codecs in the Session Description.</p><h4>Sequence Number</h4><p>The Sequence Number is used for ordering packets in a stream. Every time a packet is sent, the Sequence Number is incremented by one.</p><p>RTP is designed to be useful over lossy networks. This gives the receiver a way to detect when packets have been lost.</p><h4>Timestamp</h4><p>The Timestamp is the sampling instant for this packet. It is not a global clock, but rather represents how much time has passed in the media stream. Several RTP packets can have the same timestamp if, for example, they are all part of the same video frame.</p><h4>Synchronization Source (SSRC)</h4><p>An SSRC is a unique identifier for this stream. This allows multiple streams of media to be run over a single RTP stream.</p><h4>Contributing Source (CSRC)</h4><p>This is a list that communicates which SSRCs contributed to this packet.</p><p>This is commonly used for talking indicators. For example, if multiple audio feeds are combined into a single RTP stream on the server side, this field could be used to indicate which input streams were active at a given moment.</p><h4>Payload</h4><p>This field contains the actual payload data, which may end with the count of how many padding bytes were added if the padding flag is set.</p><h3>RTCP packet structure</h3><p>Every RTCP packet has the following structure:</p><pre>0                   1                   2                   3<br> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|V=2|P|    RC   |       PT      |             length            |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br>|                            Payload                            |<br>+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+</pre><h4>Version (V)</h4><p>The Version is always 2.</p><h4>Padding (P)</h4><p>Padding is a boolean that controls the inclusion of padding in the payload.</p><p>The last byte of the payload includes a count of the added padding bytes.</p><h4>Reception Report Count (RC)</h4><p>This indicates the number of reports included in this packet. A single RTCP packet may contain multiple events.</p><h4>Packet Type (PT)</h4><p>This is a unique identifier for the type of RTCP packet. While a WebRTC agent does not necessarily need to support all these types, there may be differences in support between agents. Some of the commonly seen packet types include:</p><ul><li>192 - Full INTRA-frame Request (FIR)</li><li>193 - Negative Acknowledgements (NACK)</li><li>200 - Sender Report</li><li>201 - Receiver Report</li><li>205 - Generic RTP Feedback</li><li>206 - Payload Specific Feedback (including PLI)</li></ul><h3>RTCP packet types in detail</h3><p>RTCP is a flexible protocol and supports several types of packets. The following details some of the most commonly used packet types.</p><h4>PLI (Picture Loss Indication)/FIR (Full Intra Request)</h4><p>Both FIR and PLI messages serve a similar purpose, requesting a full key frame from the sender. However, PLI is specifically used when the decoder failed to decode partial frames, which could be due to packet loss or decoder crashing.</p><p>As per RFC 5104, FIR should not be used when packets or frames are lost; that is the job of PLI. FIR is used to request a key frame for other reasons, such as when a new member enters a video conference and needs a full key frame to start decoding the video stream. The decoder will discard frames until a key frame arrives.</p><p>However, in practice, software that handles both PLI and FIR packets will send a signal to the encoder to produce a new full key frame in both cases.</p><p>Typically, a receiver will request a full key frame immediately after connecting to minimize the time to the first frame appearing on the user’s screen.</p><p>PLI packets are a part of Payload Specific Feedback messages.</p><h4>NACK (Negative Acknowledgement)</h4><p>When a receiver issues a NACK, it requests that the sender re-transmit a single RTP packet. This is typically done when a packet is lost or delayed. The NACK is preferable to requesting that the entire frame be re-sent because RTP divides packets into small pieces, and the receiver is usually only missing one piece. To request the missing piece, the receiver creates an RTCP message with the SSRC and Sequence Number. If the sender does not have the requested RTP packet to re-send, it will simply ignore the message.</p><h4>Sender and Receiver Reports</h4><p>These reports are crucial for transmitting statistics between agents. They effectively communicate the exact amount of packets that are received as well as the levels of jitter.</p><p>This feature provides valuable diagnostic information and enables effective congestion control. We’ll see more about how these reports are used to overcome unreliable network conditions below.</p><h3>Overcoming unreliable networks</h3><p>Real-time communication is heavily dependent on networks. In an ideal scenario, bandwidth would be unlimited and packets would arrive instantaneously. Unfortunately, networks are limited and conditions can change unexpectedly, making it difficult to measure and observe network performance. Additionally, different hardware, software, and configurations can cause unpredictable behavior.</p><p>RTP/RTCP runs across many different types of networks, so it is common for some communication to be lost between the sender and the receiver. Because it is built on top of UDP, there is no built-in way to retransmit packets or handle congestion control.</p><h4>Measuring and communicating network status</h4><p>RTP/RTCP operates on various network types and topologies, and communication drops may occur from sender to receiver due to this. As they are built on UDP, there is no inherent mechanism for packet retransmission or congestion control.</p><p>For optimal user experience, we must assess network path qualities and adapt to their changes over time. The key traits to monitor are <strong>available bandwidth</strong> (in each direction, which may not be symmetrical), <strong>round trip time</strong>, and <strong>jitter</strong> (variations in round trip time). Our systems must take into account packet loss and convey changes in these properties as network conditions change.</p><p>The protocols have two main objectives:</p><ol><li>Estimate the available bandwidth (in each direction) supported by the network.</li><li>Communicate network characteristics between sender and receiver.</li></ol><h4>Receiver reports / Sender reports</h4><p>Receiver Reports and Sender Reports are sent over RTCP and are defined in <a href="https://tools.ietf.org/html/rfc3550#section-6.4">RFC 3550</a>. They communicate network status between endpoints. Receiver Reports communicate network quality, including packet loss, round-trip time, and jitter. These reports pair with other algorithms that estimate available bandwidth based on network quality.</p><p>Sender and Receiver Reports (SR and RR) together give a picture of network quality. They are sent on a schedule for each SSRC and are used to estimate available bandwidth. The sender estimates available bandwidth after receiving the RR data, which contains the following fields:</p><ul><li><strong>Fraction Lost</strong> — Percentage of packets lost since the last Receiver Report.</li><li><strong>Cumulative Number of Packets Lost</strong> — Number of packets lost during the entire call.</li><li><strong>Extended Highest Sequence Number Received</strong> — Last Sequence Number received and how many times it has rolled over.</li><li><strong>Interarrival Jitter</strong> — Rolling Jitter for the entire call.</li><li><strong>Last Sender Report Timestamp</strong> — Last known time on sender, used for round-trip time calculation.</li></ul><p>These statistics are further fed into bandwidth estimation algorithms such as GCC (Google Congestion Control), which estimate available bandwidth which in turn drives the encoding bitrate and frame resolution.</p><h3>Conclusion</h3><p>In conclusion, RTP and RTCP are essential protocols for enabling real-time communication in WebRTC. RTP is responsible for transmitting audio and video data over the network, while RTCP is responsible for monitoring network conditions and providing feedback to the sender. Together, these protocols enable high-quality real-time communication over the internet. Understanding how RTP and RTCP work together is essential for anyone interested in developing real-time communication applications using WebRTC.</p><h3>References</h3><ul><li><a href="http://www.rfc-editor.org/info/rfc3550">RFC3550</a>(RTP: A Transport Protocol for Real-Time Applications)</li><li><a href="http://www.rfc-editor.org/info/rfc5104">RFC5104</a> (Codec Control Messages in the RTP Audio-Visual Profile with Feedback)</li><li><a href="http://www.rfc-editor.org/info/rfc8888">RFC8888</a> (RTP Control Protocol (RTCP) Feedback for Congestion Control)</li></ul><p><em>Originally published at </em><a href="https://dyte.io/blog/webrtc-rtp-and-rtcp/"><em>https://dyte.io/blog/webrtc-rtp-and-rtcp</em></a><em>/ on March 10, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177b60cf8610" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dyte/getting-real-with-rtp-and-rtcp-177b60cf8610">Getting Real with RTP and RTCP</a> was originally published in <a href="https://medium.com/dyte">Dyte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools of the Trade: Declarative DNS with dnscontrol]]></title>
            <link>https://medium.com/swlh/tools-of-the-trade-declarative-dns-with-dnscontrol-a15d023e88f0?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15d023e88f0</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[stackoverflow]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Fri, 27 May 2022 02:13:04 GMT</pubDate>
            <atom:updated>2022-05-27T03:16:01.982Z</atom:updated>
            <content:encoded><![CDATA[<h4>Effortlessly manage your DNS records declaratively</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*5Y5xGZXg2_i4dDAb.png" /></figure><h3>💡 A bit of context</h3><p>I recently moved my <a href="https://sphericalk.at/">site</a>’s hosting from DigitalOcean to <a href="https://fly.io/">fly.io</a>. That’s when I realized that I’ve been changing DNS records manually for years; go to the Cloudflare dashboard, change records, rinse-repeat…</p><p>As a programmer and self-professed automation fanatic, this rubbed me the wrong way, so I set out to do something about it. Enter DNSControl.</p><h3>🤔 Hold up, what’s that?</h3><p><a href="https://stackexchange.github.io/dnscontrol/">DNSControl</a> is an <strong>opinionated</strong> platform for seamlessly managing your DNS configuration across any number of DNS hosts, both in the cloud or in your own infrastructure.</p><p>It was created by StackOverflow to manage their own domains, and was subsequently open-sourced for the rest of us (Thanks StackOverflow!).</p><p>It lets you <em>declare</em> your DNS records using a JavaScript-ish DSL (domain specific language); for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*QqPgySJ_383spiMa.png" /></figure><h3>Okay, why should I switch?</h3><p>Switching to a new tool can be scary, but here’s some reasons that make DNScontrol unrivaled (in my opinion):</p><ul><li>Supports 10+ DNS Providers including BIND, AWS Route 53, Google DNS, Cloudflare, and name.com</li><li>Enable/disable Cloudflare proxying (the “orange cloud” button) directly from your DNSControl files.</li><li>Apply CI/CD principles to DNS: Unit-tests, system-tests, automated deployment.</li><li>Super extensible! Plug-in architecture makes adding new DNS providers and Registrars easy!</li><li>Eliminate vendor lock-in. Switch DNS providers easily, any time, with full fidelity.</li><li>All the benefits of Git (or any VCS) for your DNS zone data. View history. Accept PRs.</li></ul><p>And much more!</p><h3>🤨 Wait! I heard opinionated?</h3><p>That’s right. DNSControl has opinions about how to manage DNS. However, that isn’t a bad thing. Let’s go over their opinions and see which ones really affect us.</p><ol><li>DNS should be treated like code: Code is written in a high-level language, version controlled, commented, tested, and reviewed by a third party… and all of that happens before it goes into production.</li><li>Non-experts should be able to safely make DNS changes.</li><li>All DNS is lowercase for languages that have such a concept.</li><li>Users should state what they want, and DNSControl should do the rest.</li><li>If it is ambiguous in DNS, it is forbidden in DNSControl.</li><li>Hostnames don’t have underscores.</li></ol><p>These make total sense. To read more about the opinions and the reasons behind them, check out the <a href="https://stackexchange.github.io/dnscontrol/opinions">documentation</a>.</p><h3>✅ Okay, I’m convinced. How do I begin?</h3><p>Glad to hear it! To get started, first install DNSControl.</p><pre>go install github.com/StackExchange/dnscontrol/v3@latest</pre><p>Now, create a file called dnsconfig.js. This will house all the records for your site(s). Populate it with the starter boilerplate:</p><pre>// Providers<br>var REG_NONE = NewRegistrar(&#39;none&#39;);    // No registrar.<br>var DNS_BIND = NewDnsProvider(&#39;bind&#39;);  // ISC BIND.<br><br>// Domains<br>D(&#39;example.com&#39;, REG_NONE, DnsProvider(DNS_BIND),<br>    A(&#39;@&#39;, &#39;1.2.3.4&#39;)<br>);</pre><p>Next, create a file called creds.json for storing provider configurations (API tokens and other account information). For example, to use both name.com and Cloudflare, you would have:</p><pre>{<br>  &quot;cloudflare&quot;: {<br>    &quot;TYPE&quot;: &quot;CLOUDFLAREAPI&quot;,<br>    &quot;accountid&quot;: &quot;your-cloudflare-account-id&quot;,<br>    &quot;apitoken&quot;: &quot;your-cloudflare-api-token&quot;<br>  },<br>  &quot;namecom&quot;: {<br>    &quot;TYPE&quot;: &quot;NAMEDOTCOM&quot;,<br>    &quot;apikey&quot;: &quot;key&quot;,<br>    &quot;apiuser&quot;: &quot;username&quot;<br>  },<br>  &quot;none&quot;: { &quot;TYPE&quot;: &quot;NONE&quot; } // the no-op provider<br>}</pre><p>For a complete list of providers and how to use them, check out the <a href="https://stackexchange.github.io/dnscontrol/provider-list">provider docs</a>.</p><blockquote><strong><em>Warning</em></strong><em>: Remember to add </em><em>creds.json to your </em><em>.gitignore </em>before<em> committing and pushing your configuration.</em></blockquote><p>Now, run dnscontrol preview and make sure that it completes with no errors. The preview command is the &quot;dry run&quot; mode that shows what changes need to be made and never makes any actual changes. It will use APIs if needed to find out what DNS entries currently exist.</p><p>The results should look something like this:</p><pre>dnscontrol preview<br>Initialized 1 registrars and 1 dns service providers.<br>******************** Domain: example.com<br>----- Getting nameservers from: bind<br>----- DNS Provider: bind... 1 correction<br>#1: GENERATE_ZONEFILE: example.com<br> (2 records)<br><br>----- Registrar: none<br>Done. 1 corrections.</pre><p>Next, run dnscontrol push to actually make the changes. In this case, the change will be to create a zone file where one didn&#39;t previously exist.</p><pre>dnscontrol push<br>Initialized 1 registrars and 1 dns service providers.<br>******************** Domain: example.com<br>----- Getting nameservers from: bind<br>----- DNS Provider: bind... 1 correction<br>#1: GENERATE_ZONEFILE: example.com<br> (2 records)<br><br>CREATING ZONEFILE: zones/example.com.zone<br>SUCCESS!<br>----- Registrar: none<br>Done. 1 corrections.</pre><h3>⚙️ I already have many DNS records set up. How do I import them?</h3><p>This was a problem I faced myself, and this is how you import your existing DNS configurations.</p><p>Most DNS Service Providers have an ‘export to zonefile’ feature. (If yours doesn’t, consider moving to Cloudflare; It’s free, they’ll import all your records during setup, and will let you export a zonefile)</p><p>Place this zonefile inside a directory called zones in the directory where your dnsconfig.js resides. Rename the zonefile to &lt;domain&gt;.zone. Your directory structure should now look something like this:</p><pre>.<br>├── creds.json<br>├── dnsconfig.js<br>└── zones<br>    └── example.com.zone</pre><p>Next, run the following command:</p><pre>dnscontrol get-zones --format=js --out=draft.js bind BIND example.com</pre><p>Now you can copy the contents of draft.js to dnsconfig.js and modify as needed.</p><h3>🚀 Lastly, some advice for running in production</h3><ul><li>Store the configuration files in Git.</li><li>Encrypt or completely omit the creds.json file before storing it in Git. Do NOT store API keys or other credentials without encrypting them. Use a CI/CD tool like Github Actions/Jenkins/CircleCI/etc. to automatically push DNS changes.</li><li>Join the DNSControl community. File <a href="https://github.com/StackExchange/dnscontrol">issues and PRs</a>.</li></ul><p>I hope this tool as just as useful to you as it is to me. Stay tuned for further posts about useful tooling.</p><p><em>Originally published at </em><a href="https://sphericalk.at/blog/27-05-22_Tools-of-the-Trade:-Declarative-DNS-with-dnscontrol"><em>https://sphericalk.at</em></a><em> on May 27, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15d023e88f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/tools-of-the-trade-declarative-dns-with-dnscontrol-a15d023e88f0">Tools of the Trade: Declarative DNS with dnscontrol</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tools of the Trade: Dyte CLI]]></title>
            <link>https://sphericalkat.medium.com/tools-of-the-trade-dyte-cli-2307b0f3a873?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/2307b0f3a873</guid>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Thu, 05 May 2022 12:30:00 GMT</pubDate>
            <atom:updated>2022-05-05T13:12:16.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P5SmQan2HVKl5IV3.jpg" /></figure><p>Dyte CLI brings <a href="https://dyte.io/">Dyte</a> to your terminal. It reduces context switching, helps you focus, and empowers you to more easily script and create your own workflows on top of Dyte.</p><p>With our CLI, you can:</p><ul><li>Run your entire Dyte workflow from the terminal, from meetings through recordings</li><li>Play around with webhooks</li><li>Release your own custom plugins</li></ul><h3>🎬 From meetings to recordings</h3><p>The inherent scriptability brought to you by a CLI lets you chain many logical actions together. For example, you could have a workflow like:</p><ul><li>You’re an ed-tech startup and have a quick extra session scheduled for your students. Let’s create a meeting in a jiffy:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AIqkeJokFrTcSUan.jpeg" /><figcaption>Create meeting UX</figcaption></figure><ul><li>Now that you have a meeting to work with, you can share the link with your students and have your session 🤝.</li><li>You’ve noticed some people are tardy or completely skip extra sessions. Not good 😠. What can we do? We can keep a track of who joins using webhooks!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E9I_GlZ3-mVTOe_w.jpeg" /><figcaption>Create webhook UX</figcaption></figure><ul><li>Oh, the session is very important, you should record this!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u9LFrUCYf022mV0b.jpeg" /><figcaption>Start Recording UX</figcaption></figure><p>And that’s just an example of how you can make Dyte CLI your own!</p><h3>🎨 Design considerations</h3><p>While a CLI might not have a lot of snazzy eye-candy like a <a href="https://dyte.io/">website</a> or an app, the design that goes into it is just as important.</p><p>We kept a lot of things in mind while designing the CLI so that our end-users have the best possible experience while using it. Here’s a few of the things that went on in our heads while we were working on it:</p><h4>#️⃣ POSIX compliance</h4><p>Unix-like operating systems popularised the use of the command line and tools such as awkand sed. Such tools have effectively standardised the behaviour of command line options (aka flags), options-arguments, and other operands.</p><p>Why is it important? Users might get confused if our CLI’s syntax for arguments, options, or command parameters deviate from the de facto Unix standards they are used to.</p><p>Some examples of expected behaviour:</p><ul><li>Option-arguments or options can be notated in help or examples as square brackets ([]) to indicate they are optional, or with angle brackets (&lt;&gt;) to indicate they are required.</li><li>Allowing short-form single letter arguments as aliases for long-form arguments (see reference from the <a href="https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html">GNU Coding Standards</a>).</li><li>specifying multiple options with no values may be grouped, such as dyte -abc being equivalent to dyte -a -b -c.</li></ul><h4>💕 Empathy for the user</h4><p>We’ve put workflows in place that assist the user in interacting with the CLI successfully. We understand the frustration that comes with being unable to use an unfamiliar tool effectively, and we’re here to help you through it!</p><p>As we’ve seen while starting a recording, the start subcommand takes in a meeting ID. Failing to pass in one and being presented with an error would get pretty frustrating!</p><p>And so, we’ve taken care to prompt the user gently for any parameters they miss out on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kPylpV_djzi8KXnQ.jpeg" /><figcaption>Prompting the user</figcaption></figure><h4>✨ Rich interactions and a colourful experience</h4><p>We’ve leveraged rich command-line interactions beyond that of plain text input to provide a smoother experience for our users.</p><p>The CLI makes heavy use of prompts, drop-down selections, hidden password inputs, auto-complete and searchable lists.</p><p>Moving on to colour, most terminals used today to interact with command line applications support coloured text. We’ve made use of this to highlight important bits of output, and to draw your attention to things that might otherwise get lost in an otherwise text-heavy experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ge0VCC_qboyuPyod.jpeg" /><figcaption>Important information is highlighted in colour</figcaption></figure><h4>🧠 Stateful data</h4><p>We’ve strived to provide a stateful experience, by remembering values and data where we can to improve future interactions.</p><p>This is important to ensure we don’t bug the user to enter the same information again and again.</p><p>All data stored by the CLI can be found at ~/.config/dyte</p><h4>🧹 Cleaning up</h4><p>We’re sad to see you go, but look forward to seeing you again! We don’t leave any configuration files behind when you uninstall the CLI by leveraging the convenient postuninstall <a href="https://docs.npmjs.com/misc/scripts">script</a> that NPM provides.</p><h4>📦 Zero dependencies</h4><p>Okay, that was a bit misleading. We certainly use a few dependencies to make the CLI great, we’re not <em>that</em> good 😛.</p><p>What we do however, is bundle all these dependencies, and our own code into a single JS file using the nifty <a href="https://github.com/vercel/ncc">ncc</a> tool (thanks <a href="https://vercel.com/">Vercel</a>!)</p><p>This lets us ship the CLI without having to worry about any breaking changes in dependencies or nasty supply-chain attacks (remember left-pad and colors.js?). This way, you get exactly what our CI systems build and publish, Untouched by Human Hands™️</p><h3>🔥 Where can I get it?</h3><p>The Dyte CLI is currently available on the <a href="https://www.npmjs.com/package/@dytesdk/cli">NPM registry</a>. Please also take a moment to check out how to use the CLI in our comprehensive <a href="https://docs.dyte.io/cli/installation">docs</a>.</p><p>We’re also planning on open-sourcing the CLI soon, so keep a watch out for any announcements in that space and feel free to contribute!</p><h3>Wrapping up</h3><p>We’ve tried to make the usage of Dyte’s CLI to be as pleasant and painless as possible. Using it, you can automate an end-to-end workflow without having to interact with dashboards or our API directly.</p><p>We’ve already been using the CLI internally for months now, so bugs should be few and far between. Even so, if you find any, please report them to us!</p><p>Take your Dyte experience to new heights with the CLI!</p><p><em>Originally published at </em><a href="https://blog.dyte.io/tools-of-the-trade-dyte-cli/"><em>https://blog.dyte.io</em></a><em> on May 5, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2307b0f3a873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Cloudflare Workers and GitHub Actions to Deploy Statically Generated Sites]]></title>
            <link>https://medium.com/swlh/using-cloudflare-workers-and-github-actions-to-deploy-statically-generated-sites-c96b502d49c4?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/c96b502d49c4</guid>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 21:44:40 GMT</pubDate>
            <atom:updated>2020-12-09T10:50:11.153Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploying performant websites at massive scale has never been easier (or cheaper)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1x927ioZ8Yz7RsB.png" /></figure><h3>All hail the JAMStack</h3><p>Sites built on the JAMStack are all the rage these days; they’ve become a popular alternative to full-stack frameworks and server-side rendered web applications. They’re lightweight, performant, and are extremely easy to deploy on platforms like <a href="https://vercel.com/">Vercel</a> or <a href="https://netlify.com/">Netlify</a>. With that in mind, let’s take a look at how we can step up our deployment game and reduce load times to a minimum.</p><h4>Netlify is great…. but?</h4><p>Enter Cloudflare Workers. Workers are a serverless platform that allow you to deploy code in various languages like JavaScript, Rust, Python, Kotlin etc. A huge advantage that they possess over other serverless platforms such as AWS Lambda is that workers automatically deploy your code across the globe, thanks to Cloudflare’s massive CDN.</p><h4>Serverless code is great, but what about content?</h4><p>Workers also recently released a KV store, that can be used to store static content such as CSS or JS chunks. This makes workers ideal for deploying a performant site at massive scale.</p><h3>That’s great! How do we use one?</h3><p>Whoa there, hold yer horses. Let’s understand what a worker does exactly before jumping into it.</p><p>A worker is a piece of code that’s executed when a particular route on a website proxied by Cloudflare is accessed, <em>before</em> the request reaches Cloudflare’s cache.</p><p>The following is a super simple worker, which just responds with a Hello World!.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/657f5463af5b8ec12e1ecffb6ae9639c/href">https://medium.com/media/657f5463af5b8ec12e1ecffb6ae9639c/href</a></iframe><h4>Wrangling your workers with wrangler</h4><p>Cloudflare has a great tool to configure workers called wrangler. Install it globally using:</p><pre># With NPM<br>npm i -g @cloudflare/wrangler</pre><pre># With yarn<br>yarn global add @cloudflare/wrangler</pre><p>Or just add it to your devDependencies.</p><p>Now we need to authorize wrangler to create and edit workers. Run wrangler login to automatically add an API key to your local wrangler config file.</p><h4>Configuring a domain</h4><p>Every site needs a domain, and our site is no different! First, you need your domain to be added to the Cloudflare dashboard. I already have <a href="https://sphericalkat.dev/">sphericalkat.dev</a> added to mine.</p><p>In the DNS section, add a record of type A, with whatever subdomain you wish that points to any unreachable IP address like 192.2.0.1. This isn’t strictly necessary, but it’s recommended since our worker will intercept all requests and the IP will never resolve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPAwz7akuOu7FzdeiDycQQ.png" /><figcaption>DNS record</figcaption></figure><h4>Creating a statically generated site</h4><p>Any static site generator should work for this step. I’m personally using Next.js, but you can use whichever one you like.</p><p>Add @cloudflare/wranglerto your devDependencies and set up a wrangler project locally. This will be useful for deploying the site from GitHub actions.</p><pre>❯ yarn add -D @cloudflare/wrangler<br>❯ wrangler init --site site-worker</pre><pre>⬇️ Installing cargo-generate...<br>🔧   Creating project called `workers-site`...<br>✨   Done! New project created /Users/sphericalkat/WebstormProjects/sphericalkat.dev/workers-site<br>✨  Succesfully scaffolded workers site<br>✨  Succesfully created a `wrangler.toml`</pre><p>We’ve got a bunch of new files. Let’s take a look:</p><ul><li>workers-site directory: Contains our worker inside an index.js file, and the necessary dependencies</li><li>wrangler.toml file: worker deployment configuration</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82f87ef7ebd9336129a23526ec5ec0d6/href">https://medium.com/media/82f87ef7ebd9336129a23526ec5ec0d6/href</a></iframe><p>The above are the contents of the index.js worker. We don’t need to modify this for now, but we’ll make some changes later to get page routing working.</p><p>However, wrangler.toml needs some updates, which are highlighted below in <strong>bold</strong>.</p><pre>name = &quot;site-worker&quot;<br>type = &quot;webpack&quot;<br>account_id = &quot;<strong>&lt;YOUR ACCOUNT ID&gt;</strong>&quot;<br>workers_dev = <strong>true</strong></pre><pre>[site]<br>bucket = &quot;<strong>./out</strong>&quot;<br>entry-point = &quot;workers-site&quot;</pre><p>We can now run wrangler publish to deploy our site to a staging environment.</p><pre>❯ wrangler publish</pre><pre>✨  Built successfully, built project size is 13 KiB.<br>🌀  Created namespace for Workers Site &quot;__site-worker-workers_sites_assets&quot;<br>✨  Success<br>🌀  Uploading site files<br>✨  Successfully published your script to<br> <a href="https://site-worker.amolele.workers.dev/">https://site-worker.amolele.workers.dev</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gy57c43joA4TtmD_4Iiw9g.png" /><figcaption>Staging site deployment</figcaption></figure><p>Success! As we can see, the site is now live (and loads super fast) at the URL that wrangler gave us. However you might notice that page routing is broken on reloads. Let’s fix that by modifying the index.js inside workers-site.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b66c619dcb55423ff204c81dc1535a96/href">https://medium.com/media/b66c619dcb55423ff204c81dc1535a96/href</a></iframe><p>This modified worker file appends a .html extension to the path internally if routing fails, which allows our page routes to be loaded successfully.</p><h3>Deploying to production</h3><p>We don’t always want our site hosted at the temporary URL that Cloudflare gave us, and we most definitely don’t want to publish our site manually every time we make some changes. Let’s remedy that.</p><h4>Enter GitHub actions</h4><p>GitHub actions allow us to run workflows on any GitHub actions. We’ll be using an action triggered by a push to deploy our site. Let’s create a workflow config file at .github/workflows/workers-deploy.yml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7ac143b054a60408f8f189a22580e2/href">https://medium.com/media/af7ac143b054a60408f8f189a22580e2/href</a></iframe><p>You might have noticed the workflow file using some secrets. Well done! These secrets are necessary since we don’t want to expose our API token and account/zone ids to the entire world. Add them from your repo settings like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEZxyyqy40Nz3d6-dlQJcg.png" /><figcaption>GitHub actions secrets</figcaption></figure><p>We also need some modifications to the wrangler.toml for production deployments. The modifications are marked in bold.</p><pre>type = &quot;webpack&quot;<br>workers_dev = false</pre><pre>[site]<br>bucket = &quot;./out&quot;<br>entry-point = &quot;workers-site&quot;</pre><pre><strong>[env.production]<br>name = &quot;site-worker-production&quot;<br>route = &quot;sphericalkat.dev/*&quot;</strong></pre><p>The production options point a route to our worker. This is necessary for accessing the site using our custom domain.</p><p>Let’s see if the deploy worked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIQtQij7lmu5K9CNIulUPg.png" /><figcaption>Github actions output</figcaption></figure><p>Looks like it did. And sure enough, the site is live at <a href="https://sphericalkat.dev/">sphericalkat.dev</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjwV96piFGvFRPGmOMHpzQ.png" /><figcaption>Production deployment</figcaption></figure><h3>Conclusions</h3><ul><li>Sites require a CDN to be performant. Cloudflare is a known and proven solution.</li><li>Cloudflare Workers and Cloudflare Workers KV allows us to directly deploy statically generated sites to the edge.</li><li>We can use CI/CD pipelines to automate deployments.</li></ul><p>That’s all folks, stay safe and have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c96b502d49c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-cloudflare-workers-and-github-actions-to-deploy-statically-generated-sites-c96b502d49c4">Using Cloudflare Workers and GitHub Actions to Deploy Statically Generated Sites</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idiomatic TensorFlow on Android — Get started with the TensorFlow Support Library]]></title>
            <link>https://levelup.gitconnected.com/idiomatic-tensorflow-on-android-get-started-with-the-tensorflow-support-library-c12fe96bc029?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12fe96bc029</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 20:55:05 GMT</pubDate>
            <atom:updated>2020-06-08T14:00:47.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>Idiomatic TensorFlow on Android — Get started with the TensorFlow Support Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjsEPItNww_khr8o2me-xg.png" /></figure><h3>Working with data on Android is inconvenient!</h3><p>If you’ve used TensorFlow Lite on Android before, chances are that you’ve had to deal with the tedious task of pre-processing data, working with Float arrays in a statically typed language or resize, transform, normalize, and do any of the other standard tasks required before the data is fit for consumption by the model.</p><p>Well, no more! The <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/experimental/support/java">TFLite support library</a> nightly is now available, and in this post, we’ll go over its usage and build a wrapper around a tflite model.</p><blockquote><strong>Note: </strong>A companion repository for this post is available <a href="https://github.com/ATechnoHazard/object-detection-yolo">here</a>. Follow along, or jump straight into the source!</blockquote><p>A big thank you to <a href="https://medium.com/u/46b642aa7f12">Tanmay Thakur</a> and <a href="https://medium.com/u/d1a8d99d1836">Ubaid Usmani</a> for their help in the python implementation. Without their assistance, this wouldn’t have been possible.</p><h3>Scope of this post</h3><p>This post is limited in scope to loading and creating a wrapper class around a tflite model; however, you can see a fully functional project in the repository linked above. The code is liberally commented and very straightforward.</p><p>If you still have any queries, please don’t hesitate to reach out to me and drop a comment. I’ll be glad to help you out.</p><h3>Setting up the project</h3><p>We’re going to be deploying a <a href="https://github.com/ATechnoHazard/yolo-tflite">TFLite version</a> of the popular YOLOv3 object detection model on an Android device. Without further ado, let’s jump into it.</p><p>Create a new project using Android Studio, name it anything you like, and wait for the initial gradle sync to complete. Next, we’ll install the dependencies.</p><h4>Adding dependencies</h4><p>Add the following dependencies to your app-level build.gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5eae347f71ebe28ade23ae4b1fbc016/href">https://medium.com/media/a5eae347f71ebe28ade23ae4b1fbc016/href</a></iframe><p>Let’s go through what they are, and why we need them.</p><ol><li><strong>Quick Permissions</strong>: This is a great library to make granting permissions quick and easy.</li><li><strong>Tensorflow Lite</strong>: This is the core TFLite library.</li><li><strong>Tensorflow Lite Support</strong>: This is the support library we’ll be using to make our data-related tasks simpler.</li><li><strong>CameraView</strong>: This is a library that provides a simple API for accessing the camera.</li></ol><h4>Configuring the gradle project</h4><p>Our project still needs a little more configuration before we’re ready for the code. In the app-level build.gradle file, add the following options under the android block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ff9d18c8d8f468b0ed1d8014109510/href">https://medium.com/media/71ff9d18c8d8f468b0ed1d8014109510/href</a></iframe><p>The reason we need to add this is because we’ll be shipping the model inside our assets, which compresses it by default. This is an issue because compressed models cannot be loaded by the interpreter.</p><blockquote><strong>Note:</strong> After this initial configuration, run the gradle sync again to fetch all dependencies.</blockquote><h3>Jumping into the code</h3><p>First things first; we need a model to load. The one I used can be found <a href="https://raw.githubusercontent.com/ATechnoHazard/yolo-tflite/master/models/detect.tflite">here</a>. Place the model inside app/src/main/assets. This will enable us to load it at runtime.</p><p>The labels for detected objects can be found <a href="https://raw.githubusercontent.com/ATechnoHazard/object-detection-yolo/master/app/src/main/assets/labelmap.txt">here</a>. Place them in the same directory as the model.</p><blockquote><strong>Warning:</strong> If you plan to use your own custom models, a word of caution; the input and output shapes may not match the ones used in this project.</blockquote><h4>Creating a wrapper class</h4><p>We’re going to wrap our model and its associated methods inside a class called YOLO. The initial code is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e664e1297c0d2ecb7ee145e1c33717fb/href">https://medium.com/media/e664e1297c0d2ecb7ee145e1c33717fb/href</a></iframe><p>Let’s break this class down into its core functionality and behaviour.</p><ol><li>First, upon being created, the class loads the model from the app assets through the FileUtil class provided by the support library.</li><li>Next, we have a class member. The interpreter is self-explanatory, it’s an instance of a TFLite interpreter.</li><li>Finally, we have some static variables. These are just the file names of the model and the labels inside our assets.</li></ol><p>Moving on, let’s add a convenience method to load our labels from the assets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/207ea664587e7796544c60cc7d4a98b6/href">https://medium.com/media/207ea664587e7796544c60cc7d4a98b6/href</a></iframe><p>Here we’ve declared a method that loads the label file and lazily initialized a member var to the returned value.</p><p>Let’s get down to the brass tacks. We’re now going to define a method that takes in a bitmap, passes it into the model and returns the detected object classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39cd781a66957af2cb7a81734afb1f8a/href">https://medium.com/media/39cd781a66957af2cb7a81734afb1f8a/href</a></iframe><p>Whoa, that’s a wall of code! Let’s go through it and break it down.</p><p>We’ve declared some new lazily initialized variables; an ImageProcessor and a TensorImage. These are classes exposed by the support library, to make loading images and processing them much simpler.</p><p>As is shown here, we can load a bitmap directly into the TensorImage and then pass it on to the ImageProcessor for further processing.</p><p>The ImageProcessor has several operations available, but the one we’ve used here is to resize our input images to 300 * 300. This is because our model’s input size requires a 300 * 300 image.</p><p>After processing the image, we create several TensorBuffers. These are representations of Tensors that we can manipulate and access easily. The shapes of these TensorBuffers is determined by the model. Take a look at the model summary to figure out the appropriate shapes.</p><p>We load the TensorImage into the input TensorBuffer, and then pass the input and output buffers into the interpreter.</p><blockquote><strong>Note:</strong> The YOLOv3 model has multiple outputs. This is the reason why we had to use multiple output buffers.</blockquote><p>After running inference, the interpreter sets the internal FloatArrays of the output buffers. Right now, we’re only interested in the one that contains the predicted classes. Using the convenient kotlin map function, we map labels to the numerical classes output by the model and return them.</p><p>This class can now be used by our application to run inference on a bitmap. How convenient!</p><h3>Conclusion</h3><p>And that’s it! Compared to a project without using the support library; we’d have written much more code to resize the image, convert bitmaps to float arrays, allocate float arrays manually to store the output in, etc.</p><p>The TensorFlow support library thus makes life simpler for a developer; and despite being a nightly, it’s pretty stable in my experience.</p><p>To find out more, view the support library readme <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/experimental/support/java/README.md">here</a>. As of now, there aren’t any formal docs available, but the readme contains all the information a developer would need to get started quickly.</p><p>Stay safe, and have fun!</p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12fe96bc029" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/idiomatic-tensorflow-on-android-get-started-with-the-tensorflow-support-library-c12fe96bc029">Idiomatic TensorFlow on Android — Get started with the TensorFlow Support Library</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Work From Home to automated ChatOps: A story of Infrastructure Deployments]]></title>
            <link>https://medium.com/hackonhackathon/work-from-home-to-automated-chatops-a-story-of-infrastructure-deployments-e3380514330f?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3380514330f</guid>
            <category><![CDATA[chatops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[zulip]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Sun, 17 May 2020 20:46:46 GMT</pubDate>
            <atom:updated>2020-05-21T19:18:50.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sd50m5VidzQA8wzhJiFHhQ.jpeg" /></figure><p>I recently participated in the <a href="https://hackon.devfolio.co/">HackOn Hackathon</a>, a pan-India hackathon sponsored by some big names in the tech world: <a href="http://www.google.com/">Google</a>, <a href="http://www.github.com/">GitHub</a>, <a href="http://www.elastic.co/">Elastic</a>, <a href="https://www.ibm.com/in-en">IBM</a>, <a href="https://zulipchat.com/">Zulip</a>, and <a href="https://devfolio.co/hackathons">Devfolio</a>.</p><p>I was stuck at home due to the COVID-19 pandemic and wanted something fun to do when my friend Pragati (who was also my teammate for the hackathon) told me about HackOn. Naturally, we were in.</p><p>If you’d like to skip to the code directly, you can find the GitHub repository <a href="https://github.com/ATechnoHazard/globespinner">here</a>.</p><h3>The inspiration</h3><p>We were initially brainstorming ideas, when I remembered something my dad had said. I’m interested in all things tech, which apparently includes anecdotes about corporate culture and happenings. One of these anecdotes involved the Operations head of the project my dad was working on.</p><p>The Ops head had apparently been stuck in a rural area with poor network connectivity, no corporate laptop, and only a smartphone with mobile data. Apparently, he’d walked some people through deploying cloud infra over a call, but let’s not digress.</p><p>This got us thinking; what if we <em>could</em> deploy cloud infra from a phone, just using a simple chat interface? This seemed to fit right in with the Zulip problem statement of the hackathon. And thus we got to work.</p><h3>A bot takes shape</h3><p>I’ve been interested in DevOps for years, and I knew right off the bat what I wanted to use for actually deploying the infra: <a href="https://terraform.io/">Terraform</a>. This awesome tool by HashiCorp works with <em>every single</em> cloud provider out there, effectively making this a universal deployment platform.</p><p>As for the interface, I was originally planning to go for a simple command-based bot, but Pragati suggested that we spice things up a bit by implementing NLP using DialogFlow.</p><p>I ended up writing the Terraform deployment configs, while Pragati worked on custom DialogFlow intents and entities. We wrapped this up together neatly in a Zulip bot written using their Python SDK.</p><p>The bot can understand natural language and take the necessary action. A demonstration video is available below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FC-4PRmTXpGY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DC-4PRmTXpGY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FC-4PRmTXpGY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3ba84e87bcbb9d2563a59ed59fd3bf2/href">https://medium.com/media/e3ba84e87bcbb9d2563a59ed59fd3bf2/href</a></iframe><h3>Our HackOn experience</h3><p>Both of us love participating in hackathons, so it’s no surprise that we enjoyed this one as well. We ended up learning new ways to collaborate when working remotely and had a blast actually testing it out. NLP/ChatOps is fun!</p><p>The primary communication channel (<a href="http://telegram.hackon.tech/">Telegram</a>) chosen by the organizers was particularly convenient for me, considering I spend most of my time online there, so that’s another plus.</p><p>Seeing this confluence of talented developers in a single place was a bit overwhelming and frankly triggered my Impostor Syndrome, but we ended up chatting with everyone and even made a few friends along the way.</p><h3>What’s next?</h3><p>This project was intended as a fun little diversion, but we hadn’t actually anticipated how powerful it could be. Considering this now, we’ve made the project open source for other contributors, and are planning to actively maintain it (and make it viable for use in actual production environments).</p><p>Also, in the long run, we’d like to add a snazzy metrics dashboard, along with application monitoring using something like <a href="https://sentry.io/">Sentry</a>.</p><p>In our closing statement, we’d just like to say thank you to everyone who helped us out, and encourage people to go outside their comfort zone and take part in fun events like these.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3380514330f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackonhackathon/work-from-home-to-automated-chatops-a-story-of-infrastructure-deployments-e3380514330f">Work From Home to automated ChatOps: A story of Infrastructure Deployments</a> was originally published in <a href="https://medium.com/hackonhackathon">HackOn</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating performant REST APIs with Rust using Rocket, Diesel and Serde — Part 1]]></title>
            <link>https://medium.com/gdg-vit/creating-performant-rest-apis-with-rust-using-rocket-diesel-and-serde-part-1-7d842eccdee5?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d842eccdee5</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Thu, 07 May 2020 06:46:33 GMT</pubDate>
            <atom:updated>2020-05-15T15:44:20.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating performant REST APIs with Rust using Rocket, Diesel and Serde — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3TuSHu_tyikliROgbxP6g.jpeg" /></figure><h3>Why Rust?</h3><p>I’ve been hearing about Rust and its powerful features for a while now, and I finally decided to try it out for myself. If you don’t know, here’s a short summary of why Rust is gaining popularity.</p><ol><li>Rust is extremely safe. It prevents the programmer from making mistakes that might lead to unsafe behaviour (such as data races).</li><li>Rust is highly performant, on par with C/C++. This makes it a great alternative for systems programming, where speed <em>and </em>safety are critical.</li><li>Rust has a growing community, and an official package manager called cargo, with many packages (called crates) available at <a href="http://crates.io/">crates.io</a>.</li></ol><p>There’s been a lot of buzz around Rust, from large corporates such as Microsoft, who <a href="https://www.zdnet.com/article/microsoft-our-rust-programming-language-windows-runtime-library-is-now-in-preview/">expressed interest</a> in switching to Rust for systems programming, to relatively smaller operators such as Discord, who are already <a href="https://blog.discord.com/why-discord-is-switching-from-go-to-rust-a190bbca2b1f">using Rust in production</a> to power their microservices.</p><h3>What’s in scope for this tutorial?</h3><p>We’ll cover everything from setting up Rust to the final outcome (a fully functional CRUD RESTful API) in detail. Don’t hesitate to ask any questions you have! A companion repo for this project is available <a href="https://github.com/ATechnoHazard/hello-rocket">here</a>.</p><p>Don’t be alarmed if you don’t understand everything straightaway, Rust does have a rather steep learning curve, but the rewards are worth it! :)</p><blockquote><strong>Note</strong>: This guide expects a basic understanding of programming, syntax, and the ownership model of Rust. If you’re unfamiliar, check out the <a href="https://doc.rust-lang.org/book/">Rust Book</a> before proceeding.</blockquote><h3>Crates we’ll be using</h3><ol><li><a href="https://rocket.rs/"><strong>Rocket</strong></a><strong> — </strong>Write <em>fast</em>, secure web applications without compromising on flexibility.</li><li><a href="https://serde.rs/"><strong>Serde</strong></a><strong> — </strong>Popular framework for Serializing and Deserializing Rust data structures into JSON.</li><li><a href="https://diesel.rs/"><strong>Diesel</strong></a><strong> — </strong>Safe, Extensible ORM and Query Builder for Rust.</li></ol><h3>Setting up Rust on your machine</h3><p>If you don’t have Rust installed already, it’s very easy to get it up and running! Simply follow the instructions at <a href="https://rustup.rs/">rustup.rs</a>, and you’ll have a working Rust install.</p><p>After ensuring Rust is installed, we need to set up a Rust project. This can be done using the following command.</p><pre>cargo new hello-rocket --bin &amp;&amp; cd hello-rocket</pre><p>Before we continue, we need to switch to the nightly Rust build, because Rocket requires some features which aren’t in the stable branch yet.</p><pre>rustup override set nightly<br>rustup update &amp;&amp; cargo update</pre><p>These commands will switch you to the nightly channel for <em>this project only</em>, and ensure everything is up-to-date. With that out of the way, let&#39;s move on to a simple hello-world REST API.</p><h3>Hello, World!</h3><p>Every programmer knows these words, and for good reason. While it looks deceptively simple at first, there’s actually a lot we can learn from a Hello World application. Let’s begin by adding some base dependencies to our Cargo.toml file.</p><blockquote><strong>Note</strong>: Cargo.toml is an analogue to package.json for NPM projects or go.mod for Go modules.</blockquote><pre>[dependencies]<br>rocket = &quot;0.4.4&quot;<br>rocket_codegen = &quot;0.4.4&quot;</pre><p>These will get us set up for creating an API using Rocket. Let’s take a look at the basic hello-world application. Add the following code to src/main.rs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6b8a125cfa8b3a0df6c6514afc0ff09/href">https://medium.com/media/d6b8a125cfa8b3a0df6c6514afc0ff09/href</a></iframe><p>Let’s examine what each part does. The top feature flags are used to enable some nightly features that Rocket uses. Not much to look at there.</p><p>The next statement brings rocket’s public functions and macros into local scope. Think of it as being similar to using namespace in C++.</p><h4>The index handler</h4><p>Next, we have a function with an interesting attribute: #[get(&quot;/&lt;name&gt;&quot;)]. Let&#39;s break it down.</p><ol><li>get annotates that this handler will be triggered by a GET request.</li><li>(&quot;/&lt;name&gt;&quot;) adds a route variable. The name of the variable will be name and the type is determined by handler function just below it. In this case, the type is String.</li><li>The return type of the function is String. The value returned from the Handler is sent as the response. In this case, we&#39;re returning a greeting to the name the handler was called with.</li></ol><h4>Launching the application server</h4><p>Moving on to the main function, we see some more interesting stuff.</p><ol><li>rocket::ignite(). This simply creates a new instance of Rocket.</li><li>The subsequent call to mount adds the index handler function to the /base path.</li><li>launch starts up the application server, starts listening for and dispatching requests to the mounted handlers.</li></ol><h3>Let’s see a demo!</h3><p>We can start the application by running cargo run. This command builds and runs the app in debug mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*XDAv_Yp4TKq1HBtYxmNBCw.png" /><figcaption>Launching Rocket</figcaption></figure><p>Looks pretty cool! Let’s see if we get the response by opening http://localhost:8000/&lt;some-name&gt; in our browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*IXowswjHrB2mcOd26JvT1Q.png" /><figcaption>Response from index handler</figcaption></figure><p>Looks like it works! But what if we tried accessing other non-existent routes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3uc3t4tA2Nw2XTAMPHNeQ.png" /><figcaption>Non-existent routes</figcaption></figure><p>Looks like Rocket takes care of that for us too. How convenient!</p><h4>Request logging</h4><p>If we take a look at our console where we launched rocket, we’ll see the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*oiChNVM5_ay2uX74Z9piFQ.png" /></figure><p>We see neatly formatted logs for each request. This is especially useful during debugging, and can be disabled in production environments by setting ROCKET_ENV=production.</p><p>So far, we’ve done the following</p><ol><li>Installed Rust and switched to the nightly channel for this project.</li><li>Installed rocket as a dependency.</li><li>Created a simple hello-world handler.</li><li>Mounted and launched the handler.</li></ol><p>Congratulations! You’ve created a very basic REST API in Rust. In the next part, we’ll continue with connecting to a database using diesel and serializing/deserializing JSON data using serde.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d842eccdee5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gdg-vit/creating-performant-rest-apis-with-rust-using-rocket-diesel-and-serde-part-1-7d842eccdee5">Creating performant REST APIs with Rust using Rocket, Diesel and Serde — Part 1</a> was originally published in <a href="https://medium.com/gdg-vit">GDG VIT Vellore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating performant REST APIs with Rust using Rocket, Diesel and Serde]]></title>
            <link>https://medium.com/swlh/creating-performant-rest-apis-with-rust-using-rocket-diesel-and-serde-bbe5a4f33a4e?source=rss-23aeacd38998------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbe5a4f33a4e</guid>
            <category><![CDATA[diesel]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[SphericalKat]]></dc:creator>
            <pubDate>Wed, 06 May 2020 20:21:46 GMT</pubDate>
            <atom:updated>2020-06-06T15:14:55.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating performant REST APIs with Rust using Rocket, Diesel and Serde — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ysz4W-U4_bbc9ZGmJb6hOg.jpeg" /></figure><p>I’ve been hearing about Rust and its powerful features for a while now, and I finally decided to try it out for myself. If you don’t know, here’s a short summary of why Rust is gaining popularity.</p><ol><li>Rust is extremely safe. It prevents the programmer from making mistakes that might lead to unsafe behaviour (such as data races).</li><li>Rust is highly performant, on par with C/C++. This makes it a great alternative for systems programming, where speed <em>and </em>safety are critical.</li><li>Rust has a growing community, and an official package manager called cargo, with many packages (called crates) available at <a href="http://crates.io/">crates.io</a>.</li></ol><h3>What’s in scope for this tutorial?</h3><p>We’ll cover everything from setting up Rust to the final outcome in detail. Don’t hesitate to ask any questions you have! A companion repo for this project is available <a href="https://github.com/ATechnoHazard/hello-rocket">here</a>.</p><p>Don’t be alarmed if you don’t understand everything straightaway, Rust does have a rather steep learning curve, but the rewards are worth it! :)</p><blockquote><strong>Note</strong>: I do expect a basic understanding of programming, syntax, and the ownership model of Rust. If you’re unfamiliar, check out the <a href="https://doc.rust-lang.org/book/">Rust Book</a> before proceeding.</blockquote><h3>Crates we’ll be using</h3><ol><li><a href="https://rocket.rs/"><strong>Rocket</strong></a><strong> - </strong>Write <em>fast</em>, secure web applications without compromising on flexibility.</li><li><a href="https://serde.rs/"><strong>Serde</strong></a><strong> - </strong>Popular framework for Serializing and Deserializing Rust data structures into JSON.</li><li><a href="https://diesel.rs/"><strong>Diesel</strong></a><strong> - </strong>Safe, Extensible ORM and Query Builder for Rust.</li></ol><h3>Setting up Rust on your machine</h3><p>If you don’t have Rust installed already, it’s very easy to get it up and running! Simply follow the instructions at <a href="https://rustup.rs/">rustup.rs</a>, and you’ll have a working Rust install.</p><p>After ensuring Rust is installed, we need to set up a Rust project. This can be done using the following command.</p><pre>cargo new hello-rocket --bin &amp;&amp; cd hello-rocket</pre><p>Before we continue, we need to switch to the nightly Rust build, because Rocket requires some features which aren’t in the stable branch yet.</p><pre>rustup override set nightly<br>rustup update &amp;&amp; cargo update</pre><p>These commands will switch you to the nightly channel for <em>this project only</em>, and ensure everything is up-to-date. With that out of the way, let’s move on to a simple hello-world REST API.</p><h3>Hello, World!</h3><p>Every programmer knows these words, and for good reason. While it looks deceptively simple at first, there’s actually a lot we can learn from a Hello World application. Let’s begin by adding some base dependencies to our Cargo.toml file.</p><blockquote><strong>Note</strong>: Cargo.toml is an analogue to package.json for NPM projects or go.mod for Go modules.</blockquote><pre>[dependencies]<br>rocket = &quot;0.4.4&quot;<br>rocket_codegen = &quot;0.4.4&quot;</pre><p>These will get us set up for creating an API using Rocket. Let’s take a look at the basic hello-world application. Add the following code to src/main.rs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6b8a125cfa8b3a0df6c6514afc0ff09/href">https://medium.com/media/d6b8a125cfa8b3a0df6c6514afc0ff09/href</a></iframe><p>Let’s examine what each part does. The top feature flags are used to enable some nightly features that Rocket uses. Not much to look at there.</p><p>The next statement brings rocket’s public functions and macros into local scope. Think of it as being similar to using namespace in C++.</p><h4>The index handler</h4><p>Next we have a function with an interesting attribute: #[get(&quot;/&lt;name&gt;&quot;)]. Let’s break it down.</p><ol><li>get annotates that this handler will be triggered by a GET request.</li><li>(&quot;/&lt;name&gt;&quot;) adds a route variable. The name of the variable will be name and the type is determined by handler function just below it. In this case, the type is String.</li><li>The return type of the function is String. The value returned from the Handler is sent as the response. In this case, we’re returning a greeting to the name the handler was called with.</li></ol><h4>Launching the application server</h4><p>Moving on to the main function, we see some more interesting stuff.</p><ol><li>rocket::ignite(). This simply creates a new instance of Rocket.</li><li>The subsequent call to mount adds the index handler function to the /base path.</li><li>launch starts up the application server, starts listening to listening for and dispatching requests to the mounted handlers.</li></ol><h3>Let’s see a demo!</h3><p>We can start the application by running cargo run. This builds and runs the app in debug mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*uRhYKlKsBttmJVg9neUyBA.png" /><figcaption>Launching Rocket</figcaption></figure><p>Looks pretty cool! Let’s see if we get the response by opening http://localhost:8000/&lt;some-name&gt; in our browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*LIre2wDOe4rg7C2isq2p1g.png" /><figcaption>Response from index handler</figcaption></figure><p>Looks like it works! But what if we tried accessing other nonexistent routes?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpZg_rzi3E53cgKVVKtGEA.png" /><figcaption>Nonexistent routes</figcaption></figure><p>Looks like Rocket takes care of that for us too. How convenient!</p><h4>Request logging</h4><p>If we take a look at our console where we launched rocket, we’ll see the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*yoT8ZgOyyYcWAH9nLcUwKg.png" /></figure><p>We see neatly formatted logs for each request. This is especially useful during debugging, and can be disabled in production environments by setting ROCKET_ENV=production.</p><h3>Conclusion… For now!</h3><p>So far, we’ve done the following:</p><ol><li>Installed Rust and switched to the nightly channel for this project.</li><li>Installed rocket as a dependency.</li><li>Created a simple hello-world handler.</li><li>Mounted and launched the handler.</li></ol><p>Congratulations! You’ve created a very basic REST API in Rust. In the next part, we’ll continue with connecting to a database using diesel and serializing/deserializing JSON data using serde.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbe5a4f33a4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-performant-rest-apis-with-rust-using-rocket-diesel-and-serde-bbe5a4f33a4e">Creating performant REST APIs with Rust using Rocket, Diesel and Serde</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>