<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Twenty Two Tabs]]></title><description><![CDATA[Twenty Two Tabs]]></description><link>https://blog.twentytwotabs.com/</link><image><url>https://blog.twentytwotabs.com/favicon.png</url><title>Twenty Two Tabs</title><link>https://blog.twentytwotabs.com/</link></image><generator>Ghost 2.19</generator><lastBuildDate>Mon, 13 Apr 2026 04:33:08 GMT</lastBuildDate><atom:link href="https://blog.twentytwotabs.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[The Smallest Bash Script in the Universe]]></title><description><![CDATA[A detailed read on why every script must begin with #!, how program execution works in Linux with fork and exec, and how interpreters are actually run.]]></description><link>https://blog.twentytwotabs.com/the-smallest-bash-program-in-the-universe/</link><guid isPermaLink="false">5b8c9f40bd14fb00010d2a75</guid><category><![CDATA[bash]]></category><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Mon, 03 Sep 2018 13:57:00 GMT</pubDate><media:content url="https://blog.twentytwotabs.com/content/images/2018/09/tree-branches-against-blue-sky-1.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.twentytwotabs.com/content/images/2018/09/tree-branches-against-blue-sky-1.jpg" alt="The Smallest Bash Script in the Universe"><p>Welcome back 👋🏽</p>
<p>As usual, if you find my ramblings interesting and want to read more, or think they're rubbish and want to tell me about it, remember to scroll down to leave a comment before, during, or after your read.</p>
<h1 id="tldr">tl;dr</h1>
<p>If you're here to see the smallest Bash script, look no further.</p>
<p>Here it is:</p>
<pre><code>#!/bin/bash
</code></pre>
<p>Read on if you're wondering why it's not just an empty file like 10-years-ago-me.</p>
<h1 id="thesmallestkindasortabashscriptintheuniverse">The Smallest Kinda Sorta Bash Script in the Universe</h1>
<p>I'll let you in on a little secret.</p>
<p>Back in the day I had this misconception that a Bash script was any text file with execute permission.  In other words, I thought that <code>shell_script</code> in the following example would always be executed using <code>bash</code> as the interpreter:</p>
<pre><code># Create an empty file
$ : &gt;shell_script

# Mark that file as executable
$ chmod u+x shell_script

# Run that file
$ ./shell_script
$
</code></pre>
<p>To explain why <code>shell_script</code> is only kinda sorta the smallest Bash script, we gotta go a little deeper and learn how programs are executed on Linux.</p>
<h1 id="forkandexecve">fork and execve</h1>
<p>Most programs running on Linux run at least some code from the C programming language.</p>
<p>If they're not directly written in C, they're very likely either running code from the C runtime or are running in an interpreter that uses the C runtime.  And BTW, for the purposes of this post you can think of the C runtime as a bunch of functions that have already been written for C programmers.  This code sits in a shared library, ready to run.</p>
<p>The two functions we'll be focusing on are ones you wouldn't ever want to implement yourself as they interact with the kernel to do fun and exciting things that you don't want to get wrong.  Whoever had to review my implementations of these functions in that university operating systems course can attest to that.  I'm sorry for subjecting you to that, professor <em>I Forgot What your Name Is</em>.</p>
<p>Let's follow a C program named <code>shelly</code> as it runs on a Linux box and executes another program named <code>script</code>.  Whenever <code>shelly</code> wants to run another program, it needs to run two functions from the C runtime: <code>fork()</code> and <code>execve()</code>.</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/shelly_exec_fork-00e2df12-3657-47b0-8adf-98f1335ea70c.png" alt="The Smallest Bash Script in the Universe"></p>
<h2 id="processsplittingwithfork">Process Splitting with fork</h2>
<p><code>fork()</code> tells the kernel to clone the currently running process into two processes.  It's sort of like how cells split in a petri dish.  In Linux, however, the resulting pair of processes forms a hierarchy with the original process becoming the parent of the new process.  Once it's done, the first instruction of either process is a <code>return</code> from <code>fork()</code>.</p>
<p>So after <code>fork()</code> completes, there will be two <code>shelly</code> processes.</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/shelly_fork-a1c3c30d-8377-4163-a4a2-640fa20dfda1.png" alt="The Smallest Bash Script in the Universe"></p>
<h2 id="processreplacementwithexecve">Process Replacement with execve</h2>
<p><code>execve()</code> is a little more interesting.</p>
<p>It asks the kernel to replace the program running in the current process with some other program. <code>execve()</code> quite literally obliterates the memory image of the running program and replaces it with a new memory image for the desired program.  When its done, execution continues at the first instruction of that new program.  So in our example above, after <code>execve()</code> completes, there will be one process running the code for the <code>shelly</code> program and one process running the code for the <code>shell_script</code> program.</p>
<p>Since no remnants of <code>shelly</code> 's code will survive <code>execve()</code>, the call accepts data that the kernel will pass to the new program when it starts. This data is passed in two forms which you may have heard of:</p>
<ul>
<li><em>environment variables</em> (a list of key-value pairs)</li>
<li><em>arguments</em> (an array of strings).</li>
</ul>
<p>Arguments usually describe what a process should call itself and what precisely it should do. Environment variables usually describe the system that a process is running in or other software systems that a process may need to work with.</p>
<p>Since the environment of a process will very likely be the same as its children, that set of key-value pairs is usually just copied from the already running program to <code>execve()</code> with <em>maybe</em> a few additions.</p>
<p>Arguments are usually invocation-specific, and so are instead passed to <code>execve()</code> explicitly every time it's run.</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/shelly_exec-766e63c7-f055-4dc9-8ffd-2700c1553128.png" alt="The Smallest Bash Script in the Universe"></p>
<h2 id="whatdoesexecveactuallydo">What does execve actually do?</h2>
<p><code>execve()</code>'s only purpose in life is to ask the kernel to run programs from executable files.</p>
<p>It does this by asking the kernel to identify the type of program in an executable file and to run the appropriate kernel code to load it and set it executing.  The kernel has handlers for programs in a handful of different binary formats, but the handler we're interested in is <a href="https://github.com/torvalds/linux/blob/v4.19-rc2/fs/binfmt_script.c#L24-L25">right here</a>.</p>
<h2 id="scriptsmustbeginwith">Scripts Must Begin with #!</h2>
<p>Here's the beginning of the real magic of executing a script file:</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/load_script-80abb39b-7a25-4494-add4-22f669abaa11-1.png" alt="The Smallest Bash Script in the Universe"></p>
<p>The most important code (highlighted) checks the first two characters of the first line of the program file.  If these characters are <code>#</code> followed by <code>!</code>, the program is considered a script. It then goes on to parse out the text following the <code>#!</code> into two words: an <em>interpreter</em> and an <em>optional argument</em> to that interpreter.</p>
<p>With these values in hand, the kernel repeats what it was asked to do with a few changes:</p>
<ul>
<li>Instead of loading and executing the script file, load and execute the <em>interpreter</em>.</li>
<li>Use the <em>optional argument</em> from the <code>#!</code> line as the first argument to the interpreter.</li>
<li>Use the script's name as the second argument.</li>
<li>For the remaining arguments, simply copy them from the arguments <code>execve()</code> was originally given.</li>
</ul>
<h1 id="runningtheactualsmallestbashscriptintheuniverse">Running the Actual Smallest Bash Script in the Universe</h1>
<p>So let's say <code>shelly</code> tried to run <code>execve()</code> on a program with the following contents:</p>
<pre><code>$ cat shell_script
#!/bin/bash
$
</code></pre>
<p>Even if <code>shelly</code> forks and executes <code>shell_script</code>, the kernel will execute <code>/bin/bash</code> with a first argument of <code>shell_script</code>.</p>
<h1 id="thesmallestbashscript">The Smallest Bash Script</h1>
<p>And that's why the smallest Bash script is:</p>
<pre><code>#!/bin/bash
</code></pre>
<p>...and why it's important to always begin shell scripts with <code>#!</code>.</p>
<p>The end.</p>
<h1 id="umreally">Um...really?</h1>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/objection.jpg" alt="The Smallest Bash Script in the Universe"></p>
<p>You may notice that if you list a bunch of commands in a text file and run it in Bash, those commands still execute as if the file were a Bash script:</p>
<pre><code># Create a file containing two lines of shell
$ cat &gt; shell_script &lt;&lt;COMMANDS
echo Hello
echo world
COMMANDS

