<?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 Bastian Gruber on Medium]]></title>
        <description><![CDATA[Stories by Bastian Gruber on Medium]]></description>
        <link>https://medium.com/@gruberbastian?source=rss-b04a8ca61d5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*13WyjRiA64nuDVJSXOIb0w@2x.jpeg</url>
            <title>Stories by Bastian Gruber on Medium</title>
            <link>https://medium.com/@gruberbastian?source=rss-b04a8ca61d5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 26 Nov 2026 09:49:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gruberbastian/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[Rust for the Brave and True]]></title>
            <link>https://medium.com/@gruberbastian/rust-for-the-brave-and-true-df82982b492d?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/df82982b492d</guid>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 13:14:22 GMT</pubDate>
            <atom:updated>2019-06-11T13:21:28.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*yuegluYVNQjOAc1F.jpg" /></figure><p>A few years ago, I wanted to make the switch from Frontend to Backend. One day I fell down the YouTube rabbit hole and (partly) watched a few tech talks. I realised that many of the really good talks were held at Clojure conferences. I looked into it, and decided to learn Clojure.</p><p>The lust for learning a new programming language often times comes from the sheer boredom of your old work, so you also want to redo part of yourself. After a bit of research, I found the book called <a href="https://www.braveclojure.com/">“Clojure for the Brave and True”</a>, and absolutely loved it.</p><p>After a few weeks however, I gave up. The book wants you to jump all in and learn emacs at the same time as well, since it provides, according to the book, the best environment. I really liked the idea, but abandoned the project also due to the lack of Clojure positions for Juniors in my area (Berlin, Germany).</p><h3>Rust</h3><p>A few years later, today, I started to learn Rust and got excited about the whole ecosystem, community and possibilities. I read, wrote and programmed a lot in Rust during the last few months. So much so that I got a Rust position at a company starting August (yay!).</p><h3>Brave</h3><p>But, as I digged deeper and deeper into the language, and watched tutorials, I figured: I can’t do Systems Programming on a MacBook Pro running macOS. Don’t get me wrong: Once you mastered a skill, it doesn’t matter where you operate it on. Also a different machine doesn’t make a huge difference.</p><p>Although, I might disagree a bit with that. Take loosing weight for example. Just cutting down a few kcal per day won’t make a huge difference. Your fridge has to look completely different so you are less tempted to eat all the bad things and naturally will nurture your body in a more healthy way.</p><blockquote><em>I remembered the “Clojure for the Brave an True” concept, and wanted to apply it to my Rust environment</em></blockquote><p>This is exactly what I aimed for when I ordered a Thinkpad X1, with the intention to install Arch Linux on it. Instead of nurturing my body, I wanted to nurture my brain in the right way. If I want to learn about TCP/IP for example, I don’t want to brew install the right package every now and then.</p><h3>My reasons:</h3><ul><li>I want to spend almost all of my time on the command line</li><li>I realized that even macOS is constructed as a perfect source of leisure and wasting time: I wanted a pure work machine instead</li><li>My plan was to spend idle time not in front of a screen, but read a book or write</li><li>I wanted less distractions from my operating system</li><li>I wanted to feel closer to the machine</li></ul><h3>True</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*dG3YkqDAY9I4qSxc.png" /></figure><p>After receiving my Thinkpad, I removed Windows and installed Arch from a USB stick, <a href="https://github.com/gruberb/dotfiles">following these steps</a>. After 4 tries I finally succeeded. When I booted the first time, I installed <a href="https://wiki.archlinux.org/index.php/I3">i3</a> and <a href="https://github.com/jwilm/alacritty">alacritty</a> as my terminal. Next to this, I installed Firefox for browsing. That&#39;s it. I need a terminal, a window manager and a browser. I barely touch my mouse any more.</p><h3>What I learned from it</h3><ul><li>Using my browser to keep up with Slack and E-Mail, I finally reached my goal of just checking it twice a day (because it’s just less convenient).</li><li>Just installing Arch made me touch so many aspects of an operating system (again), and it’s not all that hard to understand certain areas</li><li>I can buy books like <a href="https://nostarch.com/tlpi">The Linux Programming Interface</a> or <a href="https://nostarch.com/tcpip.htm">TCP/IP Guide</a> and dig deep into the system</li><li>I can read the <a href="https://www.2600.com/">2600 magazine</a> and follow along the tutorials</li><li>It made me less distracted during work, since I literally have no notifications or other distractions</li></ul><p>Working under macOS, I constantly opened other programs while I didn’t know how to proceed on a task. With Arch, it’s much harder to do so (and less fun). I have a physical notebook instead next to me and I will, if I can’t proceed on a problem, note down my thoughts in the notebook and stare out of the window to think again.</p><p>I am excited again to be closer to the hardware I operate on. Being able to master nvim and setup a proper tmux setup is so much faster then doing the same workflow inside Visual Code or other editors.</p><h3>Rust Coding Environment</h3><p>I am using:</p><ul><li><a href="https://neovim.io/">NeoVIM</a></li><li><a href="https://github.com/tmux/tmux">tmux</a></li><li><a href="https://github.com/rust-lang/rls">Rust Langauge Server</a></li></ul><p>With the following PlugIns for NeoVim:</p><ul><li><a href="https://aur.archlinux.org/packages/neovim-airline/">neovim-airline</a></li><li><a href="https://github.com/autozimu/LanguageClient-neovim">LanguageClient NeoVim</a></li><li><a href="https://github.com/Shougo/deoplete.nvim">Deoplete Autocomplete</a></li></ul><p>That’s it. You can easily setup a tmux session, split the window where you have your code inside nvim and on the other half of the window cargo run/watch.</p><p>Moving through code like that makes it really hard after a while to use a normal code editor again. Allthough you can install vim bindings to VS Code I guess.</p><h3>2 Warnings/Hints</h3><ul><li>Always have a workable Live-USB stick with Arch installed with you in case of an emergency. I tinkered with the startup script and got myself into a loop. I had to boot from the stick, decrypt and mount my hard drive and then revert the changes to be able to boot again.</li><li>In addition to my Thinkpad, I operate a remote server (for around 10 Euros/month) for backups (via <a href="https://wiki.archlinux.org/index.php/Rsync">rsync</a>) and other fun activities. It can help to have another machine for backups just in case you want to take a snapshot of finally perfect configured Arch installation.</li></ul><h3>Additions</h3><p>In addition to the Thinkpad, I got a <a href="https://www.amazon.com/Vertical-Mouse-Ergonomic-Optical-Wireless/dp/B07HSMS6Y2/ref=sr_1_11_sspa?keywords=vertical+mouse+csl&amp;qid=1560258082&amp;s=gateway&amp;sr=8-11-spons&amp;psc=1">vertical mouse</a> and a <a href="https://mechanicalkeyboards.com/shop/index.php?l=product_detail&amp;p=4322">proper keyboard</a>. Both of which even increase the fun of my setup. My monitor is a Dell 4k 27&quot; which is hooked up on a monitor stand.</p><p>This is so nice to work with that I even don’t miss the beautiful 5k LG UltraFine at all, which I previously had.</p><h3>Summary</h3><p>I provide <a href="https://github.com/gruberb/dotfiles">the basic dotfiles and steps</a> for my setup on my GitHub account. It’s good to run contrary to certain environments. The iPad for example became so powerful that the casual user doesn’t need a Notebook anymore to do every day tasks. That’s a perfect time to reconsider your relationship with your tools you are using.</p><p>If you follow the steps, it’s really simple to operate within Arch on a Thinkpad. You need to tinker with HDPI here and there, and adjust some hibernate functionality. But overall it’s what I wanted: The bare minimum to get to a comfortable coding environment, with almost no distractions.</p><p>In the end, the Thinkpad also has a much better keyboard than the MacBook Pro. Also the form factor is just perfect. A bit bigger than the 13&quot; and smaller than a 15&quot; model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df82982b492d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explained: Rust Futures for Web Development]]></title>
            <link>https://itnext.io/explained-rust-futures-for-web-development-b1d0632490e7?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1d0632490e7</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Thu, 02 May 2019 09:49:54 GMT</pubDate>
            <atom:updated>2019-05-02T09:55:09.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explained: Futures in Rust for Web Development</h3><h4><em>As I explained </em><a href="https://levelup.gitconnected.com/explained-how-does-async-work-in-rust-c406f411b2e2"><em>in one of my last articles</em></a><em>, Futures are one part of an asynchrounous environment. We need Syntax, Type and a Runtime to be able to run code in an non blocking way. Futures are the type part of the Rust async story.</em></h4><h3>The two perspectives</h3><p>If you are coming from NodeJS, Futures in Rust don’t make much sense. In NodeJS, everything happens asynchronously. Therefore for you to be able to say “Hey, I really need to wait for the answer for this GET HTTP call”, you are putting.then() on a Promise, so you can make sure you just execute the code inside the .then() when the HTTP call is finished.</p><p>In Rust, everything is blocking and synchronous by default, so you might ask yourself: “Why bothering with the complexity, that’s exactly what I wanted in the first place!”</p><p>Rust is a Systems Programming Language. So for you to craft applications in Rust, you always have to wear two hats. The “Systems Hat”(⛑) and the “Programmer Hat”(🎩). The Systems Hat(⛑) lets you consider what is actually best from a machine point of view, the Programmer Hat(🎩) takes care of the syntax and how a software is written.</p><p>If you are coming from NodeJS, the Systems Hat is taken care of from Googles V8 runtime, so you can focus on syntax. In Rust you get help from crates, although you need to make certain decisions yourself.</p><p>The Systems Hat is the reason why we want to use Futures. Therefore, you need to handle Futures as a type in your application, and afterwards make sure that you use a runtime to actually execute them. If you are consuming Futures (for example when a crate you are using is returning a Future), you have to understand where the data comes from. In this case, the Programmer Hat <strong>and</strong> the Systems Hat are needed.</p><h3>What actually is a Future? 🎩</h3><p>A Future in Rust is actually a trait, which if you want to implement it, looks like this:</p><pre>trait Future {<br>    type Item;<br>    type Error;</pre><pre>    fn poll(&amp;mut self) -&gt; Poll&lt;Self::Item, Self::Error&gt;;<br>}</pre><p>The poll method is important. This will get called from your runtime and will return <a href="https://docs.rs/futures/0.1/futures/enum.Async.html">Async::Ready or </a><a href="https://docs.rs/futures/0.1/futures/enum.Async.html">Async::NotReady</a>.</p><p>If you want to fetch different magazine issues from a remote location or from the file system, you can create and return your own Future for that:</p><pre>struct Magazine {<br>    issues: Vec&lt;u8&gt;<br>}</pre><p>and impl the Future trait on it:</p><pre>impl Future for Magazine {<br>    // here we return a single byte<br>    type Item = u8;<br>    type Error = io::Error;</pre><pre>    // this method is getting called from the runtime. Everytime we can read<br>    // a byte into the buffer, we return `Async::Ready`<br>    fn poll(&amp;mut self) -&gt; Poll&lt;Self::Item, Self::Error&gt; {<br>        let mut buffer = [0;1];<br>        match self.0.poll_read(&amp;mut buf) {<br>            Ok(Async::Ready(_num_bytes_read)) =&gt; Ok(Async::Ready(buffer[0])),<br>            Ok(Async::NotReady) =&gt; Ok(Async::NotReady),<br>            Err(e) =&gt; Err(e)<br>        }<br>    }<br>}</pre><p>The runtime will fill the buffer with the information you are asking for, and the Future will return Async::Ready once the buffer is full.</p><p>This is the basic essence of a Future in Rust.</p><h3>When to use Futures? 🎩</h3><blockquote><em>Implementing the </em><em>Future trait for a type is your way of telling the machine &quot;Hey, this might take a while, consider this when executing this part of the code&quot;.</em></blockquote><p>Rust is a synchronous language. Everything happens line by line, and waits until each result is processed. This is not a problem until you want to do tasks which take longer time to process.</p><p>If you create a micro service with Rust, and you need to fetch three other micro services for some data, and afterwards you merge the data and write it into a database, that’s a use case where you want to consider using Futures.</p><h3>Why does using Futures save time? ⛑</h3><p>In our test scenario, each of these HTTP calls could take, lets say, 1 Minute. Instead of now waiting 3 Minutes for all of the calls to finish, you want to run them in parallel so you still just wait 1 Minute instead of 3.</p><p>Therefore you create three methods which return a Future each, collect them, and then pass them on to a runtime (to tokio via tokio::run for example).</p><h3>How to use Futures? 🎩 + ⛑</h3><p>If a crate returns a Future, you can use <a href="https://docs.rs/futures/0.1.26/futures/future/struct.AndThen.html">.and_then()</a> to work with the result once the Future is ready. Using <a href="https://docs.rs/futures/0.1.26/futures/future/struct.Map.html">.map()</a> on a Future lets you alter the type of the Future.</p><p>Inside the async Rust world, we have to take care of different types of data. Instead of using Strings and Numbers for example, we deal with streams of values. You will most likely deal with Streams.</p><p>A Stream is an extension of a Future. Where a Future is about producing a single value, a Stream is yielding values as long as they are present.</p><ul><li><a href="https://docs.rs/futures/0.1.26/futures/stream/index.html">Stream</a>: A Stream is, like a Future, a trait you can impl on a type. This lets you iterate over the return values (which are Some(_) or None).</li><li><a href="https://docs.rs/futures/0.1.26/futures/sink/index.html">Sink</a>: For writing data continuously (in an asynchronous way) to either a socket or to a file system</li></ul><p>So Streams are for reading data, Sinks are for writing them. We have two types of Streams in our web ecosystem:</p><ul><li>Stream of Bytes (like HTTP bodies or TCP streams)</li><li>Stream of Messages (like WebSocket Frames or UDP Packet), where each message has a fixed size</li></ul><h3>Code example</h3><p>Lets look at a use case where a crate you are using returns a Future. When doing HTTP calls, reqwest is a good example. On the Future returned from reqwest, you can use .and_then() to process the results (🎩):</p><pre>// We have to use &quot;r#&quot; before &quot;async&quot; because &quot;async&quot; is a reserved keyword.<br>use reqwest::r#async::Client;</pre><pre>// The return type has to be `Future&lt;Item=(), Error=()&gt;` to be able<br>// to use `tokio::run`. <br>// If it has a different type, you have to use `tokio::block_on`<br>fn fetch_data() -&gt; impl Future&lt;Item=(), Error=()&gt; {<br>    Client::new()<br>        .get(url)<br>        .send()<br>        .and_then(|res| {<br>            res.into_body().concat2()<br>        })<br>        .map_err(|err| println!(&quot;request error: {}&quot;, err))<br>        .map(|body| {<br>            // here you can use the body to write it to a file<br>            // or return it via Ok()<br>            // If you return it via for example Ok(users)<br>            // then you need to adjust the return type in impl Future&lt;Item=TYPE<br>            // Examples can be found here: <br>            // https://github.com/gruberb/futures_playground</pre><pre>            // For now, lets just turn the body into a Vector<br>            let v = body.to_vec();<br>        })<br>}</pre><p>Once you created the method which returns a Future (fetch_data()), <strong>you have to pass it on to a runtime</strong> like tokio (⛑):</p><pre>tokio::run(fetch_data());</pre><h3>High Level Overview</h3><ol><li>You receive a Future from an external crate</li><li>A Future is likely to return a Stream of values, so you have to form this Stream into a type you can work with in a synchronous way (like a Vector or String)</li><li>You return the whole Future from a method via -&gt; impl Future&lt;Item=(), Error=()&gt;, where the braces () are placeholders for the actual type you want to return</li><li>You pass the method on to a runtime like tokio via tokio::run(method())</li><li>The run​ call will start the runtime, set up the required resources and then put this future on a threadpool and start polling your future</li><li>It will then try to pass the work on to the operating system</li><li>Each time the runtime polls your Future, if the underlying I/O resource your Future is waiting on is not ready, it will return NotReady​. The runtime sees this NotReady​ return value and puts your Future to sleep</li><li>Once an event from the underlying I/O resource comes, the runtime checks if this I/O resource is associated with your Future, and starts polling again. This time, your Future will be able to return a Ready​ with a value, since the underlying I/O resource has provided a value</li><li>The runtime will then set the status of the Future to ready and will process the .and_then() part of the code</li></ol><p>The Future is getting, unlike in NodeJS, executed via tokio::run and not before. In Node, as soon as you write a Promise, the object is being returned immediately.</p><h3>What’s so different or hard about Futures? ⛑</h3><p>Lets walk through our example above:</p><ul><li>We create a new client with Client::new() and .send() our request</li><li>We will get a <a href="https://github.com/seanmonstar/reqwest/blob/master/src/async_impl/response.rs#L24">Response</a> back:</li></ul><pre>pub struct Response {<br>    status: StatusCode,<br>    headers: HeaderMap,<br>    url: Box&lt;Url&gt;,<br>    body: Decoder,<br>    ...<br>}</pre><ul><li>The body itself is a Decoder, which can be turned into a Body via <a href="https://github.com/seanmonstar/reqwest/blob/master/src/async_impl/response.rs#L113">.into_body()</a>.</li><li>Body itself <a href="https://github.com/seanmonstar/reqwest/blob/master/src/async_impl/decoder.rs#L155">implements</a> a <a href="https://docs.rs/futures/0.1.26/futures/stream/trait.Stream.html">Stream</a> (as mentioned earlier).</li><li>Now we can look into the Futures API from Rust and find out: We can turn a Stream of Bytes into single item via <a href="https://docs.rs/futures/0.1.26/futures/stream/struct.Concat2.html">.concat2()</a></li></ul><pre>...<br>        .and_then(|res| {<br>            res.into_body().concat2()<br>        })<br>...</pre><ul><li>We use this single item in the .map() part as body</li><li>With the help of your code editor, you will find out that this body is actually a <a href="https://github.com/hyperium/hyper/blob/master/src/body/chunk.rs">Chunk</a>, returned from the library <a href="https://github.com/hyperium/hyper">Hyper</a></li><li>We can turn this Chunk now into a <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html">Vector</a></li></ul><pre>...<br>        .map(|body| {<br>            let v = body.to_vec();<br>            // do whatever with v<br>        })<br>...</pre><p>From then on, we are back in “normal” Rust land and can forget what just happened 🙃.</p><blockquote><em>You can find the full example in this </em><a href="https://github.com/gruberb/futures_playground"><em>GitHub repository</em></a><em>. There I receive a </em><em>JSON and write it to a file.</em></blockquote><p>This is one of the reasons why dealing with Futures is so hard in the beginning. You have to think much lower level than for example in NodeJS. In addition, the async/await syntax <a href="https://internals.rust-lang.org/t/await-syntax-discussion-summary/9914">is not final yet</a>, which leads to much more boiler code.</p><p>These mental steps help you to not get lost when dealing with Futures:</p><ol><li>What’s the return type or value I am getting from this library?</li><li>How can I access the Stream of values on this response?</li><li>What will the library turn this Stream into when I collect all the values via .concat2()?</li><li>How can I turn this new type into a Vector or another Rust std format so I can pass it on to synchronous methods?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Qfu4N4ZIhqrzqCLs.png" /></figure><p><strong>Basically, you always want to figure out how to access the stream of values, collect them, and then process the resulting object.</strong></p><h3>How to execute more than one Future? 🎩</h3><p>Generally you want to collect your values as Streams, so that for each item you get over a Stream, you can spawn off a new Future to handle it.</p><p>The Rust Futures API has a method called <a href="https://docs.rs/futures/0.1.26/futures/stream/futures_unordered/struct.FuturesUnordered.html">FuturesUnordered</a> which you can use to add more than one Future:</p><pre>use futures::stream::futures_unordered::FuturesUnordered;<br>use hyper::{client::ResponseFuture, Client};</pre><pre>fn setup_requests() -&gt; FuturesUnordered&lt;ResponseFuture&gt; {<br>    let mut list_of_futures = FuturesUnordered::new();</pre><pre>    let client = Client::new();</pre><pre>    let first = client.get(URL);<br>    list_of_futures.push(first);</pre><pre>    let second = client.get(URL);<br>    list_of_futures.push(second);</pre><pre>    list_of_futures<br>}</pre><p>In this example we used <a href="https://github.com/hyperium/hyper">hyper</a> for our HTTP calls. You can find the rest of the code <a href="https://github.com/chicagohaskell/async-futures-talk/blob/master/rustlb/examples/multi-http/src/main.rs">over here on Github</a>.</p><p>The syntax will look slightly different if you are using reqwest. Here you .join() multiple requests and return it as &quot;one Future&quot;.</p><pre>fn fetch() -&gt; impl Future&lt;Item=(), Error=()&gt; {<br>    let client = Client::new();</pre><pre>    let json = |mut res : Response | {<br>        res.json::&lt;STRUCT_TYPE&gt;()<br>    };</pre><pre>    let request1 =<br>        client<br>            .get(URL)<br>            .send()<br>            .and_then(json);</pre><pre>    let request2 =<br>        client<br>            .get(URL)<br>            .send()<br>            .and_then(json);</pre><pre>    request1.join(request2)<br>        .map(|(res1, res2)|{<br>            println!(&quot;{:?}&quot;, res1);<br>            println!(&quot;{:?}&quot;, res2);<br>        })<br>        .map_err(|err| {<br>            println!(&quot;stdout error: {}&quot;, err);<br>        })<br>}</pre><p>The full code can also be found on <a href="https://github.com/seanmonstar/reqwest/blob/master/examples/async_multiple_requests.rs">GitHub</a>.</p><h3>What is the future of Futures? 🎩 + ⛑</h3><p>Futures are getting into stable Rust at 1.37, so around June. There are also changes around the syntax and runtime, which will benefit the amount of code you have to write to get this stream of values out of a Future and into a synchronous Rust format.</p><p>You can also use the <a href="https://github.com/rustasync/runtime">Runtime</a> crate, which saves you almost all of the boilerplate code. Although going through the process above helps you understand Futures on a deeper level.</p><h3>Summary</h3><p>If you perform asynchronous operations, like fetching files from the operating system or making HTTP requests to a remote server, then Futures let you work with the return values in a non-blocking way.</p><p>If it would be synchronous, you would have to block a thread the operation is running on, and wait for the result until you continue. To do this in an asynchronous way, we have a runtime which creates threads themselves, and takes on Futures. It will fill the value inside the Future when the operating system returns a value to the runtime.</p><p>Once the Future is fulfilled, the runtime sets Async::Ready and the .and_then() part of the code will get executed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d0632490e7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/explained-rust-futures-for-web-development-b1d0632490e7">Explained: Rust Futures for Web Development</a> was originally published in <a href="https://itnext.io">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Development with Rust — 03/x: Create a REST API]]></title>
            <link>https://levelup.gitconnected.com/web-development-with-rust-03-x-create-a-rest-api-f3d7e56dc502?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d7e56dc502</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 08:53:02 GMT</pubDate>
            <atom:updated>2019-04-15T12:52:17.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Development with Rust — 03/x: Create a REST API</h3><h4><em>Follow me on </em><a href="https://twitter.com/byteadventures"><em>twitter</em></a><em> to always get the latest information about web development in Rust. Also checkout the </em><a href="https://github.com/gruberb/web-programming-in-rust"><em>GitHub repository</em></a><em> to this series.</em></h4><h3>Content</h3><ol><li>HTTP Requests</li><li>POST/PUT/PATCH/DELETE are special</li><li>The Job of a Framework</li><li>Creating an API spec</li><li>Crafting the API</li><li>Input Validation</li><li>Summary</li></ol><p>APIs are the bread and butter of how a modern and fast-paced web environment. Frontend application, other web services and IoT devices need to be able to talk to your service. API endpoints are like doors to which you decide what comes in and in which format.</p><p>Since Rust is a static typed language with a strong compiler you won’t face many of the common pitfalls about running a web service in production. Although there are still run time errors which you have to cover.</p><h3>HTTP Requests</h3><p>When we talk about creating an API we basically mean a web application which listens on certain paths and responds accordingly. But first things first. For two devices to be able to communicate with each other there has to be an established TCP connection.</p><p>TCP is a protocol which the two parties can use to establish a connection. After establishing this connection, you can receive and send messages to the other party. HTTP is another protocol, which is built on top of TCP, and it’s defining the contents of the requests and responses.</p><p>So on the Rust side of things, TCP is implemented in the Rust core library, HTTP is not. Whatever framework you chose in the <a href="https://medium.com/@gruberbastian/rust-for-the-web-02-x-deploy-your-first-app-51d1ed69cbe3">previous article</a> they all implement HTTP and therefore are able to receive and send HTTP formatted messages.</p><p>An example GET requests for example looks like this:</p><pre>GET / HTTP/1.1<br>Host: api.awesomerustwebapp.com<br>Accept-Language: en</pre><p>It includes:</p><ul><li>GET: the HTTP method</li><li>/: The path</li><li>HTTP/1.1: The version of the HTTP protocol</li><li>HOST: The host/domain of the server we want to request data from</li><li>Accept-Language: Which language we prefer and understand</li></ul><p>The most common used HTTP methods are:</p><ul><li>GET</li><li>POST</li><li>PUT</li><li>PATCH</li><li>DELETE</li></ul><h3>POST/PUT/PATCH/DELETE are special</h3><p>We are using GET every time we browse the web. If we want to alter data however (like using POST to send data over to another server), we need to be more cautions and precise.</p><p>First, not everyone is allowed to just send a bunch of data to another server. Our API can for example say: “I just accept data from the server with the host name allowed.awesomerustapp.com.</p><p>Therefore, when you send a POST to another server, what actually happens is the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS workflow</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*fJy1CEMpsNLeSWvh.png" /></figure><p>We first ask the server what is allowed, where do you accept requests from and what are your accepted headers. If we fulfill all of these requirements, then we can send a POST.</p><p>The web framework <a href="https://actix.rs/">actix</a> for example has its own <a href="https://actix.rs/actix-web/actix_web/middleware/cors/index.html">cors middleware</a>.</p><blockquote><em>Disclaimer: Not all frameworks (like </em><a href="https://github.com/SergioBenitez/Rocket/issues/25"><em>rocket</em></a><em> and </em><a href="https://github.com/rustasync/tide/pull/104"><em>tide</em></a><em>) are implementing CORS in their core. However, in a professional environment, you handle CORS on the </em><a href="https://imti.co/kubernetes-ingress-nginx-cors/"><em>DevOps side</em></a><em> of things and put it for example in your NGINX config.</em></blockquote><h3>The Job of a Framework</h3><p>We use the hard work of other people to create web applications. Everything has to be implemented at some point, just not from you for most of the time. A framework covers the following concerns:</p><ul><li>Start a web server and open a PORT</li><li>Listen to requests on this PORT</li><li>If a request comes in, look at the Path in the HTTP header</li><li>Route the requests to the handler according to the Path</li><li>Help you extract the information out of the request</li><li>Pack the generated data and HTTP StatusCode (created from you) and form a response</li><li>Send the response back to the sender</li></ul><p>The Rust web framework <a href="https://github.com/rustasync/tide">tide</a> includes <a href="https://github.com/rustasync/http-service">http-service</a>, which provides the basic abstractions you need when working with HTTP calls. The crate http-service is built on top of <a href="https://github.com/hyperium/hyper">hyper</a>, which transforms TCP-Streams to valid HTTP requests and responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*jT23hSjjiEZy32d3.png" /></figure><p>Your job is to create routes like /users/:id and add a route_handler which is a function to handle the requests on this particular path. The framework makes sure that it directs the incoming HTTP requests to this particular handler.</p><h3>Creating an API spec</h3><p>You have to define your resources first to get an idea what your application needs to handle and uncover relationships between them. So if you want to build a idea-up-voting site, you would have:</p><ul><li>Users</li><li>Ideas</li><li>Votes</li></ul><p>A simple spec for this scenario would look like this:</p><h4>Users</h4><ul><li>POST /users</li><li>GET /users</li><li>PUT /users/:user_id</li><li>PATCH /users/:user_id</li><li>DELETE /users/:user_id</li><li>GET /users/:user_id</li></ul><p><strong>Ideas</strong> and <strong>Votes</strong> behave accordingly. A spec is helpful for two reasons:</p><ul><li>It gives you guidelines not to forget a path</li><li>It helps to communicate to your API users what to expect</li></ul><p>You can tools like <a href="https://swagger.io/">swagger</a> to write a full spec which also describes the structure of the data and the messages/responses for each path and route.</p><p>A more professional spec would include the return values for each route and the request and response bodies. However, the spec can be finalized once you know how your API should look like and behave. To get started, a simple list is enough.</p><h3>Crafting the API</h3><p>Depending on the framework you are using, your implementation will look different. You have to have the following features on your radar to look out for:</p><ul><li>Creating routes for each method (like app.at(&quot;/users&quot;).post(post_users_handler))</li><li>Extracting information from the request (like headers, uri-params and JSON from the request body)</li><li>Creating responses with proper HTTP codes (200, 201, 400, 404 etc.)</li></ul><p>I am using the latest version of <a href="https://github.com/rustasync/tide">tide</a> for this web series. You can add it in your <strong>Cargo.toml</strong> file and use it for your web app:</p><pre>[dependencies]<br>tide = &quot;0.1.0&quot;</pre><p>Our first User implementation will look like this:</p><pre>async fn handle_get_users(cx: Context&lt;Database&gt;) -&gt; EndpointResult {<br>    Ok(response::json(cx.app_data().get_all()))<br>}</pre><pre>async fn handle_get_user(cx: Context&lt;Database&gt;) -&gt; EndpointResult {<br>    let id = cx.param(&quot;id&quot;).client_err()?;<br>    if let Some(user) = cx.app_data().get(id) {<br>        Ok(response::json(user))<br>    } else {<br>        Err(StatusCode::NOT_FOUND)?<br>    }<br>}</pre><pre>async fn handle_update_user(mut cx: Context&lt;Database&gt;) -&gt; EndpointResult&lt;()&gt; {<br>    let user = await!(cx.body_json()).client_err()?;<br>    let id = cx.param(&quot;id&quot;).client_err()?;</pre><pre>    if cx.app_data().set(id, user) {<br>        Ok(())<br>    } else {<br>        Err(StatusCode::NOT_FOUND)?<br>    }<br>}</pre><pre>async fn handle_create_user(mut cx: Context&lt;Database&gt;) -&gt; EndpointResult&lt;String&gt; {<br>    let user = await!(cx.body_json()).client_err()?;<br>    Ok(cx.app_data().insert(user).to_string())<br>}</pre><pre>async fn handle_delete_user(cx: Context&lt;Database&gt;) -&gt; EndpointResult&lt;String&gt; {<br>    let id = cx.param(&quot;id&quot;).client_err()?;<br>    Ok(cx.app_data().delete(id).to_string())<br>}</pre><pre>fn main() {<br>    // We create a new application with a basic, local database<br>    // You can use your own implementation, or none: App::new(())<br>    let mut app = App::new(Database::default());<br>    app.at(&quot;/users&quot;)<br>        .post(handle_create_user)<br>        .get(handle_get_users);<br>    app.at(&quot;/users/:id&quot;)<br>        .get(handle_get_user)<br>        .patch(handle_update_user)<br>        .delete(handle_delete_user);</pre><pre>    app.serve(&quot;127.0.0.1:8000&quot;).unwrap();<br>}</pre><p><em>You can find the full implementation of the code in the </em><a href="https://github.com/gruberb/web-programming-in-rust/tree/master/03-x"><em>GitHub repository</em></a><em> to this series.</em></p><p>We see that we first have to create a new App</p><pre>let mut app = App::new(())</pre><p>add routes</p><pre>app.at(&quot;/users&quot;)</pre><p>and for each route add the HTTP requests we want to handle</p><pre>app.at(&quot;/users&quot;).get(handle_get_users)</pre><p>Each framework has a different method of extracting parameters and JSON bodies. Actix is using <a href="https://actix.rs/docs/extractors/">Extractors</a>, rocket is using <a href="https://api.rocket.rs/v0.4/rocket/request/trait.FromQuery.html">Query Guards</a>.</p><p>With tide, you can access request parameters and bodies and database connections through Context. So when we want to update a User with a specific id, we send a PATCH to /users/:id. From there, we call the handle_update_user method.</p><p>Inside this method, we can access the id from the URI like this:</p><pre>let id = cx.param(&quot;id&quot;).client_err()?;</pre><p>Each framework is also handling its own way of sending responses back to the sender. Tide is using EndpointResult, rocket is using <a href="https://api.rocket.rs/v0.4/rocket/struct.Response.html">Response</a> and actix <a href="https://actix.rs/docs/response/">HttpResponse</a>.</p><p>Everything else is completely up to you. The framework might help you with session management and authentication, but you can also implement this yourself.</p><p><strong>My suggestion is: Build the first skeleton of your app with the framework of your choice, figure out how to extract information out of requests and how to form responses. Once this is working, you can use your Rust skills to build small or big applications as you wish.</strong></p><h3>Input Validation</h3><p>Your best friend in the Rust world will be <a href="https://github.com/serde-rs/serde">serde</a>. It will help you parse JSON and other formats, but will also allow you to serialize your data.</p><p>When we talk about input validation, we want to make sure the data we are getting has the right format. Lets say we are extracting the JSON body out of a request:</p><pre>let user: User = serde_json::from_str(&amp;request_body);</pre><p>We are using <a href="https://docs.serde.rs/serde_json/">serde_json</a> here to transform a JSON-String into a Struct of our choice. So if we created this struct:</p><pre>struct User {<br>    name: String,<br>    height: u32,<br>}</pre><p>we want to make sure the sender is including name <strong>and</strong> height. If we just do serde_json::from_str, and the sender forgot to pass on the height, the app will panic and shut down, since we expect the response to be a user: let user: User.</p><p>We can improve the error handling like this:</p><pre>let user: User = match serde_json::from_str(&amp;request_body) {<br>    Ok(user) =&gt; user,<br>    Err(error) =&gt; handle_error_case(error),<br>};</pre><p>We catch the error and call our handle_error_case method to handle it gracefully.</p><h4>Summary</h4><ol><li>Pick a framework of your choice (<a href="https://rocket.rs/">rocket</a> is nightly, <a href="https://actix.rs/">actix</a> is stable, <a href="https://github.com/rustasync/tide">tide</a> is fostered close to the Rust Core and also works on Rust nightly)</li><li>Know that there is no common CORS handling (yet). Recommendation is to handle this on the DevOps side (NGINX for example)</li><li>After picking a framework, spec out your resources (`/users`: GET, POST etc.)</li><li>Figure out how the framework of your choice is handling extracting parameters and JSON from the request and how to form a response</li><li>Validate your input via match and <a href="https://docs.serde.rs/serde_json/">serde_json</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d7e56dc502" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/web-development-with-rust-03-x-create-a-rest-api-f3d7e56dc502">Web Development with Rust — 03/x: Create a REST API</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[Explained: How does async work in Rust?]]></title>
            <link>https://levelup.gitconnected.com/explained-how-does-async-work-in-rust-c406f411b2e2?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c406f411b2e2</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 10:26:24 GMT</pubDate>
            <atom:updated>2019-04-02T11:37:29.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article will outline an overview of the why and how <strong>async</strong> exists in Rust. The differences between concurrency, parallelism and asynchronous code won’t be covered.</h4><h3>Async Concept</h3><p>Asynchronous programming is a concept which allows not blocking the program workflow when waiting for the results of certain actions. So you can open a large file or query a database, but your program will continue processing each line afterwards.</p><p>This concept was first needed on the kernel level, because you want to be able to listen to music while you type something on your keyboard. On a software level, this was achieved through multi-threading. On the CPU side, you can have multiple processes running on each core at the same time.</p><p>Later on, web servers came into play and needed to be able to hold millions of connections while performing I/O tasks. To be able to do this in a non-blocking way, we can either use threads on the kernel level, or implement our own way of handling threads and events.</p><h3>What’s needed and why</h3><p>The kernel already has the concept implemented (through threads and other concepts), however they are quite “expensive”, which means there is just a finite amount of resources available and dealing with this problem on OS level adds a whole new level of complexity.</p><p>Therefore it would be nice to handle our internal async flow on program level. We need a so called runtime, which can handle async code and is able to communicate to the kernel.</p><p>The general idea is:</p><ul><li>Implement your own way of handling threads and queues on program level (green threads)</li><li>Add syntactic sugar to your language so the runtime/compiler can identify async parts of the code</li><li>Add async types so they can notify when they are “done”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*fip8SGfgHanOzQal.png" /></figure><p>Instead of dealing with Strings for example, an async type needs to have certain states (processing and done). The runtime can handle these types and set the state in them. Afterwards in your code you can access the value at a later point or wait for them to be done before you continue.</p><h3>Workflow</h3><p>You mark a method in your code as async, in this async method you can now use your async types. You can either wait for them to finish (“fetch data from GitHub…”) or you “start” them, continue with your flow and later on check if they finished and use the value from them.</p><p>Once done writing the code, you need a runtime which can take this async part of your code and actually run it. The runtime needs also to take processes from the queue and hand it over to the operating system, since there is where the real work happens.</p><p>After the operating system is done with the processing, it will notify the runtime, which in return will set the state inside the async type and hand it back to the program workflow.</p><h3>NodeJS vs. Go. vs. Rust</h3><p>Lets look at how Node, Go and Rust are implementing the concepts we talked about, namely: Syntax, Type and Runtime.</p><h3>NodeJS</h3><p>In NodeJS you have the async/await syntax and Promises. You can await a Promise aka an action which might need more time to process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*HCnpbPSv8ZnFPLz9.png" /></figure><pre>const async_method = async () =&gt; {<br>    const dbResults = await dbQuery();<br>    const results = await serviceCall(dbResults);<br>    console.log(results);<br>}</pre><h3>Go</h3><p>In Go, you start goroutines instead of Promises. And instead of async/await you simple write go method_name(). Instead of V8, Go ships with its own Go runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*QDZWzVXre_o-H5or.png" /></figure><pre>func f(greeting string) {<br>    fmt.Println(greeting, &quot;, World!&quot;)<br>}</pre><pre>go f(&quot;Hello&quot;)</pre><h3>Rust</h3><p>The Rust Async ecosystem is still in progress and not final yet. The proposal here is to also use async/await, instead of Promises and Goroutines you have <a href="https://github.com/rust-lang-nursery/futures-rs">Futures</a>.</p><p>The Rust Language Team decided <a href="https://github.com/rust-lang/rfcs/blob/0806be4f282144cfcd55b1d20284b43f87cbe1c6/text/0230-remove-runtime.md">not to include</a> any runtime. Rust wants to be as small as possible, and to be able to swap parts in and out as needed. Therefore you need to rely on crates to provide the appropiate runtime for you.</p><p>The most popular one is <a href="https://tokio.rs/">tokio</a>, which uses <a href="https://github.com/carllerche/mio">mio</a> internally as its event queue. Even other runtimes are using mio since it’s providing abstraction over kernel methods like epoll , kqueue and IOCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*yV7CvORSa9Xhe5RZ.png" /></figure><p>One special feature about Rust is also that you have to “start” a Future. So just declaring it like a Promise in NodeJS or writing go name_of_goroutine() doesn&#39;t trigger the Future to do something yet. So in case you are using tokio, you need to:</p><pre>let response = client.get(&quot;http://httpbin.org&quot;)</pre><pre>let response_is_ok = response<br>    .and_then(|resp| {<br>        println!(&quot;Status: {}&quot;, resp.status());<br>        Ok(())</pre><pre>tokio::run(response_is_ok);</pre><p>In the hopefully not so distant future, you can use async in Rust like this:</p><pre>#[async]<br>fn async_function_name(...) -&gt; Result&lt;ReturnType, ErrorType&gt; {<br>    let db_results = await!(query_database());<br>    let more_data = await!(fetch_another_service(db_resukts));<br>    process(more_data)<br>}</pre><p><a href="https://github.com/alexcrichton/futures-await">The </a><a href="https://github.com/alexcrichton/futures-await">async/await syntax</a> is still in process and needs to be approved, merged and parts of the language adjusted to the new form.</p><h3>Rust Async in Detail</h3><p>Lets zoom in a bit on how a runtime works or can work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*M1X1q4LXLT9o1Zu0.png" /></figure><p>Tokio is using <a href="https://tokio.rs/docs/going-deeper/building-runtime/">internally</a> the <a href="https://www.puncsky.com/blog/2015/01/13/understanding-reactor-pattern-for-highly-scalable-i-o-bound-web-server/">Reactor-Executor pattern</a>.</p><p>What tokio and other runtimes want to achieve is a highly scalable server for high raw data throughput. They don’t want to block when doing I/O operations. We have basically two options here: Thread-Based or Event-Driven Architecture. To make it short: Thread-Based is limiting because of the limited physical resources.</p><p>So Event-Driven is best in our case. It is registering incoming Future requests and saves a pointer to the async function handler. It then triggers an event in the kernel. Once the I/O operation is done, we call the pointer and execute the async method with the results from the I/O (kernel).</p><p>For this, we need a Reactor, which notifies if data is coming over the network or a file writing operation is in progress, and an executor which takes this data and executes the async function (Future) with it.</p><p>In addition, each runtime needs to understand kernel methods (like <a href="https://people.eecs.berkeley.edu/~sangjin/2012/12/21/epoll-vs-kqueue.html">epoll</a>) for starting I/O operations. For Rust there is a crate called <a href="https://github.com/carllerche/mio">mio</a> which implements these kernel methods. Tokio is using mio internally.</p><h3>Is it usable?</h3><p>There is a lot happening at the moment in async Rust world. It will take a bit of time to have a final version out there which is easy to use and understand. Until then you can use your web frameworks like you are used to, since they already ship with a runtime.</p><p>Dropbox for example is using Futures in combination with tokio in production to serve data from the disk on Dropbox&#39;s servers. Futures is in Rust stable in version 0.1, and in Rust nightly in version 0.3. The runtime tokio is relying on Rust stable, so it is using Futures 0.1.</p><p>You can transform 0.3 into 0.1 Futures and vice-versa via the <a href="https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.9/futures/compat/index.html">compat module</a>.</p><p>Rust needs a few more months to get ready for its easy to use and powerful Futures. They are less expensive as in other languages, and you can have a thin or thick runtime, it’s totally up to you.</p><h3>Get started</h3><p>As mentioned, tokio is one of the runtimes you can use. Another one is a combination of <a href="https://github.com/withoutboats/romio">Romio</a> and <a href="https://github.com/withoutboats/juliex">Juliex</a>.</p><p>If you are building web applications, there is a crate called <a href="https://hyper.rs/">hyper</a>, which already includes tokio. So here you can use Futures 0.1 in you application.</p><h3>Keep up to date</h3><p>You can check out the website <a href="https://areweasyncyet.rs/">areweasyncyet</a> to follow the progress on async Rust. Similarly, <a href="http://www.arewewebyet.org/">arewewebyet</a> is tracking the progress of frameworks and tools around building web applications.</p><p>Further reading</p><ol><li><a href="https://manishearth.github.io/blog/2018/01/10/whats-tokio-and-async-io-all-about/">What Are Tokio and Async IO All About?</a></li><li><a href="https://slides.com/wraithm/async-io-in-rust-and-haskell/#/">Futures in Rust and Haskell</a></li><li><a href="https://v8.dev/blog/fast-async">Fast async in NodeJS</a></li><li><a href="https://gobyexample.com/goroutines">Go by example: Goroutines</a></li><li><a href="https://tokio.rs/docs/going-deeper/building-runtime/">Tokio: Building a runtime</a></li></ol><p><a href="https://gitconnected.com/learn/rust">Learn Rust - Best Rust Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c406f411b2e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/explained-how-does-async-work-in-rust-c406f411b2e2">Explained: How does async work in Rust?</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[How to combat JavaScript fatigue with Rust]]></title>
            <link>https://medium.com/@gruberbastian/how-to-combat-javascript-fatigue-with-rust-5de86d2e46d6?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de86d2e46d6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 19:05:12 GMT</pubDate>
            <atom:updated>2019-03-20T19:19:52.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you find yourself in any of those thoughts when creating applications with NodeJS?</p><ul><li>“I for sure need to pick the right npm module to solve this problem, but which one fits best and is getting supported well?”</li><li>“Uh, my app is growing so big, I have no idea what the difference between user and customer is anymore and which properties they have.&quot;</li><li>“TypeScript will definitely solve my problems!”</li><li>“Hm, I don’t know if this is an error with TypeScript or in the transpiled JavaScript? Or did I just disable the wrong ESLint option?”</li><li>“Is this all what I will do for the rest of my career?”</li></ul><p>Creating JavaScript applications is easy at first but it’s getting harder and harder once the application growsYou can wait and hope that any of the big tech companies will solve your problems through TypeScript and other tools A few years go by and you ask yourself: Is this all? Do I create CRUD application for the next 20 years?</p><p>It is sometimes harder to keep up with <a href="https://dev.to/tomekponiat/javascript-predictions-for-2019-by-npm-pie">the latest hype train</a> then actually learning fundamentals.</p><p>NodeJS became a victim of its own success. The market is flooded with developers, every company is using Node in some part of their tech stack. You can say that companies don ‘t pick it because of it’s underlying technology but because they can get cheap labor and feel safe because all the other companies are also using Node, so it must be a good choice.</p><h3>Meet Rust</h3><p>You probably know the saying that you should learn Lisp, even if you won’t use it, just because the learned mindset will make you a better developer? Instead of learning Lisp to become a better developer, you can learn a language which is actually in use and will improve you as good as Lisp does. Meet Rust. Rust is not the latest hype, but has <a href="https://arxiv.org/pdf/1903.00982.pdf">fundamentals</a> which offer you a wide range of opportunities, even in the long run.</p><blockquote><a href="https://www.rust-lang.org/">Rust</a> is a systems language, but it’s ergonomic syntax empowers the developer after the first struggles.</blockquote><p>From a NodeJS perspective, Rust can be used to create web server applications and services. You can write <a href="https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/">Lambda functions</a> or full fledged applications. Instead of using TypeScript, Rust has a strong build-in Type system. Instead of using ESLint, it ships with the <a href="https://vorner.github.io/difficult.html">pickiest compiler out there</a>.</p><p>The pain you feel in the beginning is different. I call it good pain. Good pain lets you grow as a person (and developer), bad pain just hurts. I would categorize many of the TypeScript and NodeJS pains as bad pain. Not because the tools are bad, but a language which was created in <a href="https://en.wikipedia.org/wiki/JavaScript#History">10 days</a> just gets you so far.</p><p>At some point you need to make a personal decision of how your life should look like. Your day to day has a huge impact on your happiness and the well-being of your surroundings. Rust can help you rediscover the joy of programming again.</p><p>After you learned Rust, you may think you just replaced tool X with tool Y and end up in the same place. But, there is a difference. Once learned, you can use Rust to create:</p><ul><li>Games</li><li>CLI tools</li><li>Operating Systems</li><li>Web Services</li><li>Browser Applications</li><li>Applications on Embedded Devices</li></ul><p>One would say you can cover the whole stack. Rust creates a self feeding system:</p><ul><li>Developers from C, C++, Java, Kotlin, Python, Ruby and JavaScript flock to the language</li><li>Rust and its features are getting discussed not only in a web context but in a wide range of scenarios</li><li>Different areas, perspectives and use cases are getting fed back into the language in an <a href="https://predictablynoisy.com/rust-governance">open way</a></li></ul><h3>Lets picture a perfect world 5 years from now</h3><p>You are writing your web service in Rust. Instead of installing five different npm modules which help you cover your mistakes, you are using build-in tools to harden your code base. After the compiler gives you a green light you are 98% sure your application will run <a href="https://youtu.be/cDFSrVhnZKo?t=1865">safe and fast</a> in the years to come.</p><p>But, hold on, you are still sometimes frustrated by the repetitive work environment. But now you mastered a language which you can use to build your own <a href="https://os.phil-opp.com/">Operating System</a> on the side, you can implement the <a href="https://www.youtube.com/watch?v=bzja9fQWzdA">TCP protocol</a>, you can <a href="http://arewegameyet.com/">create Games</a> and join a local game community. You can even create applications for the Browser which are <a href="https://webassembly.org/">compiled to WASM</a>. If this is not enough, you can get yourself a piece of hardware and <a href="https://www.rust-lang.org/what/embedded">run Rust on it</a>.</p><h3>Node is not gone</h3><p>NodeJS won’t be completely gone, and your skills neither. However you found a great addition and you might just focus on Rust more in the future. Remember, no language survived forever. NodeJS could end up with the same faith as PHP and others. Picking a systems language like Rust gives you strength and opportunities for many years to come.</p><h3>Should you learn Rust?</h3><p>From a developers perspective: Yes, definitely. Rust has many unique features which will be copied also to other programming languages (<a href="https://github.com/apple/swift/blob/master/docs/OwnershipManifesto.md">like Ownership in Swift</a>). Learning Rust sharpens your thinking and will make you more considered in your day-to-day language of choice.</p><p>From a safety and correctness perspective: You should aim to replace part of your web service with Rust. Start small and see where it leads you. Other companies like <a href="https://www.rust-lang.org/static/pdfs/Rust-npm-Whitepaper.pdf">NPM</a>, <a href="https://www.wired.com/2016/03/epic-story-dropboxs-exodus-amazon-cloud-empire/">Dropbox</a> and <a href="https://www.youtube.com/watch?v=u6ZbF4apABk">Yelp</a> are doing it and had big success.</p><p><a href="http://www.arewewebyet.org/">Rust for the web is not completely there</a>, but once fully landed, it can not only convert your web services into safe bets. Once mastered, Rust lets you jump up and down the stack, explore Computer Science concepts first hand and build tools in your free time other then the next CRUD application.</p><p>So, take the chance and make 2019 the year you learn Rust. Have <a href="https://medium.com/@gruberbastian/rust-for-the-web-02-x-deploy-your-first-app-51d1ed69cbe3">something in production</a> by Christmas and try to replace part of your services at work in Rust and see if it’s successful. Rust will not only let you sleep calmer at weekends, knowing that a rock solid <a href="https://doc.rust-lang.org/book/ch14-01-release-profiles.html">binary</a> is running in production, but the skills you gained let you explore a vast universe of possibilities around technology.</p><blockquote>I will help you with that. Follow my series on “<a href="https://levelup.gitconnected.com/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">Practical Web Development with Rust</a>” and build with me a shiny web application in the next few months.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de86d2e46d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust for the Web — 02/x: Deploy your first App]]></title>
            <link>https://medium.com/@gruberbastian/rust-for-the-web-02-x-deploy-your-first-app-51d1ed69cbe3?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d1ed69cbe3</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 14:48:06 GMT</pubDate>
            <atom:updated>2019-03-19T09:20:26.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Programming in Rust— 02/x: Deploy your first App</h3><blockquote><a href="https://medium.com/@gruberbastian/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">You can find the Introduction to web programming in Rust over here.</a> Follow me on <a href="https://medium.com/@gruberbastian">Medium</a> or <a href="https://twitter.com/byteadventures">twitter</a> to always get the latest information about web development in Rust. Also checkout the <a href="https://github.com/gruberb/web-programming-in-rust">GitHub repository to his series</a>.</blockquote><h4><strong>This series has 3 goals</strong></h4><ol><li>Show the obstacles new developers will face when programming in Rust but also its advantages when it comes to the specific topic (this time: Deployments).</li><li>Show different options for web development in Rust.</li><li>Always have an updated application in production afterwards.</li></ol><p>Number three is super important for me. That’s the reason why we start part 02/x with a few ideas on what you can build, and why this tutorial will look like as it does. Whenever you learn something new, take this mental model:</p><blockquote><em>Never do things for their own sake</em></blockquote><p>Which translate to: Never learn Rust just because you want to learn Rust. This is the biggest factor why you will fail to learn a new language or basically anything in life. You have to have a goal in mind, a reason to do something.</p><h4><strong>“So how should I learn Rust then?”</strong></h4><p>For you to be able to successfully learn Rust, you need two things.</p><ol><li>Have an app or idea in mind you want to see in production. This can be a service to calculate prime numbers, a web app to track your programming goals, a service which fetches your latest likes on GitHub and tracks their activities etc. You decide what you want to build.</li><li>Hold yourself accountable to it. Tell your friends, work colleagues or your partner that you promise them that in 6 months time, they will be able to use this service. Every few days or weeks, you will keep them updated about your current status.</li></ol><p>It doesn’t need to be a polished idea or a service to compete with other apps. It has to be something you would like to have. It will help you staying through the hardships in the beginning, and through the phase when the honey moon is over and you see that Rust can be hard at times.</p><p><strong>I will make mine public as well:</strong></p><p><em>At the end of the next 6 months, I have a running web service with frontend for my MeetUp “Rust and Tell Berlin” up an running so speakers can submit proposals and slides and videos can be watched from talks which were held the previous events.</em></p><p>I will hold myself accountable through this tutorial series.</p><p>Lets move on. In this part of the series, we want to deploy our first application. If you come from NodeJS, the deployment life cycle looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*Y5YooLGDGoJYyCgt6QLLKA.png" /><figcaption>Possible breaks during a deployment and in production</figcaption></figure><p>With NodeJS, you can push any code to a production server. You have to have good tests, ESLint and other tools to catch undefined and Type errors.</p><p>In an ideal world, we have a development cycle which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*UD1nPkc_9f7wUUa5FObFGg.png" /><figcaption>An ideal world scenario where the code fails before it is getting deployed</figcaption></figure><p>So we want to break things as early and close to the code (your local machine) as possible. Once we figured out a working code base, we would like to bring exactly this working solution onto a server. Because of Rusts Type System and strong compiler, we would be able to pack a working binary and move it to production. Tests would cover the rest of the errors.</p><p><strong>Rust moves possible errors closer to the coding environment</strong></p><p>a) The Rust Compiler will catch a lot of problems, almost all of them.</p><p>b) You can catch the rest with good tests (in our case: Error handling when receiving the wrong parameters).</p><p>c) After you can compile your Rust Code, you have a binary which can be shipped in many different ways.</p><h4>Difference between local and production-ready code</h4><p>When we talk about deploying, we have to make sure that our code is able to:</p><ul><li>randomly assign a PORT based on the environment it is running</li><li>handle errors gracefully</li><li>respond to not expected input with proper return codes and messages</li><li>fail early in the deployment pipeline with a proper test setup</li><li>log events so errors can be traced</li></ul><p>In this article we will cover the first must-have (randomly assigning a PORT). Each article in the series will cover the rest of the requirements.</p><p><strong>Four different deployment options</strong></p><p>We generally have different deployment and hosting options. Some are more suited for large scale application and some are better for private projects and to get a project off the ground without too much complexity. Our options are:</p><ul><li>Managed Deployments / Hosting (Heroku)</li><li>Self managed via Docker and a Docker registry</li><li>Self managed via Docker and a Git registry</li><li>Managed Serverless Lambda functions (AWS Lambda, ZEIT now)</li></ul><p>We will cover each of these options in this article and see advantages, disadvantages and how to prepare your Rust Code so it can be deployed (in the best possible way).</p><h3>Building the first version of your app</h3><p>As we said in the beginning, we need an idea and what we want to build. Even if we map out a bigger picture of the application in the next article (03/x), we can get started and choose a framework we want to build it with:</p><ol><li><a href="https://rocket.rs/">rocket</a></li><li><a href="https://actix.rs/">actix</a></li><li><a href="https://gotham.rs/">gotham</a></li><li><a href="https://github.com/rustasync/tide">tide</a> (work in progress)</li></ol><p><a href="https://medium.com/@gruberbastian/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">As seen in the first article</a>, you can go lower level if you want:</p><ol><li><a href="https://hyper.rs/">hyper</a></li><li><a href="https://docs.rs/reqwest/0.9.11/reqwest/">reqwest</a></li><li><a href="https://github.com/carllerche/h2">h2</a></li></ol><p>We will pick one framework for the written version of this article. I will pick <a href="https://github.com/rustasync/tide">tide</a>, since I am planning to contribute to it more in the future. I will map out solutions for rocket and actix <a href="https://github.com/gruberb/web-programming-in-rust">in the GitHub repository for this series.</a></p><h3>Set up our app</h3><p>We want to make sure to use asynchronous code, which is not in Rust stable yet. Therefore we need to install and set the <a href="https://doc.rust-lang.org/book/appendix-07-nightly-rust.html">nightly version</a> of Rust:</p><pre>$ rustup install nightly-2019-02-25<br>$ rustup default nightly</pre><p>Now we can create our application. Open a terminal window and enter:</p><pre>$ cargo new my-cool-web-app<br>$ cd my-cool-web-app</pre><p>This will generate our first folder structure. The bare bones of a running web app with <a href="https://github.com/rustasync/tide">tide</a> look like this:</p><p><strong>Cargo.toml</strong></p><pre>[package]<br>name = &quot;my-cool-web-app&quot;<br>version = &quot;0.1.0&quot;<br>authors = [&quot;YOUR NAME + EMAIL&quot;]<br>edition = &quot;2018&quot;</pre><pre>[dependencies]<br>tide = &quot;0.0.5&quot;</pre><p><strong>main.rs</strong></p><pre>#![feature(async_await)]</pre><pre>fn main() {<br>    let mut app = tide::App::new(());<br>    app.at(&quot;/&quot;).get(async || &quot;Hello, world!&quot;);</pre><pre>    app.serve();<br>}</pre><p>As we said earlier, we need to give the hosting environment the chance to assign a PORT to our application.</p><p>Our <strong>main.rs </strong>has to accompany these requirements:</p><pre>#![feature(async_await)]</pre><pre><em>// to be able to read environment variables<br></em>use std::env;</pre><pre><em>// to be able to pass a different base configuration to our app<br></em>use tide::{configuration::Configuration};</pre><pre><em>// we need to read the PORT from the env variable (Heroku sets it)<br></em>fn get_server_port() -&gt; <em>u16</em> {<br>    env::var(&quot;PORT&quot;)<br>    .ok()<br>    .and_then(|p| p.parse().ok())<br>    .unwrap_or(8181)<br>}</pre><pre>fn main() {<br>    let mut app = tide::App::new(());<br>    let app_config = Configuration::build()<br>        .address(String::from(&quot;0.0.0.0&quot;))<br>        .port(get_server_port())<br>        .finalize();</pre><pre>    app.config(app_config);<br>    app.at(&quot;/&quot;).get(async || &quot;Hello, World!&quot;);</pre><pre>    app.serve();<br>}</pre><p>With this setup ready, we can go over each deployment option.</p><h3>Managed Deployments via Heroku</h3><blockquote>Managed environments are for the most part just an abstraction. They internally do the same as you would with your own pipeline: Push code to a git repository. A “hook” is watching this repository and on changes will start to compile the latest version and run it. For you however, it’s just a git push heroku master .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9izLeauVSUtKW2pD2HBRA.png" /><figcaption>High level overview of deployments via Heroku</figcaption></figure><p>To get started, you need a <a href="https://signup.heroku.com/">Heroku account</a> (free). Login with your new account and create a new app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtpO90QkrNVG6UQiQO1-Sg.png" /><figcaption>“Create new app” interface in Heroku</figcaption></figure><p>After clicking “Create app”, Heroku explains under the “Deploy” tab how to push your code to their servers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lDNLkXBhj05PH3X1eYFwA.png" /><figcaption>Heroku explains what you need to do to push and deploy code</figcaption></figure><h4>Prepare your code</h4><p>First, we need to be able to push our code base to the remote location (Heroku). Therefore please install the <a href="https://devcenter.heroku.com/articles/heroku-cli">Heroku toolchain</a>. Afterwards we can add the remote location to our GIT repository:</p><pre>$ cd my-cool-web-app<br>$ heroku login<br>$ heroku git:remote -a my-cool-web-app</pre><p>Next, we need to tell Heroku how to run our application after it is build. Heroku expects a file with the name <strong>Procfile</strong>, which has the start command in it:</p><pre>$ touch Procfile</pre><p>And put the following line it it:</p><pre>web ./target/release/my-cool-web-app</pre><p>We also have to tell Heroku which version of Rust we are using. Since we want to use nightly, we create a file called <strong>RustConfig </strong>in the root directory:</p><pre>$ touch RustConfig</pre><p>with the following line:</p><pre>VERSION=nightly</pre><h4>Caveat</h4><p>Rust is so new that Heroku doesn’t support it out of the box. We need to install and activate a “buildpack” for Rust. So inside the root directory of your application, execute the following commands</p><pre>$ heroku create --buildpack emk/rust<br>$ heroku buildbpacks:set emk/rust</pre><p>This will activate the language support for Rust.</p><p>Now we can</p><pre>$ git add .<br>$ git commit -m &quot;Init&quot;<br>$ git push heroku master</pre><p>When succeeded, we go back to the Heroku dashboard in the browser and click on the the generated domain (under “Settings”). A browser windiw should open and display “Hello, World!”.</p><h4>Summary</h4><ul><li>Heroku makes it easy to deploy your application</li><li>In less then 5 minutes you have a running version of your app live</li><li>You can assign your own domain and activate HTTPS (if you pay for it)</li><li>Heroku ist the best option when it comes to this tutorial and starting side projects: Cheap, easy to use and removes the overhead of deplyoments especially in the beginning</li></ul><h3>Docker</h3><blockquote>Using Docker has the huge advantage of being free in choosing your pipelines and environments. You can either build the image locally and push it as-is to a Docker registry. From there a server can take(download) and execute ( docker run ) it. Or you create a blueprint (Dockerfile) which other service can use to build on their servers.</blockquote><p>If you are using Docker for your deployments, you have two options. The first one is to push your code (with a Dockerfile) to a Git registry (like GitHub or Bitbucket) and then have a configured deployment server which listens to changes, SSHs into the Git registry, takes the code, deploys and runs it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRjiVMFbMjiPs7Eg1xvO7g.png" /><figcaption>Using Docker and a Git registry to publish your code</figcaption></figure><p>Your second option is to use a Docker registry. There you have the advantage to pre build your container and ship it as-it-is. This makes it sometimes faster to run deployments and you have to ship less code (especially in case of Rust).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbZQLRdAluzoLHFiHreCMQ.png" /><figcaption>Using Docker and a Docker registry to ship and publish your container</figcaption></figure><p>We can use Rusts feature of being able to be compiled to a binary. We can even go one step further and compile a static Rust binary with no external dependencies. What we would need for this, is:</p><ul><li>Build a Rust binary</li><li>Statically linked the needed C libraries to it so it can run on it’s own</li></ul><p>The result would be to have a binary which doesn’t even need Rust to run. Thanks to the Open Source community and Erik Kidd, there is already a solution out there which helps us with that.</p><p>The result is a super small Docker image with no external dependencies. Meet <a href="https://github.com/emk/rust-musl-builder">rust-musl-builder</a>. It is a Docker image which helps you build static Rust binaries. It will download the whole image just after the first execution.</p><p>Everything we type and create happens from the root directory of our application.</p><pre>$ cd my-cool-web-app</pre><p>Before we create our Dockerfile, lets see what we actually trying to do. We are using the rust-musl-builder to statically link the <a href="https://www.musl-libc.org/">musl-libc </a>library into our binary.</p><pre>$ docker run --rm -it -v &quot;$(pwd)&quot;:/home/rust/src ekidd/rust-musl-builder cargo build --release</pre><p>This will create our super small binary. You can inspect it like that:</p><pre>$ ls -lh target/x86_64-unknown-linux-musl/release/my-cool-web-app</pre><p>It is just a few MB small (in my example: 4,4MB). To be able to recreate this procedure over and over again, and not just on our local machine but also in a deployment pipeline on different servers, we create a multi-stage Dockerfile.</p><pre>FROM ekidd/rust-musl-builder:nightly AS build<br>COPY . ./<br>RUN sudo chown -R rust:rust .<br>RUN cargo build --release</pre><pre>FROM scratch<br>COPY --from=build /home/rust/src/target/x86_64-unknown-linux-musl/release/my-cool-web-app /<br>ENV PORT 8181<br>EXPOSE ${PORT}<br>CMD [&quot;/my-cool-web-app&quot;]</pre><p>You can build the image now via</p><pre>$ docker build -t my-cool-web-app:latest .</pre><p>And run it with</p><pre>$ docker run -d --rm -P --name heroku heroku:latest</pre><p>Now you can open your browser via:</p><pre>$ open <a href="http://$(docker">http://$(docker</a> container port my-cool-web-app 8181)</pre><p>We just created a super minimal Docker image which contains our binary with no external dependencies. You can inspect your just created image via</p><pre>$ docker image ls my-cool-web-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwDQT2E1fpaFm8RDCIgiGw.png" /><figcaption>The size of our Docker image is super small</figcaption></figure><h4>Summary</h4><ul><li>Docker is a beast, but when used wisely can be quite helpful</li><li>Especially with Rust: You can create statically linked binaries which are super small and don’t even need a Rust environment to run in</li><li>You also have much more options to host and run your application when choosing Docker</li><li>However, managed hosting environments like Heroku don’t allow pushing Docker images to their environment</li></ul><h3>Serverless runtimes — ZEIT/now</h3><blockquote>Serverless is a different mindset then the first two options. Serverless also means stateless, so you are not building web applications but functions. Instead of having API endpoints build into your app, you basically just have those API endpoints (in serverless terms: handlers). Our web frameworks like rocket and actix might be an overkill here. Right now, <a href="https://github.com/zeit/now-builders/issues/297#issuecomment-473682599">ZEIT is not supporting Rust nightly builds </a>in their new serverless environment.</blockquote><p>So instead of creating a binary (with cargo new web-app ), we create a library:</p><pre>$ cargo new now-service --lib<br>$ cd now-service</pre><p>Here we have to create a file called <strong>now.json</strong></p><pre>{<br>  &quot;name&quot;: &quot;now-service&quot;,<br>  &quot;version&quot;: 2,<br>  &quot;builds&quot;: [<br>    {<br>      &quot;src&quot;: &quot;src/index.rs&quot;,<br>      &quot;use&quot;: &quot;<a href="http://twitter.com/now/rust">@now/rust</a>&quot;<br>    }<br>  ]<br>}</pre><p>And our <strong>src/lib.rs</strong> example looks like this:</p><pre>use http::{Request, Response, StatusCode, header};</pre><pre>fn handler(request: Request&lt;()&gt;) -&gt; http::Result&lt;Response&lt;String&gt;&gt; {<br>    let response = Response::builder()<br>        .status(StatusCode::OK)<br>        .header(header::CONTENT_TYPE, &quot;text/html&quot;)<br>        .body(&quot;&lt;!doctype html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;A simple deployment with Now!&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Welcome to Rust on Now&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;.to_string())<br>        .expect(&quot;failed to render response&quot;);</pre><pre>    Ok(response)<br>}</pre><p>As with Heroku, you need to <a href="https://zeit.co/docs/v2/getting-started/installation/">install the ZEIT toolchain, which is called “now”</a>. There are several options. If you are on macOS, you can do it via:</p><pre>$ brew cask install now</pre><p>Which installs the Now application. Find it in your /Applications folder and open it. You can finish the installation by typing in your email address. This will also install the command line tool chain.</p><p>That’s basically it. You can type</p><pre>$ now</pre><p>and hit Enter. This will start the upload of your application. Login to your <a href="https://zeit.co/dashboard">ZEIT dashboard</a> and click on the provided link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjwqYYTzh0bYoEJSKzZ8ag.png" /><figcaption>All deployments are getting listed with a link to the deployed application</figcaption></figure><h4>Summary</h4><ul><li>Serverless lets you save costs: The service is just running when requested</li><li>This ends up in higher boot times which need to be considered</li><li>The mindset of serverless lets you rethink state and if you really need a fully fledged web application for some use cases</li><li>The deployment can take a bit longer when using AWS Lambda or ZEITs now</li></ul><blockquote>Follow me on <a href="https://medium.com/@gruberbastian">Medium</a> or <a href="https://twitter.com/byteadventures">twitter</a> to always get the latest information about web development in Rust. Also checkout the <a href="https://github.com/gruberb/web-programming-in-rust">GitHub repository to his series</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d1ed69cbe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to web programming in Rust for NodeJS developers]]></title>
            <link>https://levelup.gitconnected.com/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a9c048c4de1</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[introduction]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 10:53:02 GMT</pubDate>
            <atom:updated>2019-03-19T14:48:22.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Web Development with Rust for NodeJS Developers</h3><p>Rust is different. You can pick up Python or Ruby over the weekend, create a first CRUD application and be happy with the results.</p><p>With Rust… with Rust you will struggle to pass a String to a different method, change and return it. You then will order the Rust book, see its size, *sigh* and get started.</p><p>After a few weeks of fighting through the book after work, you give up and wait until someone else creates an easy-to-follow tutorial.</p><h4>Here is your “easy” tutorial</h4><p>I struggled with the same problems. Life circumstances however gave me a few months time on my hands to really focus on Rust.</p><p>What follows is a first overview, concept, and paths to follow. In the coming weeks and months, I’ll publish a series of articles to help you to get from concept to product.</p><h4>NodeJS vs Rust</h4><p>After installing them (I chose brew for macOS in this example, the method doesn’t matter), the underlying stack looks different. NodeJS needs V8, the runtime engine from Google, and bindings to the JavaScript library to run JavaScript code.</p><p>Rust depends almost completely on Rust itself. Just the compiler is using <a href="https://llvm.org/">llvm libraries</a>, which are written in C and C++.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*VVW_BFV4pt8Twqb5wPqRPQ.png" /></figure><h4>How much “web” is in Rust?</h4><p>It was and is a design decision <a href="https://users.rust-lang.org/t/announcing-the-http-crate/12123">not to include a standard http library in Rust</a>. The OSI layer is therefore covered differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*o82nUghM17eZtSHb3Cw-xQ.png" /></figure><p>Node covers the whole stack, and offers with Koa and Express, two well-known and “rock-solid” web frameworks which help you to build applications on top of HTTP.</p><p>On the Rust side of things, just <a href="https://doc.rust-lang.org/std/net/struct.TcpStream.html">TCP</a> is implemented in the Rust Core. The current web frameworks (<a href="https://actix.rs/actix/actix/">actix</a> and <a href="https://rocket.rs/">rocket</a>) are implementing everything up until HTTP though. So you don’t need to care where this is coming from.</p><p>If you want to use pure HTTP calls without any larger framework, you can install “crates” (equivalent to npm packages in the Node world) which implement the HTTP protocol (like <a href="https://github.com/hyperium/hyper">hyper</a> and <a href="https://github.com/tiny-http/tiny-http">tiny_http</a>).</p><h4>npm vs cargo</h4><p>Node is using npm for its package management:</p><ul><li>npm install is installing dependencies</li><li>npm run xyz is executing scripts inside the package.json</li></ul><p>On the Rust side, <a href="https://doc.rust-lang.org/cargo/">cargo is handling everything related to your project</a>:</p><ul><li>cargo new NAME --bin is creating an application</li><li>cargo new NAME --lib to create a library</li><li>cargo run is executing the code</li><li>cargo build is creating an executable</li><li>cargo test is running all tests inside the project</li></ul><p><a href="https://github.com/rust-lang/cargo/issues/5586">There is an open PR</a> to add cargo add to install dependencies. Right now you have to add them by hand to your Cargo.toml file. As you see, you don’t need to include scripts in a package.json to run tests or build and test your application.</p><blockquote>Mindset change: Cargo is fetching the packages after cargo run , and just if the version changed. So the first time it will fetch all packages, the second time just when a change in the version number happened. Unlike npm i which fetches the packages right away, and will add it to the package.json with the save notation.</blockquote><h4>Ecosystem</h4><p>Node is not successful for no reason. The ecosystem is rich and flourishing. Rust is still developing, but has already many great “crates”. The website <a href="http://www.arewewebyet.org/">arewewebyet.org</a> is tracking the progress and showing you interesting packages in the Rust world.</p><p>There is also an attempt to create an official Rust Web Framework, called <a href="https://github.com/rustasync/tide">Tide</a>. It is already pretty mature and can be used for side projects. Feel free to contribute and help craft a great environment for web development in Rust.</p><h4>Asnyc programming aka Promises aka Futures</h4><p>Nodes killer feature are Promises. Although not always easy to understand and handle, Promises and the event loop are what makes Node so lucrative.</p><p>Rust is also implementing an asynchronous mechanism, which are not yet in the final version. They are called <a href="https://github.com/rust-lang-nursery/futures-rs">Futures</a>. A library called <a href="https://tokio.rs/">Tokio</a> is already offering an asynchronous run time. You can track the progress on asynchronous programming in Rust over at <a href="https://areweasyncyet.rs/">areweasyncyet</a>.</p><h4>How to get started?</h4><ol><li>Install Rust: curl https://sh.rustup.rs -sSf | sh</li><li>Create a new project: cargo new web-app --bin</li><li>cd web-app</li></ol><p>Now you can choose your web framework of choice. You can either start with <a href="https://rocket.rs/">Rocket</a> or <a href="https://actix.rs/">actix</a>. You can follow the tutorials on the website to get a first web application running.</p><h4>Heads up: undefined, borrowing and types</h4><p>To not to get frustrated until my next post, here are the main four things about Rust you will have to get used to (which are quite awesome after a while).</p><p>The following example covers already a great amount of new concepts. Make sure to add reqwest to your Cargo.toml dependencies:</p><pre>reqwest = “0.9.11</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19buWOAtuYgd4I9q4Qtuhw.png" /></figure><ol><li>There is no undefined. Rust has no real null value. This is a feature. Rust has a type called <a href="https://doc.rust-lang.org/std/option/index.html">Option</a>, which encapsulates either the return value or None. In this case, we use the <a href="https://doc.rust-lang.org/std/result/#result-and-option">Result</a> type to return a value. You could, instead of returning a String, return an Option which might have a String value, or None if the website we are fetching from doesn’t contain any text. An easy solution, which you should not use in production, is to .unwrap() results to get the String out of the encapsulation. <a href="https://doc.rust-lang.org/std/result/#result-and-option"><strong>Homework (click): Try to check if the GET request errored and return an Error in this case instead of Ok().</strong></a></li><li>You must have heard about <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">borrowing</a>. In short: Every assignment (=) to a non trivial type (everything which doesn’t have a fixed size) moves the ownership over. The method fetch_text() is not taking ownership over the url but just using a reference to it (via the &amp; ).<strong> </strong><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=d7527a2b8570393dd70c2083172d621a"><strong>Homework (click): Figure out why this code here fails and how to solve it.</strong></a></li><li>You always have to know which type is returned from a method. In this example, our HTTP crate reqwest is returning a Response struct (type) which implements certain methods. The documentation is, as with so many crates, excellent. <a href="https://docs.rs/reqwest/0.9.11/reqwest/struct.Response.html#method.text">So have a look here</a>.</li><li>You don’t have to type return to return a value from a method. Just don’t put a ; at the end of a statement and this becomes your return value.</li></ol><p>Use this example to play around, see where you can get errors and learn to fix them.</p><h4>Is this all?</h4><p>Two opinions:</p><ul><li>“Sadly no!”</li><li>“No, but that’s a good thing!”</li></ul><p>You actually have to learn a decent amount of Rust to get started. This is what I am here for. In the next few days, weeks and months I will cover the basics up until creating a solid web application.</p><p>Up until then, I can recommend <a href="https://exercism.io/my/tracks/rust">the Rust track on Exercism.io</a> and the <a href="https://doc.rust-lang.org/stable/book/">Rust Book</a> which you can find also in a paper version at your local book store or at Amazon.</p><p><a href="https://medium.com/@gruberbastian/moving-from-nodejs-to-rust-in-2019-62c0b85d2fa7">As mentioned in my first article</a>, Rust is making you a better developer, so the road will be long at times, but always worth it. Follow me on <a href="https://twitter.com/byteadventures">twitter</a> or <a href="https://medium.com/@gruberbastian">Medium</a> to stay up to date!</p><figure><a href="https://levelup.gitconnected.com"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6CoI_MRyZ1JInNPsBSHtA.png" /></a></figure><p><a href="https://gitconnected.com/learn/rust">Learn Rust - Best Rust Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a9c048c4de1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">Intro to web programming in Rust for NodeJS developers</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[Moving from NodeJS to Rust in 2019]]></title>
            <link>https://medium.com/@gruberbastian/moving-from-nodejs-to-rust-in-2019-62c0b85d2fa7?source=rss-b04a8ca61d5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/62c0b85d2fa7</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Bastian Gruber]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 05:48:56 GMT</pubDate>
            <atom:updated>2019-03-11T20:00:14.147Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><a href="https://medium.com/@gruberbastian/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">For a more nuanced introduction and in-depth introduction to web programming in Rut, read part 1 of X in my series.</a></blockquote><p>If you followed me for the last few weeks or months on <a href="https://twitter.com/byteadventures">twitter</a>, you saw that I take Rust pretty seriously lately.</p><p>In this article I want talk about my reasoning behind it, and why you as a NodeJS developer should consider the same.</p><h4>Rust is the new JavaScript</h4><p>JavaScripts appeal comes mainly from it’s easy-to-use and available-everywhere characteristics. It’s the only choice in the browser to build applications.</p><p>It also shines on the server side of things with its easy to use frameworks, easy syntax and no static types.</p><p>Building a web application with NodeJS takes literally a few hours. And with React on the frontend you have a always evolving and powerful tool to build complex applications.</p><p>So why is Rust the new JavaScript then?</p><ul><li>Rust is available not only on the server, but also runs on hardware</li><li><a href="https://rustwasm.github.io/docs/book/why-rust-and-webassembly.html">With WASM, Rust will be able to run in the browser as well</a></li><li>As a frontend developer, NodeJS helped you to get into server-side programming. Learning Rust will help you covering the whole stack from hardware to server to frontend</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*QcibeYRbU1wZcwlKTplarg@2x.jpeg" /></figure><h4>Rust is the logical next step</h4><p>NodeJS was so successful that even large applications got build with it. However, one missing piece was and is its type system. With no static types, Microsoft had to step in and create TypeScript. It offers many people who had to move from C++ and Java a familiar environment.</p><p>However, now instead of learning JavaScript, you are learning a tool from Microsoft which adds another layer on top of all the other layers to make JavaScript run on the server.</p><blockquote>Learning TypeScript is bad pain, learning Rust is good pain</blockquote><p>When you learn TypeScript, you mostly cope with a tool which is there to improve a language which lacks well thought through features.</p><p>If you want types, and you might need them in bigger applications, you can move to a typed language right away. Why bother with a transpiler?</p><h4>Types</h4><p>You know the saying: The biggest strength is also your biggest weakness?</p><p>Well with Rust, the thing you will love the most is its static type system. It will take some time though. The type system will prevent you from easily deploying a CRUD app in under one hour, but it will help you in the long run crafting sophisticated, safe and fast applications.</p><p>And once you are used to it, you can create your own “rust-web-starter” app and get the same benefits of crafting fast prototypes as you would with Node.</p><h4>Rust is the new Bitcoin, but better</h4><p>I painted a pretty simple picture: Why would you then choose Rust over, lets say Go? Since Go has static types as well (<a href="https://drewdevault.com/2019/02/18/Generics-arent-ready-for-Go.html">although, generics are not yet a thing yet in Go-land</a>).</p><p>Because Rust is the new Bitcoin. The majority of contributers are not working for Mozilla (who took over the Rust project and published it). The development of the language happens in the open, and everyone can contribute. Decentralized if you wish. Everything happens on <a href="https://github.com/rust-lang">GitHub</a> and in <a href="https://discord.gg/nDUEKhX">Discord</a>.</p><p>If Mozilla would completely abandon the language, it would still live on and flourish. Go however is solely maintained within Google, and we all know what happens to most Google projects after a few years.</p><p>It doesn’t seem like Go will go anywhere, the language is great and you will be super productive with it. But so is Rust, plus it has all the other features.</p><h4>Documentation</h4><p>When I talked about “leveling up” in the beginning, I meant leveling up. You don’t have to read through StackOverflow to fix some random problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WixdCdyoUzcbd6qX0goI7A@2x.jpeg" /></figure><p><a href="https://doc.rust-lang.org/std/index.html">The Rust docs are superb</a>. You have to get used to them though. The structure and explanations make more sense once you start building your own applications and need help.</p><h4>The Rust Compiler</h4><p>Your biggest enemy and your best friend. The term “good pain” couldn’t be more accurate when it comes to the Rust Compiler. You will hate it that even simple exercises will fail in the beginning and you can’t even easily pass Strings around.</p><p>But, once you got the hang of it, you realize the biggest strength of the compiler:</p><blockquote>You can pair program with the compiler and be sure to have crafted a solid application afterwards</blockquote><p>Rust is still evolving, and you might live in a city where the community is not strong yet! So what? The Rust Compiler knows everything, and if it approves your code you can feel safe and secure.</p><h4>Obviously…</h4><p>Rust is as well:</p><ul><li><a href="http://blog.seraum.com/crystal-lang-vs-nodejs-vs-golang-vs-julia-vs-rust-vs-luajit-vs-c-fibonacci-benchmark">Faster then NodeJS</a></li><li>Easier to deploy</li><li><a href="https://www.rust-lang.org/static/pdfs/Rust-npm-Whitepaper.pdf">Easier to maintain</a></li><li><a href="https://blog.rust-lang.org/2018/12/17/Rust-2018-dev-tools.html">The tooling is build-in</a></li><li><a href="https://github.com/rust-lang/rfcs">Crafted over many years and maintaines with clear goals in mind</a></li></ul><p>[UPDATED 03/10]: <a href="https://medium.com/@gruberbastian/intro-to-web-programming-in-rust-for-nodejs-developers-1a9c048c4de1">Here is Part 1 of X of how to get started with web development in Rust from a NodeJS perspective.</a></p><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2IVAl0TbsfES9cFGYr40g.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_read_later_text">Journal</a>.</p><p>🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: <a href="https://usejournal.com/newsletter/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_text">Get the noteworthy newsletter &gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62c0b85d2fa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>