# Mark the file as executable
$ chmod u+x shell_script

# Execute the file
$ ./shell_script
Hello
world
$
</code></pre>
<p>I haven't been lying to you.  Attempts to ask the kernel to execute a text file that doesn't start in <code>#!</code> will always fail.  If Bash is doing the executing, though, the shell will do you a solid.</p>
<p>Don't believe me?  Take a peek at <a href="https://github.com/bminor/bash/blob/64447609994bfddeef1061948022c074093e9a9f/execute_cmd.c#L5532-L5565">the source</a>:</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/09/bash-execute-command-3c6e6edf-5dd4-4433-b5ea-a72c07b8d5dd.png" alt="The Smallest Bash Script in the Universe"></p>
<p>Your script may not always be executed by Bash (e.g. from a cron job, by the backend of a web service, or by a continuous integration system) so it's important to always start scripts with <code>#!</code> followed by the interpreter and an optional argument.</p>
<h1 id="furtherreading">Further Reading</h1>
<p>Hope you found that interesting and helpful.  If it was, be sure to click Recommend below and may be even leave a comment.</p>
<p>For further reading on how Bash scripts are executed, see:</p>
<ul>
<li><a href="https://lwn.net/Articles/630727/">How programs get run</a>, Linux Weekly News</li>
<li><a href="https://github.com/torvalds/linux/blob/v4.19-rc2/fs/binfmt_script.c"><code>binfmt_script.c</code></a>, The Linux Kernel</li>
<li><a href="http://man7.org/linux/man-pages/man2/execve.2.html"><code>execve(2)</code></a>, The Linux Manual</li>
<li><a href="https://github.com/bminor/bash/blob/64447609994bfddeef1061948022c074093e9a9f/execute_cmd.c#L5532-L5565"><code>execute_command.c</code></a>, GNU Bash</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[The Magic of $@]]></title><description><![CDATA[Recently while lurking some geeky subreddits, I stumbled upon an interesting question about bash.  I have a bit of a soft spot for shell programming, so I decided to share some insight in a blog-worthy response.  If you too are interested in the magic variable that is $@, read on.]]></description><link>https://blog.twentytwotabs.com/the-magic-of-dollars-at/</link><guid isPermaLink="false">5b78765b2025f70001d2cda7</guid><category><![CDATA[bash]]></category><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Sat, 18 Aug 2018 22:51:45 GMT</pubDate><media:content url="https://blog.twentytwotabs.com/content/images/2018/08/software-developer.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://blog.twentytwotabs.com/content/images/2018/08/software-developer.jpg" alt="The Magic of $@"><p>Hey 👋</p>
<p>Recently while lurking some geeky subreddits, I stumbled upon an interesting question about <code>bash</code>.  I have a bit of a soft spot for shell programming, so I decided to share some insight in a blog-worthy response.  If you too are interested in the magic variable that is <code>$@</code>, read on.</p>
<p>I promise you'll learn something 🎓</p>
<p>So, here's the question:</p>
<blockquote>
<p>Can anyone explain this... I have a script which runs commands in docker containers with docker run and sh -c. I pass the arguments of the script to the command with $@. Now if I do this directly it only passes the first argument, but if I assign it to a different variable first and then pass that variable to docker run I get all the arguments. Let's say I have a file bin/test and the contents is this:</p>
<pre><code class="language-shell">#!/usr/bin/env bash

# Outputs all arguments
echo &quot;$@&quot;

# Only outputs fist argument
docker run --rm -ti node:10.9 sh -c &quot;echo $@&quot;

# Outputs all arguments
args=$@
docker run --rm -ti node:10.9 sh -c &quot;echo $args&quot;
And I run it with bin/test foo --bar the output would be:

foo --bar
foo
foo --bar
</code></pre>
<p>Why does the second command only pass the first argument?</p>
</blockquote>
<h1 id="afewwordsaboutwords">A few words about words</h1>
<p>As some background, whenever a command is parsed and run, a bunch of things happen, including two important steps:</p>
<ul>
<li><strong>Parameter substitution:</strong> for example, replacing variable references like <code>$var</code> and <code>${bar}</code> with the contents of variables <code>var</code> and <code>bar</code> respectively.</li>
<li><strong>Word splitting:</strong> splitting a command line into a list of words suitable for a call to <a href="https://linux.die.net/man/2/execve"><code>execve(2)</code></a>.  In English, this means starting with a command line like <code>grep pattern file</code> and splitting it into a command name, <code>grep</code> and a list of arguments, <code>pattern</code> and <code>file</code>.</li>
</ul>
<p>Although other interesting things happen to command lines as the shell reads and executes them, those two steps happen in that order.  This is why seemingly correct scripts like:</p>
<pre><code class="language-shell">#!/bin/bash

file=&quot;abc def ghi.txt&quot;
cat $file
</code></pre>
<p>...don't quite work out as expected.</p>
<h1 id="isspecial">$@ is special 🌟</h1>
<p><code>$@</code> is a special variable when it comes to <em>parameter substitution</em> and <em>word splitting</em>.</p>
<p>If <code>$@</code> is evaluated while it's not surrounded by double quotes, it simply expands to a space delimited list of the positional parameters (the arguments to the enclosing script or function).</p>
<p>However, if <code>$@</code> is evaluated while it's directly surrounded by double quotes, it temporarily overrides word splitting such that each of the positional parameters are treated as separate words—one word per positional parameter.  This even includes the positional parameters that have spaces in them.</p>
<p>This is what makes this script crash and burn:</p>
<pre><code class="language-shell">$ cat foo.sh
#!/bin/bash

grep PASSWORD $@
$ ./foo.sh 'a file with spaces.txt'
grep: a: No such file or directory
grep: file: No such file or directory
grep: with: No such file or directory
grep: spaces.txt: No such file or directory
</code></pre>
<p>...while this script works out:</p>
<pre><code class="language-shell">$ cat foo.sh
#!/bin/bash

grep PASSWORD &quot;$@&quot;
$ ./foo.sh 'a file with spaces.txt'
MY PASSWORD IS passw0rd
</code></pre>
<p>This property also makes the output of even trivial scripts deviate ever so slightly from expectations:</p>
<pre><code class="language-shell">$ cat foo.sh
#!/bin/bash

echo You provided: $@
$ ./foo.sh &quot;a   parameter   with   tripled   spaces&quot;
a parameter with tripled spaces 🤔
</code></pre>
<p>Comparing the argument to <code>foo.sh</code> and its output, notice that sequences of multiple spaces are all folded into one. This is because the shell first expands <code>$@</code> into a space delimited list of the command line arguments, and then proceeds to split the resulting command line into words, starting with <code>./foo.sh</code> and ending in <code>spaces</code>.</p>
<h1 id="maybealittletoospecial">Maybe a little too special</h1>
<p>There's even more to <code>$@</code> 😱.  The moment a double-quoted <code>$@</code> is encountered, the shell temporarily goes into a word emitting mode</p>
<p>What this means is: if a double quoted <code>$@</code> appears directly after or right before what would otherwise be a word (with no separating whitespace), the first word emitted by <code>$@</code> will be joined to the word directly before it and the last word emitted by <code>$@</code> will be joined to word that directly follows it.</p>
<p>Feels like an example is in order:</p>
<pre><code>#!/bin/bash

echo a b c&quot;$@&quot;d e 
</code></pre>
<p>Here, <code>echo</code> will be called with the arguments: <code>a</code>, <code>b</code>, <code>c$1</code>, <code>$2</code>, ... , <code>${n}d</code>, <code>e</code>, and <code>f</code>. The same would happen if <code>$@</code> appeared in double quotes with other text. Like, <code>echo a b &quot;c$@&quot;d e f</code>: The first and last word from <code>$@</code> would be fused with <code>c</code> and <code>d</code>.</p>
<h1 id="isjustplainordinary">$* is just plain ordinary</h1>
<p>If you ever want to avoid <code>$@</code>'s special behaviour, use <code>$*</code>. It's just like <code>$@</code>, but it doesn't cause the script to go into funky modes. It just expands to the positional parameters, separated by single spaces.  No muss...no fuss.</p>
<h1 id="sowhysmyscriptbroken">So why's my script broken?</h1>
<p>So, back to the problem script:</p>
<blockquote>
<pre><code>echo &quot;$@&quot;
</code></pre>
</blockquote>
<p>This works as expected because it's being run, un-adulterated by the shell that's interpreting the script. The double quotes directly surrounding the $@ have the shell translate its command line parameters directly into words.</p>
<blockquote>
<pre><code>docker run --rm -ti node:10.9 sh -c &quot;echo $@&quot;
</code></pre>
</blockquote>
<p>This works strangely because the shell that's interpreting your shell script sees the <code>$@</code> and flips into word emitting mode: Although word splitting will occur on the rest of this command line later, when the shell expands <code>$@</code> it immediately starts turning it into words that will bypass the real word-splitting phase: <code>echo $@</code> becomes the following words, <code>echo (1st arg)</code> and <code>(2nd arg)</code>, <code>(3rd arg)</code>, (...the rest of the script's arguments as individual words).</p>
<p>By the time the entire command line is split into words, it becomes: <code>docker</code> <code>run</code> <code>--rm</code> <code>-ti</code> <code>node:10.9</code> <code>sh</code> <code>-c</code> <code>echo (1st arg)</code> <code>(2nd arg)</code> ... <code>(3rd arg)</code>. Docker then turns around and runs <code>sh -c 'echo (1st arg)' '(2nd arg)' '(3rd arg)' ...</code>, which means &quot;run the script <code>echo (1st arg)</code> with the command line arguments, <code>(2nd arg)</code>, <code>(3rd arg)</code>, ... .&quot;</p>
<p>To get around this strange behavior, you could try replacing <code>$@</code> with a variable that doesn't have special word-splitting-bypassing properties, like <code>$*</code>.</p>
<blockquote>
<pre><code>args=$@; docker run --rm -ti node:10.9 sh -c &quot;echo $args&quot;
</code></pre>
</blockquote>
<p>This works as expected because the value of <code>$@</code> is stored in the args variable. Even if it were double quoted, word splitting doesn't occur when you assign a value to a regular variable, so the variable just receives the list of command line args, separated by a space character as a single string. Since <code>$args</code> is a plain ol' variable, it's expanded without any funky word splitting nonsense in the <code>-c</code> scriptlet and runs as expected.</p>
<p>Hope this post is as helpful to you as it was to the reddit user who posted it.</p>
<p>Love shell?  Hate it?  Not sure why it does the things it does?</p>
<p><strong>Leave a comment</strong> and let's bash it out.</p>
<p>~ chris</p>
]]></content:encoded></item><item><title><![CDATA[Docker In A Nutshell]]></title><description><![CDATA[<p>Recently, I started ramping up on a little something called <a href="http://docker.io">Docker</a>.  In its simplest form, Docker lets you treat a runtime environment like a codebase under source control.</p>
<p>Want to record how an environment looks?</p>
<pre><code>docker commit &lt;container&gt; &lt;tag&gt;
</code></pre>
<p>Made a few unfortunate changes, and want</p>]]></description><link>https://blog.twentytwotabs.com/docker-in-a-nutshell/</link><guid isPermaLink="false">5b4bb0b762016a000135d41a</guid><category><![CDATA[docker]]></category><category><![CDATA[runtime]]></category><category><![CDATA[container]]></category><category><![CDATA[Getting Started]]></category><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Mon, 25 Apr 2016 20:38:00 GMT</pubDate><media:content url="https://blog.twentytwotabs.com/content/images/2018/08/horizontal.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.twentytwotabs.com/content/images/2018/08/horizontal.png" alt="Docker In A Nutshell"><p>Recently, I started ramping up on a little something called <a href="http://docker.io">Docker</a>.  In its simplest form, Docker lets you treat a runtime environment like a codebase under source control.</p>
<p>Want to record how an environment looks?</p>
<pre><code>docker commit &lt;container&gt; &lt;tag&gt;
</code></pre>
<p>Made a few unfortunate changes, and want to roll it back?</p>
<pre><code>docker rm &lt;container&gt;
docker run &lt;tag&gt; &lt;command&gt;
</code></pre>
<p>It's more than a little intruiging and I'll definitely get back to how to make the most of it, but first an admission.  Early on, I was routinely confused by all of the terms.  &quot;Images, containers and processes, oh my,&quot; I recall saying to myself on more than one occasion while staring aimlessly at an <code>xterm</code>.  To help me keep all this straight in my head, I whipped up a simple analogy.</p>
<blockquote>
<p>In docker...</p>
<p>An <em>image</em> is like a blueprint for a jail cell.</p>
</blockquote>
<p>A docker image contains a <em>starting point</em> for a runtime environment.  This includes all of the files on disk at the time that environment starts.  In there as well are tips on what network ports the process in the environment may need to listen on, the current working directory of this process, as well as a default command to run when the environment is started.</p>
<blockquote>
<p>A <em>container</em> is like a completed jail cell...with internet access.</p>
<p>A <em>dockerized process</em> is like a prisoner.</p>
</blockquote>
<p>A docker container is the <em>runtime environment</em> mentioned above.  Processes bound to a container may do whatever they want—create or delete files on disk, produce diagnostics, create users, bind network ports, or even create new processes.  The useful thing is that the effects of these actions will extend no further than the container walls.  This means that processes in two different containers can simultaneously, e.g. write different content to <code>/etc/foo.conf</code> or listen on port <code>8080</code> without conflict.</p>
<blockquote>
<p>The <em>docker daemon</em> is part prison guard; part construction crew.</p>
</blockquote>
<p>The docker daemon does a lot of work.  But the important bits involve creating containers from images, running dockerized processes, and recording their output.  The daemon also manages network traffic destined to containers (connections from other containers as well as ones routed in through the docker host), and helps manage requests to turn containers into new images.</p>
<blockquote>
<p>A <em>linux machine with <a href="https://linuxcontainers.org">lxc</a> enabled and <a href="https://docker.io">docker</a> installed</em> is like a prison.</p>
</blockquote>
<p>Docker is effectively a thin veneer over a still maturing set of kernel features collectively called <a href="https://linuxcontainers.org">Linux Containers</a>.  Containers are a not so easy way to setup isolated zones of execution on a Linux machine.  Docker makes these features extremely easy to use.</p>
<p>And that's it—Docker in a nutshell.  This will definitely save the day the next time I'm staring at my <code>xterm</code>.  Hope it saves yours, too :-)</p>
]]></content:encoded></item><item><title><![CDATA[Cloudant and Couchdb: Little Docs, Big Thoughts]]></title><description><![CDATA[<p>Especially for developers like me who were brought up on RDBS, when it comes to document-based data stores like <a href="https://www.cloudant.com">Cloudant</a> or its laid back self-hosted cousin, <a href="http://couchdb.apache.org/">CouchDB</a>, the first question to come to mind is <em>how do I structure my data</em>?</p>
<p>I'm learning more and more that the answer is</p>]]></description><link>https://blog.twentytwotabs.com/cloudant-and-couchdb-little-docs-big-thoughts/</link><guid isPermaLink="false">5b66830c4bb73600011c5bf2</guid><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Wed, 17 Feb 2016 04:55:00 GMT</pubDate><content:encoded><![CDATA[<p>Especially for developers like me who were brought up on RDBS, when it comes to document-based data stores like <a href="https://www.cloudant.com">Cloudant</a> or its laid back self-hosted cousin, <a href="http://couchdb.apache.org/">CouchDB</a>, the first question to come to mind is <em>how do I structure my data</em>?</p>
<p>I'm learning more and more that the answer is not always clear cut and actually changes over time.  Especially here, though, the old adage applies:</p>
<blockquote>
<p>Start simple, then make it complicated!</p>
</blockquote>
<p>Consider the following scenario:</p>
<p>You have been tasked with writing a web-app that houses a collection of real life <code>robot</code>s.  Each <code>robot</code> can have one or more <code>capability</code>s.  These <code>capability</code>s come in a handful of varieties, each of which can be registered with the web-app.</p>
<h2 id="startsimple">Start Simple</h2>
<p>When it comes to document-based data stores, the simplest way to store data is such that each document represents <em>a primary entity</em> from the problem domain. From the description, the primary entity is a <code>robot</code>, so having one document per <code>robot</code> would be <em>the simplest way</em>.</p>
<p>e.g.</p>
<pre><code class="language-language-javascript">{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;some-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Optimus&quot;,
    &quot;description&quot;: &quot;A robot full of snazziness.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;,
    &quot;capability_instances&quot;: [
        {
            &quot;type&quot;: &quot;transform-into-a-vehicle&quot;,
            &quot;description&quot;: &quot;Make a sound and change into a vehicle&quot;,
            &quot;instance_id&quot;: &quot;some-universally-unique-instance-id&quot;,
            ...
            ..
            .
        },
        ...
        ..
        .
    ]
}

</code></pre>
<h2 id="howaboutupdates">How About Updates?</h2>
<p>Updating a <code>robot</code>—for example, changing a <code>robot</code>'s <code>description</code>—is a matter of updating its document in <em>the Cloudant way</em>.</p>
<p>In other words:</p>
<pre><code>- Fetch the latest.
  - On error, bubble the error.
  - On success, update the description of what was fetched.
  - Insert fetched-and-modified document.
    - On error:
        - If it's a conflict, do this all again.
        - Otherwise, bubble the error.
    - On success, bubble success.
</code></pre>
<blockquote>
<p>But isn't this slow?</p>
</blockquote>
<p>In practice, not really, but there is a lot of cross talk here.  For predictable operations like updating a known field of a document, <a href="https://wiki.apache.org/couchdb/Document_Update_Handlers">update handlers</a> can be used to avoid the need to <em>fetch-a-doc-to-update-a-doc</em>.</p>
<p>Here is an example of an update handler:</p>
<pre><code class="language-language-javascript">{
    ...
    ...
    &quot;updates&quot;: {
        &quot;update-robot-description&quot;:  &quot;function (doc, req) {
            var resp = { 
                headers: {
                    &quot;content-type&quot;: &quot;text/plain&quot;,
                },
                code: 200,
                body: &quot;ok&quot;
            };
            
            if (!doc || !doc.type || doc.type !=== &quot;robot&quot;) {
                resp.code = 404;
                resp.body = &quot;not-found&quot;;
                return [ null, resp ];
            }

            doc.description = req.form.description;
            return [ doc, resp ];
        }&quot;
    }
    ...
    ...
}
</code></pre>
<p>With this update handler, the web-app can now update robot descriptions by sending a <code>POST</code> to <code>/_design/DESIGN/_update/update-robot-description/SOME_DOC_ID</code> with the <code>description</code> field set in the request body.</p>
<h2 id="views">Views</h2>
<p>Using Cloudant's built in APIs, given an ID, we can fetch the document for any robot; all we need is its <code>id</code>.  But what if we wanted to fetch a document by other attributes, like its <code>name</code>?</p>
<p>The answer is a <em>View</em>.</p>
<p>Without going too much into the topic, a view is a special list of imaginary documents, each derived (via a function you provide) from a single real document.  They're imaginary in that they're actually derived documents—again, from <em><strong>a single real</strong> document</em>.</p>
<p>So, in theory, a view could safely disappear and there would be no real data loss.  But don't worry: Views don't usually disappear. In fact, they're automatically generated and efficiently updated whenever any document changes.</p>
<p>So, with views you can have Cloudant efficiently prepare answers to questions like the following:</p>
<ul>
<li>Give me all of the <code>robot</code>s with a <code>capability</code> of <code>type</code>, <code>transform-into-a-vehicle</code>.</li>
<li>How many <code>robot</code>s have the capability, <code>transform-into-a-vehicle</code>?</li>
<li>Give me all of the <code>robot</code>s with the <code>name</code>, <code>Optimus</code>.</li>
<li>Give me all of the <code>robot</code>s with no capabilities.</li>
</ul>
<p>For more info on views, see <a href="https://wiki.apache.org/couchdb/Introduction_to_CouchDB_views?action=show&amp;redirect=Views">this wiki page</a>.</p>
<h2 id="queries">Queries</h2>
<p>Views are great, but defining them is kind of difficult.  Also, views spawn documents that map a key (e.g. the id of an instance of a type of capability) to a value (e.g. the robot that the capability instance is in).  These get very complicated if you need to ask questions that involve more than one field of a document.</p>
<p>For example, <em>Give me the robots that have a name <code>Optimus</code> and a <code>capability</code> with <code>type</code>, <code>transform-into-a-transport-truck</code></em> is a difficult question to answer with views.  Also, a view would need to be created for each variation on this type of question ahead of time:  Changes to the names or number fields involved in the question will result in changes to the view code.</p>
<p>For situations where it's impractical to create a view ahead of time, Cloudant provides a feature called Cloudant Query.  Similar to preparing a view, preparing a query involves giving Cloudant a function that generates zero or more <code>key:value</code> mappings for each document.  The important difference between a query and a view is that these <code>key:value</code> mappings are automatically fed into a query engine which incrementally generates enough data to answer more complex questions.</p>
<p>Do note, though, that like views, each of these mappings derives from <em>a single document</em>.</p>
<p>For more info on Cloudant Query, see <a href="https://cloudant.com/blog/introducing-cloudant-query">this post</a>.</p>
<h2 id="bigdocsaresimpleandreadsarefast">Big Docs are Simple and Reads are FAST!</h2>
<p>So there you have it: The big-doc extreme of document based data stores like Cloudant.</p>
<p>In summary:</p>
<ul>
<li>Big documents are a great starting point.</li>
<li>They're simple.</li>
<li>If your domain entities are strictly hierarchical, big documents are a natural fit.</li>
<li>Techniques like update-handlers can simplify updates.</li>
<li>Because of the way conflicts work, all reads are always consistent:  You'll never read a doc half way through an operation.</li>
<li>Reads pertaining to a primary entity will be extremely fast because they'll always require a single fetch.</li>
</ul>
<h2 id="bigdocsarehardtokeepdry">Big Docs Are Hard to Keep DRY</h2>
<p>In spite of all of those benefits, big documents aren't all sunshine and roses. Remember that document for that robot?  Let's make a few small tweaks to it and add a second robot:</p>
<pre><code class="language-language-javascript">// Added a new capability, speech, to Optimus
// Added a new robot, Bumblebee, who can transform but
//   cannot speak.

{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;some-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Optimus&quot;,
    &quot;description&quot;: &quot;A robot full of snazziness.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;,
    &quot;capability_instances&quot;: [
        {
            &quot;type&quot;: &quot;transform-into-a-vehicle&quot;,
            &quot;description&quot;: &quot;Make a signature sound and change into a vehicle&quot;,
            &quot;instance_id&quot;: &quot;some-universally-unique-id&quot;
        },
        {
            &quot;type&quot;: &quot;speech&quot;,
            &quot;description&quot;: &quot;Speak in a human language&quot;,
            &quot;instance_id&quot;: &quot;some-universally-unique-instance-id&quot;
        }
    ]
},
{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;some-other-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Bumblebee&quot;,
    &quot;description&quot;: &quot;A robot that can't talk.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;,
    &quot;capability_instances&quot;: [
        {
            &quot;type&quot;: &quot;transform-into-a-vehicle&quot;,
            &quot;description&quot;: &quot;Make a signature sound a change into a vehicle&quot;,
            &quot;instance_id&quot;: &quot;some-universally-unique-instance-id&quot;
        }
    ]
}
</code></pre>
<p>You may notice issue number one when documents are too big:  Repeated data.  I guess this isn't an issue in-and-of-itself—it's only a few bytes of repeated data—but what if we weren't sure what we wanted to store in a <code>capability_instance</code>.</p>
<p>For example, what if we wanted to add a link to a video demonstrating the type of capability?  We'd need to:</p>
<pre><code>- For each capability type:
  - For each robot that contains this capability type:
    - Fetch the robot.
    - Add a new &quot;video&quot; field to the capability 
      instance(s) of this type.
</code></pre>
<p>Further, what if we, for some odd reason, wanted to embed the video right into the database?  The space usage would be massive as the same video of a robot transforming into a vehicle would be embedded <strong>everywhere</strong>.</p>
<h2 id="bigdocsmeanmoreconflicts">Big Docs Mean More Conflicts</h2>
<p>Another issue with big documents is that the losers during &quot;concurrent&quot; edits need to do the conflict dance.  In-and-of-itself, this isn't an issue; in fact, it's how Cloudant and Couchdb were designed.  In practice, though, this conflict resolution flow ends up scaling poorly as the number of concurrent editors increases.</p>
<p>A concrete example:</p>
<blockquote>
<p>What if our bread and butter—the flow our users used 24/7 and 10,000 operations per minute—was trying out new types of <code>capability_instances</code> with a single <code>robot</code>.  The more concurrent edits to its list of <code>capability_instances</code>, the more conflicts would result, and the slower each edit would appear to be.</p>
</blockquote>
<p>A less obvious winkle:</p>
<blockquote>
<p>What if someone wanted to just change the description of a robot during this period of heavy load? They'd see conflicts as well, and may be wondering what's taking so long:  It's just the description.</p>
</blockquote>
<p>The answer: <em>little docs</em>.</p>
<h2 id="littledocshelpensuredryness">Little Docs Help Ensure DRY-ness</h2>
<p>Consider the following alternate list of documents:</p>
<pre><code class="language-language-javascript">// Details on each &quot;class of capabilities&quot; have been
//  moved to separate documents.
{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;some-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Optimus&quot;,
    &quot;description&quot;: &quot;A robot full of snazziness.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;,
    &quot;capability_instances&quot;: [
        {
            &quot;name&quot;: &quot;transform-into-a-vehicle&quot;,
            &quot;id&quot;: &quot;some-universally-unique-instance-id&quot;
        },
        {
            &quot;name&quot;: &quot;speech&quot;
        }
    ]
},
{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;some-other-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Bumblebee&quot;,
    &quot;description&quot;: &quot;A robot that can't talk.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;,
    &quot;capability_instances&quot;: [
        {
            &quot;name&quot;: &quot;speech&quot;,
            &quot;id&quot;: &quot;some-universally-unique-instance-id&quot;
        }
    ]
},
// Separate documents ---v
//
{
    &quot;type&quot;: &quot;capability&quot;,
    &quot;name&quot;: &quot;transform-info-a-vehicle&quot;,
    &quot;description&quot;: &quot;Make a signature sound a change into a vehicle&quot;
},
{
     &quot;type&quot;: &quot;capability&quot;,
     &quot;name&quot;: &quot;speech&quot;,
     &quot;description&quot;: &quot;Speak in a human language&quot;
}
</code></pre>
<p>Here, you'll notice that I created a few additional documents with a different <code>type</code> field.  There's actually nothing special about the word <code>type</code>.  It could be <code>sunshine_and_lollipops</code>.  Cloudant doesn't care what the field is called.</p>
<p>Whatever the field is named, it can come in handy for preparing queries on only documents that represent <code>capability</code>s, or while creating views where the view's imaginary documents spawn only from <code>robot</code> documents.</p>
<h2 id="littledocshelpreduceconflicts">Little Docs Help Reduce Conflicts</h2>
<p>I know.  The collection of docs above helps us not repeat ourselves, but what about our users' desires to constantly try out different combinations of capabilities on <code>Optimus</code>?</p>
<p>Consider the following:</p>
<pre><code class="language-language-javascript">// Capability instances have been entirely removed
//   from robots.  Now, adding a capability instance will never
//   result in a conflict.
{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;1-some-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Optimus&quot;,
    &quot;description&quot;: &quot;A robot full of snazziness.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;
},
{
    &quot;type&quot;: &quot;robot&quot;,
    &quot;id&quot;: &quot;2-some-other-universally-unique-id&quot;,
    &quot;name&quot;: &quot;Bumblebee&quot;,
    &quot;description&quot;: &quot;A robot that can't talk.&quot;,
    &quot;owner&quot;: &quot;cttttt@domain.com&quot;
},
{
    &quot;type&quot;: &quot;capability&quot;,
    &quot;name&quot;: &quot;transform-info-a-vehicle&quot;,
    &quot;description&quot;: &quot;Make a signature sound a change into a vehicle&quot;
},
{
     &quot;type&quot;: &quot;capability&quot;,
     &quot;name&quot;: &quot;speech&quot;,
     &quot;description&quot;: &quot;Speak in a human language&quot;
},
{
      &quot;type&quot;: &quot;capability_instance&quot;,
      &quot;name&quot;: &quot;speech&quot;,
      &quot;robot&quot;: &quot;1-some-other-universally-unique-id&quot;,
      &quot;id&quot;: &quot;some-universally-unique-instance-id&quot;
},
{
      &quot;type&quot;: &quot;capability_instance&quot;,
      &quot;name&quot;, &quot;transform-into-vehicle&quot;
      &quot;robot&quot;: &quot;1-some-other-universally-unique-id&quot;,
      &quot;id&quot;: &quot;some-universally-unique-instance-id&quot;
},
{
      &quot;type&quot;: &quot;capability_instance&quot;,
      &quot;name&quot;, &quot;transform-into-vehicle&quot;
      &quot;robot&quot;: &quot;2-some-other-universally-unique-id&quot;,
      &quot;id&quot;: &quot;some-universally-unique-instance-id&quot;
}
</code></pre>
<p>Here we have removed <code>capability_instance</code>s from our <code>robot</code>s entirely.  Now, adding a capability to a robot will always succeed with no conflict dance.</p>
<p>Neat huh?</p>
<h2 id="smalldocsbenefitsandcompromises">Small Docs: Benefits...and Compromises</h2>
<p>Remember how before, fetching a robot was a simple case of asking the DB for its document?</p>
<p>Now it involves the following steps:</p>
<pre><code>- Ask the DB for the robot's document and set it aside.
- Collect a list of capability instances referring to this robot (could be a view or query).
- Fetch those and incorporate them into the robot documents we fetched earlier.
- Collect a list of capabilities referred to by these capability instances.
- Fetch these and incorporate them into the result.
- Return the composed document.
- Hope nothing changed during all of that.
</code></pre>
<p>Also, in case you were wondering about views, remember what I kept repeating earlier:  <em>Each document in a view may only be derived from <strong>a single</strong> real document</em>.  Ditto for the mappings backing a query, which are each derived from <em><strong>a single</strong> real document</em>.</p>
<p>There is no way to have Cloudant round up the full view of a primary entity anymore.  It <em>necessarily requires</em> multiple fetches.</p>
<p>Another compromise is that with multiple updates come potential consistency problems.  We're using the same Cloudant as before here:  The data in a document will always be consistent and will never be <em>between operations</em>.  However, now we're composing data from multiple documents.  These could well be out of sync and we now have no way of knowing for sure.</p>
<h2 id="littledocsbigthoughts">Little Docs, Big Thoughts</h2>
<p>You may have expected this post to hold all of the answers to your questions on how to structure your data in Cloudant or Couchdb.  Hopefully, it's clear that there is really no right answer and that it depends on a few factors.</p>
<blockquote>
<p>Does your problem domain have a primary entity?  If it's highly relational, consider something else.</p>
</blockquote>
<p>If your data is hierarchical in nature, document based data stores like Cloudant make a lot of sense.  Introspection is easy—just read the documents.  As well, having the database prepare answers to questions about your entities is effortless with views and queries.  If, on the other hand, your problem domain has a bunch of primary entities that need to stay consistent with each other, you may want to consider another type of database.</p>
<blockquote>
<p>Lots of reads?  Not a lot of writes?  Stay big!</p>
</blockquote>
<p>If your data is accessed a lot and mutated relatively infrequently, it makes a lot of sense to stick with the initial one-document-per-primary-entity model, using views and queries to fetch slices of your data.  It may seem like this could not possibly be efficient, but trust me:  It's probably just fine.</p>
<p>An added benefit of this approach is guaranteed data consistency <em>for free</em>.  Because updates to a document are atomic, and because views and query data are updated automatically and efficiently, there are no opportunities for fetching data mid-operation.  You may occasionally fetch old data, but it'll never be inconsistent.</p>
<blockquote>
<p>Going small always adds complexity and always slows down reads.</p>
</blockquote>
<p>It may seem like a great idea to go small from the start.  Heck, this is the only thing you can do in an RDBS, but going small carries a cost:</p>
<ul>
<li>Forming a primary entity requires multiple fetches.  There's no such thing as a <code>JOIN</code> in a document based data store, so round trips are required.</li>
<li>Multiple fetches means the possibility of data inconsistency.  The only (sort of) atomic write operation in Cloudant is an insert or update of a document (with autonomy enforced through conflicts).  This guarantee doesn't exist when updating multiple docs that compose an entity.</li>
</ul>
<blockquote>
<p>Large amounts of repeated data? Pull out <em>only that data</em>.</p>
</blockquote>
<p>Because of these costs, small documents should only be used where absolutely required to mitigate specific capacity or performance issues.  For example, if large pieces of data are repeated across documents, consider replacing that data with a reference to a <em>typed document</em> and update your existing views/queries to emit for only specific types of documents.  Fetching primary entities (<code>Robot</code>s above) will be a bit harder, but the added complexity will be justified.</p>
<blockquote>
<p>Lots of writes to a portion of a doc will slow down writes to <strong>any part</strong> of the <strong>entire doc</strong>!</p>
</blockquote>
<p>Another reason to evict a portion of a big document into a series of little documents is to distribute load.  Recall that only one update can be made to a document at once (with concurrent editors seeing a costly conflict).  Where you know there will be contention on a certain structure within a document, consider exploding the structure into individual documents, each referring to the original doc.  This way, inserts into this structure will always be conflict-free.  As above, though, this will make it just that little bit harder to fetch documents.  It will also make it harder to avoid data consistency issues.</p>
<p>Well, that's that.  Hope this helps!</p>
<p>— chris</p>
]]></content:encoded></item><item><title><![CDATA[Promises 101]]></title><description><![CDATA[<p>The other day I was reading up on <a href="http://koajs.com/">a new Node.js backend framework</a> and was intrigued as it was based on a new Javascript language feature: Generators.  Knowing nothing about this bleeding edge Javascript tech, I set out on a bit of an adventure.  It turns out that generators</p>]]></description><link>https://blog.twentytwotabs.com/promises-101/</link><guid isPermaLink="false">5b6681e94bb73600011c5bf0</guid><category><![CDATA[nodejs]]></category><category><![CDATA[promises]]></category><category><![CDATA[Getting Started]]></category><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Tue, 05 Jan 2016 04:50:00 GMT</pubDate><media:content url="https://blog.twentytwotabs.com/content/images/2018/08/nodejs-new-pantone-black.png" medium="image"/><content:encoded><![CDATA[<img src="https://blog.twentytwotabs.com/content/images/2018/08/nodejs-new-pantone-black.png" alt="Promises 101"><p>The other day I was reading up on <a href="http://koajs.com/">a new Node.js backend framework</a> and was intrigued as it was based on a new Javascript language feature: Generators.  Knowing nothing about this bleeding edge Javascript tech, I set out on a bit of an adventure.  It turns out that generators are part of a yellow brick road that the TC39 hopes will lead developers away from zigzagging pyramid-like programs to code that more closely resembles the plain old synchronous variety almost all of us are used to.</p>
<p>But where does this journey begin?  Consider the following slow function...and just a note that all of these code examples should run in NodeJS <code>v5.4.1</code> with no special flags or modules.</p>
<pre><code class="language-javascript">/*
 * A slow routine.
 */
function slowlyIncrement(i, cb) {
        setTimeout(function() {
                cb(null, i + 1);
        }, 1000);
}
</code></pre>
<p>This function follows a pretty well defined pattern where the last argument is a piece of code <em>pushed in</em> by the caller.  Internally, the function does some work and calls the provided callback, <code>cb</code>, sending it an optional error and a result.</p>
<p>Pretty simple.</p>
<p>But what if you need to run several slow routines in sequence?</p>
<pre><code class="language-javascript">slowlyIncrement(0, function(err, i) {
        // TODO: handle errors
        slowlyIncrement(i, function (err, j) {
                // TODO: handle errors
                slowlyIncrement(j, function (err, k) {
                        // TODO: handle errors
                        slowlyIncrement(k, function (err, x) {
                                // TODO: handle errors
                                slowlyIncrement(x, function (err, y) {
                                        // TODO: handle errors
                                        slowlyIncrement(y, function (err, z) {
                                                // TODO: handle errors
                                                console.log(z); // prints 6
                                        });
                                });
                        });
                });
        });
});
</code></pre>
<p>The main issue—the one that pops right out like one of those 3D stereograms from a few decades ago—is what I like to call <em>the bad kind of horizontal scaling</em>.  Another more subtle issue is how errors are handled.  Because potential errors are passed as arguments to each callback, there's no way to defer error handling:  Every callback must have error handling code.  Both of these issues may be jarring to someone more used to synchronous code and exceptions.</p>
<h2 id="arrowfunctions">Arrow functions</h2>
<p>One neat feature introduced in ES6/ES2015 is a shorthand for anonymous functions.  It's pretty simple.</p>
<p>In compatible runtimes, this:</p>
<pre><code class="language-javascript">function (i) {
        console.log(i);
}
</code></pre>
<p>...is equivalent to this:</p>
<pre><code class="language-javascript">(i) =&gt; {
        console.log(i);
}
</code></pre>
<p>So, our crazy zigzagging code can be reduced to this:</p>
<pre><code class="language-javascript">slowlyIncrement(0, (err, i) =&gt; {
        slowlyIncrement(i, (err, j) =&gt; {
                slowlyIncrement(j, (err, k) =&gt; {
                        slowlyIncrement(k, (err, x) =&gt; {
                                slowlyIncrement(x, (err, y) =&gt; {
                                        slowlyIncrement(y, (err, z) =&gt; {
                                                console.log(z); // prints 6
                                        });
                                });
                        });
                });
        });
});
</code></pre>
<h2 id="promises">Promises</h2>
<p>Although arrow functions are a great way to reduce a little repetition, they don't really address the structural issues with our code.  Enter <em>promises</em>.</p>
<p>As I mentioned above, when a slow function is provided a callback, the programmer is <em>pushing</em> an entity (a piece of code) into that function.  At least to me, this concept was pretty confusing when I started working with Javascript.  I was used to functions—slow or fast—<code>return</code>-ing values which got <em>pulled out</em> via a function call.</p>
<p><em>Promises</em> are an attempt at turning this unintuitive convention back on its head.  Don't spend too much time studying it too closely, but consider the following new and improved slow function:</p>
<pre><code class="language-javascript">function slowlyIncrement (i) {
        return new Promise((resolve, reject) =&gt; {
                setTimeout(() {
                        resolve(i + 1);
                }, 1000);
        });
}
</code></pre>
<p>One immediate improvement here is that we're no longer expecting callers to push code to our function.  Instead, callers pass in arguments and <em>pull out</em> an object that represents the eventual result.</p>
<p>For example:</p>
<pre><code class="language-javascript">var result = slowlyIncrement(0);
</code></pre>
<p>Now, the trick is coaxing the actual value out of this object.  This is accomplished via it's only documented method, <code>then</code>:</p>
<pre><code class="language-javascript">var result = slowlyIncrement(0);
result.then((i) =&gt; {
        console.log(i); // prints 1
});
</code></pre>
<p>The idea is that the callback provided to <code>then</code> will be called when the value underlying the promise is known or <em>resolved</em>.</p>
<p>A neat bit of trivia is that because the only standard method of a promise is <code>then</code>, a promise is usually described as a <em>thenable</em> object.  But more on that later.</p>
<h2 id="morethenmeetstheeye">More <code>then</code> meets the eye</h2>
<p><code>then</code> has a few more tricks up it's sleeve; actually, two pretty simple properties:</p>
<ol>
<li><code>then</code> always returns a promise.  Let's call this promise <code>thenResult</code>.</li>
<li><code>thenResult</code> resolves to whatever the callback provided to <code>then</code> returns.  Specifically:</li>
<li>If the callback provided to <code>then</code> returns a run of the mill value, <code>thenResult</code> will immediately be resolved with that value.</li>
<li>If the callback provided to <code>then</code> returns a <em>thenable</em>, <code>thenResult</code> will be resolved whenever (and with whatever) that <em>thenable</em> is resolved with.</li>
</ol>
<p>Here's an example of a run of the mill value being propagated:</p>
<pre><code class="language-javascript">var result = slowlyIncrement(0);
result
.then((i) =&gt; {
        return i + &quot;'s the result&quot;;
})
.then((i) =&gt; {
        console.log(i);  // prints &quot;1's the result&quot;
});
</code></pre>
<p>Here's an example of a promise being chained:</p>
<pre><code class="language-javascript">var result = slowlyIncrement(0);
result
.then((i) =&gt; {
        return slowlyIncrement(i); // a promise is returned here
}) // this then() returns a promise which resolves to whatever value the promise above does
.then((i) =&gt; {
        return i + &quot;'s the result&quot;;
})
.then((i) =&gt; {
        console.log(i); // prints &quot;2's the result&quot;
});
</code></pre>
<h2 id="scalingvertically">Scaling vertically</h2>
<p>Now we have all the knowledge required to tackle that nesting in our original code snippet.  You remember...the code that performed five increments in sequence and spanned three screen widths.</p>
<p>Here's the Cole's Notes version:</p>
<pre><code class="language-javascript">slowlyIncrement(0)
.then((i) =&gt; {
  slowlyIncrement(i);
})
.then((j) =&gt; {
  slowlyIncrement(j);
})
.then((k) =&gt; {
  slowlyIncrement(k);
})
.then((x) =&gt; {
  slowlyIncrement(x);
})
.then((y) =&gt; {
  console.log(y);
})
</code></pre>
<p>...which can be reduced even further as:</p>
<pre><code class="language-javascript">// slowlyIncrement just so happens to accept one param
// ditto for console.log.
slowlyIncrement(0)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(console.log)
</code></pre>
<h2 id="ohyeaherrorhandling">Oh yeah.  Error handling.</h2>
<p>Although I didn't get into it earlier, there was something I didn't mention about the <code>then</code> method of a promise.  It actually takes two callbacks.</p>
<p>The first one is called whenever the value underlying the promise is known (or <em>resolves</em>).  The second one is called whenever an error occurs while arriving at a value.  When this happens, it's up to the promise returning function to raise an error by <em>rejecting</em> the promise.</p>
<p>Here's an example of a more complete <code>slowlyIncrement</code> which rejects where the provided value is not a number:</p>
<pre><code class="language-javascript">function slowlyIncrement(i) {
        return new Promise(function (resolve, reject) {
                if (Number.isNaN(Number(i))) {
                        reject(new Error(i + &quot;: Not a number&quot;));
                } else {
                        setTimeout(() =&gt; {
                                resolve(i+1);
                        }, 1000);
                }
        });
}
</code></pre>
<p>Here's an example usage with proper error handling:</p>
<pre><code class="language-javascript">// Here, no error occurs.
slowlyIncrement(0)
.then(
  console.log, // prints 1
  (e) =&gt; {
    console.log(e.stack);
  }
);
</code></pre>
<p>Here's an example usage where an error actually occurs:</p>
<pre><code class="language-javascript">// Here, an error occurs because &quot;abcde&quot; isn't a number
slowlyIncrement(&quot;abcde&quot;)
.then(
  console.log,
  (e) =&gt; {
    console.log(e.stack);  // displays a stack trace
  }
);
</code></pre>
<h2 id="theweakestlink">The Weakest Link</h2>
<p>Just like resolved values propagate down the promise chain, so too do errors.  Here, errors will still be caught, even if we decide not to handle them for each and every call to <code>then</code>:</p>
<pre><code class="language-javascript">slowlyIncrement(&quot;abcde&quot;)
.then(slowlyIncrement)
.then(
  console.log,
  (e) =&gt; {
    console.log(e.stack);
  }
);
</code></pre>
<p>This is looking much more familiar, eh?  Let's close the loop.  With promises, that grimy, nested, error prone mess all the way at the top becomes this:</p>
<pre><code class="language-javascript">function slowlyIncrement(i) {
        return new Promise(function (resolve, reject) {
                if (Number.isNaN(Number(i))) {
                        reject(new Error(i + &quot;: Not a number&quot;));
                } else {
                        setTimeout(() =&gt; {
                                resolve(i+1);
                        }, 1000);
                }
        });
}

slowlyIncrement(0)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(slowlyIncrement)
.then(
  console.log,
  (e) =&gt; {
    console.log(e.stack);
  }
)
</code></pre>
<p>Now I know what you're thinking:</p>
<p><strong>The Good</strong></p>
<ul>
<li>We can cut our use of the keyword <code>function</code> down considerably with <em>arrow functions</em>.</li>
<li>With promises, we no longer need to <em>push code</em> to slow functions.  We simply call those functions and fetch a deferred result in the form of a <em>promise</em>.</li>
<li>Because promises may be chained, we no longer have to contend with very wide source files or hard to match parentheses.</li>
<li>Promises allow error handling code to be consolidated, instead of <em>needing to <strong>always</strong> be</em> spread out throughout an asynchronous call chain.</li>
</ul>
<p><strong>The Bad</strong></p>
<ul>
<li>We're still <em>pushing code to fetch a value</em>, but to the <code>then</code> method of a promise.  This still feels a bit unnatural.</li>
<li>A promise is a type that controls the execution path of a program.  Shouldn't this be part of the language's syntax? This way, the compiler will be privy to the desired control flow and may be able to optimize or at least confirm syntax.</li>
<li>The implementation of the slow running function is still kind of unnatural.  This is probably related to the point above about the lack of language support for any of this.</li>
</ul>
<p>In my next post, I'll get into the part of the road closer to the Emerald City—that place where async code can look as clean and familiar as the synchronous code of old.</p>
<p>This leg of the journey is definitely under construction, with some pretty crazy twists and turns.  The exciting part, however, is how much of this plumbing is being brought behind the curtain of the Javascript language where it belongs.</p>
<p>Until next time,</p>
<p>— chris</p>
]]></content:encoded></item><item><title><![CDATA[How to Timeout a Connection in Node According to Stack Overflow]]></title><description><![CDATA[<p>Firstly, I just want to make it clear that this post is in no way a slight towards Stack Overflow.  Without this fantastic collection of carefully curated questions and answers, we would all be lost.  This is just a story about an imaginary software developer maintaining imaginary legacy code.</p>
<p>Last</p>]]></description><link>https://blog.twentytwotabs.com/how-to-timeout-a-connection-in-node/</link><guid isPermaLink="false">5b667e424bb73600011c5bee</guid><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Wed, 25 Nov 2015 04:34:00 GMT</pubDate><content:encoded><![CDATA[<p>Firstly, I just want to make it clear that this post is in no way a slight towards Stack Overflow.  Without this fantastic collection of carefully curated questions and answers, we would all be lost.  This is just a story about an imaginary software developer maintaining imaginary legacy code.</p>
<p>Last week, this imaginary dev was on a bit of an adventure. Instead of writing brand new code or making calm one-or-two line edits to fix bugs in well written Javascript, he was helping maintain a bit of a crow's nest.</p>
<p>Let's just call this micro-service <em>the Gardiner expressway</em>.</p>
<h2 id="oncemoreuntothebreachdearfriends">Once more unto the breach, dear friends...</h2>
<p>What I learned from this program—which I coincidentally named after a notoriously unmaintainable downtown Toronto thoroughfare —is a brand new way to timeout an outgoing HTTP connection.</p>
<p>Here's a module that demonstrates this new approach.  I'll throw this into <code>get.js</code>:</p>
<pre><code class="language-language-javascript">/* eslint-env node */
/* eslint no-use-before-define: 0 */
/* eslint no-multi-spaces: 0 */

&quot;use strict&quot;;

var request = require(&quot;request&quot;);

module.exports = function (url, timeout, callback) {
    var isTimedOut;

    setTimeout(function () {
        isTimedOut = true;
	callback(new Error(&quot;Connection timed out&quot;));
	return;
    }, timeout);

    request.get(url, function (err, res, body) {
        if (isTimedOut) {
            return;
        }

        callback(err, body);
        return;
    });
};
</code></pre>
<p>And here's a quick driver program that takes the URL and timeout off of the command line, runs our modularized function to fetch the URL, and displays the number of characters in the response body:</p>
<pre><code class="language-language-javascript">/* eslint-env node */
/* eslint no-use-before-define: 0 */
/* eslint no-multi-spaces: 0 */
/* eslint no-shadow: 0 */
/* eslint no-process-exit: 2 */

&quot;use strict&quot;;

var get = require(&quot;./get&quot;);

if (process.argv.length !== 4) {
    console.error(
        &quot;Usage: %s URL MILLISECONDS\n&quot; +
        &quot;Fetch URL and display the length of the fetched body.&quot; +
        &quot;Timeout after the provided number of ms.&quot;
    );
    process.exit(1);
}

var url = process.argv[2],
    timeout = process.argv[3]
;

get(url, timeout, function (err, body) {
    if (err) {
        printError(err);
	return;
    }

    console.log(&quot;%s characters received&quot;, body.toString().length);
});

function printError(err) {
    if (err instanceof Error) {
        console.error(err.stack);
    } else {
        console.log(err.toString());
    }
}
</code></pre>
<p>So, for example, to fetch the url, <code>https://www.google.com</code> and give up after one second:</p>
<pre><code class="language-language-shell">$ npm install request
...
...
$ node index https://www.google.com 1000
55429 chars received
</code></pre>
<p>And, as you'd expect, if we bump the timeout down low enough, we'll see errors:</p>
<pre><code class="language-language-shell">$ node index https://www.google.com 900
55452 chars received
$ node index https://www.google.com 800
55460 chars received
$ node index https://www.google.com 700
55471 characters received
$ node index https://www.google.com 600
55415 chars received
$ node index https://www.google.com 500
Error: Connection timed out
    at null._onTimeout (/Users/ctaylorr/proj/hownottotimeout/get.js:14:11)
    at Timer.listOnTimeout (timers.js:110:15)
</code></pre>
<h2 id="itworksletsshipitbtwwhattheactualeff">It works! Let's ship it! BTW, what the actual eff?!?!?!</h2>
<p>But wait a second.  This isn't the way this is done in other runtimes:</p>
<ol>
<li>
<p>We're starting our <em>timeout countdown</em> far before the connection is attempted.  This is measuring the latency of the destination server all right; but also:</p>
<ul>
<li>DNS lookup time.</li>
<li>Socket creation time.</li>
<li>The amount of time it takes to run code in <code>request(...)</code> prior to creating a connection.</li>
</ul>
</li>
<li>
<p>The <code>setTimeout</code> code is tying up the event loop.  This can be demonstrated by running <code>node index https://www.google.com 10000</code>.</p>
</li>
<li>
<p>Even when we do timeout, the connection is still active.  Don't believe me?  Run <code>node index https://www.google.com:12345 500</code>.</p>
<p>Node will not terminate since the connection is still tying up the event loop.  If this code were run in a web-app, we would be leaking sockets under heavy load.  One of the goals of implementing timeouts is to save resources.</p>
<p>We better look into this.</p>
</li>
</ol>
<p>There are probably other issues, but what we've found so far are enough to consider investigating alternatives to this approach.</p>
<p>Let's try to address them one-by-one:</p>
<h2 id="butfirstletscheckthedocs">But first, let's check the docs...</h2>
<p>According to the docs for the <a href="https://github.com/request/request#requestoptions-callback">request module</a>, implementing a connection timeout requires an additional option:</p>
<pre><code class="language-language-javascript">
var request = require(&quot;request&quot;);

request.get({
    url: &quot;https://www.google.com&quot;,
    timeout: 1000  // &lt;---- THAT'S IT. AN OPTION.
}, function (err, res, body) {
    // handle errors

    // process results
});
</code></pre>
<h2 id="itwasanoptionallalong">It was an option all along</h2>
<p>Yup.  And the resulting code is so simple, you don't even need a separate module.  Just run <code>request()</code> with the extra option.</p>
<h2 id="tldrknowyourtools">tl;dr: Know your tools.</h2>
<p>The moral of this story is that when using new tech (an API, a framework, ...anything) always set aside some time to take a look at the documentation.  No need to commit the entire thing to memory, but use this as the first stop when a new requirement pops up.  If nothing pops out, consider composing concepts from the docs.</p>
<p>If that still doesn't work, only then consider the clever techniques from sites like <a href="https://www.stackoverflow">Stack Overflow</a>.</p>
<p>Hope this helps,</p>
<p>— chris</p>
]]></content:encoded></item><item><title><![CDATA[Twenty two tabs at a time]]></title><description><![CDATA[The more tabs, the better in my book]]></description><link>https://blog.twentytwotabs.com/twenty-two-tabs-at-a-time/</link><guid isPermaLink="false">5b4b666f110a060001a1fcf9</guid><dc:creator><![CDATA[Chris Taylor]]></dc:creator><pubDate>Thu, 01 Oct 2015 15:21:00 GMT</pubDate><content:encoded><![CDATA[<p>I've always held the firm belief that being a software developer is more of a learning experience than anything else.  Granted, there will always be those super-hero moments when I live in an editor, write reams of code, hit <em>build</em>, run my unit tests and it all works out.  But a lot of days end up something like this...</p>
<p><img src="https://blog.twentytwotabs.com/content/images/2018/08/twenty_two_tabs-1.png" alt="twenty_two_tabs-1"></p>
<p>...and to me at least, that's a-okay.  It just means that by the time I packed it in for the day, I learned something.</p>
]]></content:encoded></item></channel></rss>