<?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 Kash on Medium]]></title>
        <description><![CDATA[Stories by Kash on Medium]]></description>
        <link>https://medium.com/@kash.?source=rss-a5f8bb046c3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mN6INC3OY_aOdZHSEMgLRg.jpeg</url>
            <title>Stories by Kash on Medium</title>
            <link>https://medium.com/@kash.?source=rss-a5f8bb046c3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:37:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kash./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[The magic of Array iteration in Javascript]]></title>
            <link>https://medium.com/@kash./the-magic-of-array-iteration-in-javascript-eae52d49c5e2?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae52d49c5e2</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 08:43:24 GMT</pubDate>
            <atom:updated>2018-09-02T08:43:24.114Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A cheat sheet to understanding it all</em></p><p>Javascript provides us with the Array composite type so we can easily create dynamically sized and loosely defined lists in our application. Understanding how to effectively iterate arrays is essential to letting us properly manage and utilise them. The question is do you know all the methods available?</p><p>We will use the following array list throughout our examples:</p><pre>const eArray = [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]</pre><h3>Non-prototypal methods:</h3><h4>Simple for loop:</h4><p>The bane of many a functional programmer, we can use the trusty for loop to iterate Arrays.</p><ul><li>Reassigns and increments the value of i from our initially set index (0) while its value is less than the array length. Uses i to refer to each position of the array.</li><li>Current iteration can be skipped with <em>continue</em></li><li>Can be short circuited with <em>break</em> or <em>return</em></li></ul><pre>for (let i = 0; i &lt; eArray.length; i++){<br>   if (eArray[i]===&quot;val1&quot;) continue;<br>   console.log(eArray[i]);<br>   if (eArray[i]===&quot;val3) break;<br>}</pre><pre>/* <br>val2<br>val3<br>*/</pre><h4>for…in iteration:</h4><p>We can also use the object iteration syntax on Arrays.</p><ul><li>Assigns the value of pos to the current iteration location from 0 index</li><li>Can use <em>const</em> as long as no reassignment is made to <em>pos</em> in curly brace</li><li>Current iteration can be skipped with <em>continue</em></li><li>Can be short circuited with <em>break</em> or <em>return</em></li></ul><pre>for (const pos in eArray){<br>   console.log(eArray[pos])<br>}</pre><pre>/*<br>val1<br>val2<br>val3<br>val4<br>*/</pre><h4>for…of iteration:</h4><p>for…of directly assigns the value of the array instead of a positional index as with for…in</p><ul><li>Assigns the value of <em>item</em> to value of current index location</li><li>Can use <em>const</em> as long as no reassignment is made to item in curly brace</li><li>Current iteration can be skipped with <em>continue</em></li><li>Can be short circuited with <em>break</em> or <em>return</em></li><li>Syntax directly addresses value so no access to index of iteration</li></ul><pre>for (const item of eArray){<br>   console.log(item)<br>}</pre><pre>/*<br>val1<br>val2<br>val3<br>val4<br>*/</pre><h3>Prototypal Methods</h3><p>For reference we can get a list of accessible prototypes using:</p><pre>console.log(Object.getPrototypeOf([]))</pre><p>Lets go through them according to use case:</p><h4>I want to iterate everything unconditionally and perform a task on each item</h4><ul><li>Use the <em>forEach</em> prototype</li><li>We pass in a function which is executed per item. Our function does not need to return a value</li><li>The end result of for…each returns undefined: you are interested in performing logic in your function, not a return value</li><li><em>return</em> can be used to skip iteration like <em>continue</em> can in standard loops</li><li>Cannot be short circuited, must iterate to end</li></ul><pre>console.log(<br>   eArray.forEach((item, i, array)=&gt;{<br>      if (item===&quot;val2&quot;) return;<br>      console.log(item, i, array);<br>   })<br>)</pre><pre>/*<br>val1 0 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val3 2 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val4 3 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>undefined<br>*/</pre><h4>I want to see if a condition exists at least once in the array</h4><ul><li>Use <em>includes</em> for primitives or <em>some</em> prototype for composites</li><li><em>includes</em> takes a primitive param</li><li>For <em>some</em> we pass in a function which enforces our criteria and:<br> — Returns true if the criteria is found<br> — Returns false if the criteria is not found</li><li><em>some</em> can be short circuited. The end result is a boolean:<br> — <em>true</em> if criteria is found. Short circuit happens on first <em>true </em>(ie. some elements meet our criteria)<br> — <em>false</em> if criteria is not found. This will iterate all values (ie. we are sure no values contain our criteria)</li></ul><pre>// Using some prototype<br>console.log(<br>   eArray.some((item, i, array)=&gt;{<br>      console.log(item, i, array)<br>      return item === &quot;val2&quot;<br>   })<br>)</pre><pre>/*<br>val1 0 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val2 1 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>true<br>*/</pre><pre>// Using includes<br>console.log(<br>   eArray.includes(&quot;val2&quot;)<br>)<br>/*<br>true<br>*/</pre><h4>I want to check a condition exists in every item of the array</h4><ul><li>Use the <em>every</em> prototype</li><li>We pass in a function which enforces our criteria and:<br> — Returns true if the criteria is found<br> — Returns false if the criteria is not found</li><li>Can be short circuited and end result is a boolean:<br> — <em>true</em> if criteria is met. This will iterate all values (ie. we are sure every value meets our criteria)<br> — <em>false</em> if criteria is not found. Short circuit happens on first false (ie. we are sure not every value meets our criteria)</li></ul><pre>console.log(<br>   eArray.every((item, i, array)=&gt;{<br>      console.log(item, i, array)<br>      return item === &quot;val1&quot;<br>   })<br>)</pre><pre>/*<br>val1 0 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val2 1 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>false<br>*/</pre><h4>I want to find the location of a value in the array</h4><ul><li>If you have an array of primitives you can use <em>indexOf</em> otherwise use <em>findIndex</em>. If you’re in search of the last value of a primitive, use <em>lastIndexOf </em>which reverses the direction of the lookup from left to right to right to left</li><li>Returns -1 if the value is not found, otherwise will return the location of the item as a 0 indexed integer</li><li>Will short circuit on the first found item</li></ul><pre>// Using findIndex for non-primitives<br>console.log(<br>   eArray.findIndex((item, i, array)=&gt;{<br>      console.log(item, i, array)<br>      return item === &quot;val2&quot;<br>   })<br>)</pre><pre>/*<br>val1 0 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val2 1 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>1<br>*/</pre><pre>// Using indexOf for primitives<br>console.log(<br>   [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val2&quot;].indexOf(&quot;val2&quot;)<br>)</pre><pre>/*<br>1<br>*/</pre><pre>// Using indexOf for primitives<br>console.log(<br>   [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val2&quot;].lastIndexOf(&quot;val2&quot;)<br>)</pre><pre>/*<br>3<br>*/</pre><h4>I want a transformed array to fulfill another purpose</h4><ul><li>Use the <em>map</em> prototype</li><li>We pass in a function which will take the current value and return the target structure we want to transform into</li><li>The end result is an identically sized array consisting of the newly transformed objects</li><li>If you need to mutate size consider using filter before/after a map transformation (depending on which is most efficient in your case)</li></ul><pre>console.log(<br>   eArray.map((item, i, array)=&gt;{<br>      console.log(item, i, array)<br>      return item === &quot;val2&quot; || item === &quot;val4&quot;<br>   })<br>)</pre><pre>/*<br>val1 0 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val2 1 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val3 2 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>val4 3 [&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;val4&quot;]<br>[false, true, false, true]<br>*/</pre><h3>I want to accumulate my array into a single value</h3><ul><li>Use the <em>reduce</em> function (for left to right iteration) or <em>reduceRight</em> (for right to left iteration)</li><li>We pass in a function which takes an accumulator and the current value</li><li>All items are iterated allowing us to “accumulate” into our accumulator</li><li>The end result is our accumulator</li></ul><pre>console.log(<br>   eArray.reduce((accumulator, item)=&gt;{<br>      console.log(accumulator, item)<br>      return accumulator += item<br>   })<br>)</pre><pre>/*<br>val1 val2<br>val1val2 val3<br>val1val2val3 val4</pre><pre>val1val2val3val4<br>*/</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae52d49c5e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disintermediating “bad” websites with Electron… or enhancing the good ones]]></title>
            <link>https://medium.com/@kash./disintermediating-bad-websites-with-electron-or-enhancing-the-good-ones-a1fdfd5f3b87?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1fdfd5f3b87</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Sun, 26 Aug 2018 06:34:58 GMT</pubDate>
            <atom:updated>2018-08-26T06:34:58.968Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting honey from the hive</h4><p><em>Browsers are a beautiful thing: they’ve proven themselves over years to be a highly reliable and interopable way to provide consumers with enriched digital experiences. Sometimes though, experiences aren’t as “enriched” as we would prefer them to be. Fortunately, for these occasions we can crack them open and take out the good bits and leave the bad behind.</em></p><h3>The Problem</h3><p>Picture this: you’ve found a website that serves some content you need but it turns out the site is full of ads. Not the good kind of ads, those would be okay, these are the terrible kind that put you a click away from downloading malware.</p><p>Maybe that’s just fair exchange, maybe its not. Ethics aside, from an academic perspective, lets look at how we can best disintermediate this site and restructure it to easily access the content. This is dissimilar from what a typical adblocker does in that:</p><ol><li>This site has multiple scripts to detect adblockers and enforces IP bans if breaches are detected</li><li>This site serves adds that are not readily detected by general adblocker configs and any custom configs expire quickly due to source rotations</li><li>The site has custom captchas we would like to circumvent</li><li>The sites flow is non-ideal, it requires too much clicking and interaction, we want a lazier solution</li></ol><p>Please note that I cant provide any specific source code here which will undermine my target site. I will however post generic code which describes the important aspects of the solution.</p><h3>Introducing Electron</h3><p>To describe it in a few words for the uninitiated, Electron is a custom chromium browser with Node JS plumbing.</p><p>Where most browsers are focused on sandboxing and resource control to prevent malicious vectors and limit system exposure, Electron is built with deep system integration in mind.</p><p>Browser limitations like CORS, user initiated gesture restrictions and the inability to reference the filesystem in a non-sandboxed fashion no longer bind developers in Electron environments. Further, because of access to the NodeJS runtime, developers can invoke C code and system API’s to write some fairly hardcore and deeply integrated expereinces.</p><p>Most importantly, this is all whilst maintain the benefit of an interchangeable UI written in HTML and the interopability in NodeJS and Chromium. In fact the code for my application invokes seamlessly across Mac OS, Windows and Linux with negligible effort.</p><p>The best part is there’s a good chance you’ve already been using electron apps! You can review a more complete list <a href="https://electronjs.org/apps">here</a> but VS Code, Atom, Skype and Slack are a few that spring to mind.</p><p>On a side note there is a false perception that electron apps are as secure as their website equivalents. Keep in mind that, whilst electron itself is secure, developers have the same privileges as a standard executable for the host platform.</p><h3>Understanding The High Level Architecture</h3><p>Our application will consist of multiple windows which are all centrally managed by a process in the background which holds references to them (lets call it “main process”).</p><ul><li>Each window will have its own render process decoupled from the main process</li><li>All windows will talk back back and forth to the main process using IPC via generic handlers we create</li><li>Windows will not be aware of each other: communication between windows will be through the main process</li></ul><p>In a diagram this looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jBKrqMpvSHAnjqWTUbiwZA.png" /></figure><ul><li>Window 1: Primary window the user interacts with. Is persistently available to orchestrate app functions and is the “go-to” screen for the user</li><li>Window 2: A scraper window with temporary instantiation, predominately used to spoof initial sessions against security SDK’s which execute in the browser</li><li>Window 3: A popout window used to display contextual content</li></ul><h3>Getting Started</h3><p>I’m going to assume we already have an updated version of Node installed. Lets get started with a vanilla node project:</p><pre>mkdir my_electron_project<br>cd my_electron_project</pre><pre>npm init<br># Use whichever parameters suit you best</pre><pre># Install electron as a developer dependency<br>npm install electron --save-dev</pre><pre># Create a source folder<br>mkdir src src/site src/lib<br>touch src/index.js src/site/app.html src/site/app.js</pre><p>Resulting in the below project structure:</p><pre>my_electron_project<br>├── node_modules<br>├── package.json<br>├── package-lock.json<br>└── src<br>    ├── index.js<br>    ├── lib<br>    └── site<br>        ├── app.html<br>        └── app.js</pre><p>In the above project schema:</p><ul><li>All code written by us is placed in src. Later we’ll use a dist folder to place our compiled files into</li><li>The site folder is where we will place our render assets such as CSS, HTML and supporting JS files</li><li>The lib folder is where we will place our node.js supporting libraries</li></ul><h3>index.js</h3><p>Index.js will act as the entry point for our app, we will use it to instantiate electron and maintain its state. We’ll also let it orchestrate the initialisation activities of our app.</p><p>At a high level, in this case it will be responsible for:</p><ul><li>Initialising our main render with a loading screen</li><li>Initialising the target website and ensuring we are able to scrape out cloud flare cookies that are then persisted across the application</li><li>Providing our application with a generic IPC handler to manage communications between the render and node services</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336b25c4ef8cc88074b8350c70611e65/href">https://medium.com/media/336b25c4ef8cc88074b8350c70611e65/href</a></iframe><h3>app.js</h3><p>Contains our main frontend render logic. What you put in here will depend on your use case, but there are two important components I want to discuss:</p><ul><li>IPC handler: We’ll create another IPC handler to send instructions to our main process. It will submit the exact lib, method, args and even its own callback path to the main process. It will be entirely in charge of the its own call orchestration and drive the main processes libs to its contextual requirements</li><li>Generic callback singleton: Will honor replies from the main process when it has fulfilled its task instructions and take action accordingly</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22fadacfc3bf0033f9ca206f445e58fd/href">https://medium.com/media/22fadacfc3bf0033f9ca206f445e58fd/href</a></iframe><h3>window.js</h3><p>This file is referenced in index.js and is fairly self explanatory. Its just tracks windows and provides a wrapper over the default electron instantiation to standardise our approach to menu handling etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f633361b2590b0939367d4911619f0/href">https://medium.com/media/19f633361b2590b0939367d4911619f0/href</a></iframe><h3>requests.js</h3><p>This file is quite vanilla so I won’t post an extract of it here. At a high level, it uses a combination of Cheerio and Request to scrape content from our target website and process it into an interpretable format for the render.</p><p>Cheerio is more efficient here than JQuery in the render since it does not construct a DOM. Request gives us full flexibility of Node JS’s requests and async handling instead of a limited browser capability. Whilst you can now call Node.JS libs from the render this can get conceptually messy and encumber your frontend.</p><h3>A few useful tid bits</h3><ul><li>You can instantiate your app using this command from terminal (make sure not to use a terminal that is electron based since that will cause issues):</li></ul><pre>./node_modules/electron/dist/electron src/</pre><ul><li>You can publish your app using something like electron-publisher</li></ul><pre># From your project CWD<br>npm install electron-publisher -g<br>npm install electron-prebuilt-compile --save-dev<br>mkdir dist<br>#Build windows and linux binaries<br>electron-packager . generic-app --overwrite --platform=linux --platform=win32 --arch=x64 --prune=true --out=dist --asar=true</pre><h3>Summary</h3><p>Using the concepts above you’re in a good position to get started with disintermediating your first website for academic purposes.</p><p>Of course most sites may add additional layers of complexity in the form of captchas, however most captchas are resolvable by importing a couple of libs. Where the captcha is custom you an implement a user source solution where successful responses can be relayed to a server and then propagated to other users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1fdfd5f3b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple and Elegant: Basics of Queue Management In NodeJS]]></title>
            <link>https://medium.com/@kash./simple-and-elegant-basics-of-queue-management-in-nodejs-cc4427c89ee2?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc4427c89ee2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Thu, 16 Aug 2018 12:02:38 GMT</pubDate>
            <atom:updated>2018-08-16T12:05:53.227Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Solving the mysteries of task manipulation in async</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*X_S5Ley-yHyYqCawE-xeEA.png" /></figure><p>In my previous articles we discussed Nodes asynchronous nature and how this, in practice, can cause us some coding challenges. Today we’ll look at tackling a general concept that comes hand in hand with asynchronicity: creating queues and processors.</p><p>As a heads up, its highly recommended that you have a functional understanding of async/await and promises before proceeding with the rest of this article. If you would like to understand these topics in more detail, feel free to read through my previous articles and post questions there.</p><h3>The Scenario</h3><p>Lets think up a scenario to work with first. Think of building a web scraper that needs to aggregate multiple segments of information from a list of source URL’s. All your HTTP requests in node by default are asynchronous in nature (to the ire of many a new developer) so this problem fits the description nicely.</p><h3>Simple Iteration</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F20v2xnppvp%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F20v2xnppvp%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F20v2xnppvp%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2b49379208f5cbf35a6029187138938/href">https://medium.com/media/d2b49379208f5cbf35a6029187138938/href</a></iframe><p>In the example above we spawn a request for each URL in our “requests” array via a simple iterator construct. We then await all our requests completing before proceeding further. The problem with this is that the map method (as well as all other iterators pre ES2018) don’t await asynchronous operations: they will simply push all requests onto the event queue regardless of their status or completion. This is demonstrated in the high request concurrency: effectively we’re making all our requests at the same time.</p><p>While this might not seem like a big deal in the above example, if we think in terms of big data manipulation where we’re iterating thousand of links, this is not sustainable for anybody:</p><ol><li>We’re impolitely saturating the target server with high request concurrency that will likely impair its performance</li><li>The target server is likely to have some sort of CDN or internal protection that easily distinguishes our utility as a scraper</li><li>Our own server is depleting resources quicker than this task necessitates. If we do not manage queues appropriately, we may exhaust ephemeral ports, file handlers or even heap space. This is especially important on multi-tenanted environments where ulimits are strictly enforced.</li></ol><p>So what can we do to optimise this?</p><h3>Introducing the queue</h3><p>Our first lesson is to learn to queue our tasks. This might sound fancy, but in Javascript the construct of a queue can simply be dialed down to a regular array filled with functions containing their execution scope as below:</p><pre>const tasks = requests.map(request =&gt; () =&gt; window.util.request(request));</pre><pre>// Notice that we return a function in the above code.<br>// We do not trigger the request unlike our original code below:<br>// const tasks = requests.map(request =&gt; window.util.request(request));</pre><pre>// Prior to ES6 this would have looked like<br>// var tasks = requests.map(function(request){<br>//  return function(){<br>//    window.util.request(request)<br>//  }<br>//})</pre><p>The map method allows us to construct a new array from our current one. At every position of the new array, we return a function containing our target operation. This function, when invoked, will execute the target operation (our request). Its essential to understand that unlike in the previous example, no requests have been made by the map method (because we have instantiated functions in our new array, not invoked them).</p><p>Importantly, the invocation of our function is agnostic: all scopes are already included lexically rather than passed as an argument. This is our queue: a single dimensional list of things to do which can be invoked in a uniform and accessible way.</p><h3>Writing a processor</h3><p>So we just discussed that our queue is special in that it has done exactly nothing so far. But we obviously want to do something, so what next?</p><p>The next piece is writing a processor for the queue. Where the queue is a list of instructions, a processor is a function which takes a list of instructions as an input and executes them in a way we control. In the first example we will write a simple processor which waits for each request to complete before sending the next (simulates “synchronous” behavior):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2F57j45kz9p%3Fautoresize%3D1%26module%3D%252Fsrc%252Findex.js&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F57j45kz9p%3Fautoresize%3D1%26module%3D%252Fsrc%252Findex.js&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/58c745d38426c7343e8c11401e6ad7f2/href">https://medium.com/media/58c745d38426c7343e8c11401e6ad7f2/href</a></iframe><p>In the above, the makeSync function recursively and sequentially operates on the queue until there are no items left. It then returns all results accumulated to the user to iterate on. In many if not most cases, this level of simple queue control will suffice. There are however occasions where simple queuing won’t suffice. For those we can take this concept and build upon it further.</p><h3>Supporting concurrent execution and callbacks</h3><p>Adding support for variable concurrency (ie. we instruct that the queue can process x requests at once but then wait for these to complete) provides us with the ability to optimise for situations where the roundtrip expenditure needs to be balanced with our concurrency concerns.</p><p>Another problem to address is queue size. Queueing responses within makeSync before returning the entire processed output is memory expensive and does not allow us to effectively manage streams. One way to mitigate this is to build callback support into makeSync so outputs can be processed without aggregation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F010xj1yvyw&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F010xj1yvyw&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F010xj1yvyw%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a392b5950d6c428da67a6abd5561c8c/href">https://medium.com/media/2a392b5950d6c428da67a6abd5561c8c/href</a></iframe><h3>Fixing the glaring issues</h3><p>Our processor lacks sophistication and elegance, there are still some glaring issues that will evidently prevent if from effectively scaling:</p><ol><li>The concurrency handling requires all tasks to complete before proceeding. If we have a concurrency of 100, we should not be waiting for 49 requests to complete when we have already processed 51. Instead we should be proactively topping up our queue.</li><li>Our processor is unconditionally cumulative: we can invoke it as many times as we want throughout multiple instances of our code. Thinking back to our scraper, if our goal was to write responses to disk, imbalances in throughput between TCP and disk can rapidly cause instructions to bank up within the queue. If our queue cannot let the application know it needs to wait before using it, we will keep pushing onto it and eventually crash.</li></ol><p>In order to resolve these problems we’ll look at two things:</p><ol><li>Adding a new item to the queue from the backlog every time a request is completed</li><li>Providing a permission method we can call across our code. This method will return a promise. The promises resolution is bound to event emission from our queue. The event that we emit will in turn be dependent on the queue dropping to a certain length. This way, we can conditionally close the tap in our application depending on how filled the runtime is.</li></ol><p>This is implemented below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fm5pn3jy1ky&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fm5pn3jy1ky&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fm5pn3jy1ky%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe2b0a4739077d76e7d0c422756a6dd/href">https://medium.com/media/cfe2b0a4739077d76e7d0c422756a6dd/href</a></iframe><h3>The end result</h3><p>So in the above example we’ve neatly solved the issues we discussed earlier. With further tweaks and optimizations upon the same methodology we’ve just covered, I was able to remove all instances of application crashes in one of my major, highly intensive projects. In addition, application throughput and box performance were significantly increased:</p><ul><li>Load average reduce from 26 to 18 on my 24 core box. CPU utilization increased from 60% to almost 100%</li><li>Throughput increased by ~3x</li><li>Disk IO became more regular and consistent (ie. there was less IO volatility and saturation) resulting in greater system stability</li><li>File handlers which were exhausted previously were now in sufficient supply for the application to scale further</li></ul><p>*Please keep in mind that the above code for brevity omits exception handling for multiple scenarios. Use discretion in implementing it anywhere that isn’t academic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc4427c89ee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Laptop Coolers Actually Do Anything?]]></title>
            <link>https://medium.com/@kash./do-laptop-coolers-actually-do-anything-7c2813b51b51?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2813b51b51</guid>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 15:11:07 GMT</pubDate>
            <atom:updated>2018-06-09T15:11:07.859Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>There are an abundance of laptop coolers on the market, but are they necessary and do they really do anything?</blockquote><p>Have you ever wondered why gaming laptops are chunky and noisy whereas ultrabooks are slim and quiet but terrible for gaming and compute intensive productivity tasks? The answer is fairly simple: heat. Faster silicon within the same generation generally consumes more power and in turn generates more heat. More heat means more size since we have to worry about dissipating it.</p><p>In recent years, more efficient fabrication and transistor designs have led to vast increases in computational efficiency, however our ability to dissipate heat has remained much the same as it has always been. While we’re at the point where a desktop part can be chucked into a laptop, cooling hasn’t changed: use a thermally conductive metal (such as a copper heat pipe), surround it with a fin array for surface area, then blow some ambient air on the surface to cool it down.</p><p>The above method has significant draw backs: the more heat we need to dissipate, the more metal and surface area we need. If we want portable devices, the weight and size of the metal we can use is limited and so is our cooling ability. Further, the smaller the fans used, the greater the RPM and static pressure required to move air across the fins which in turn results in louder operating noise.</p><p>But given the above, can we use a larger laptop cooler to blow more air into the laptop and enhance the efficiency of the stock cooling system? As a spoiler, yes we can. Read more if you would like to learn how and what kind of difference we can make.</p><p>Before we get into benchmarks and evidence, lets consider a few technicalities and terminologies that will be relevant in this article:</p><ul><li>Clock speed: The amount of cycles a processor can make in a second. A higher clock generally means you can do more Instructions Per Second (which is a good thing)</li><li>Throttling: A mechanism provided by manufacturers to reduce the power consumption of a component to reduce the thermal emissions. This keeps components from overheating and degrading at the expense of performance. Throttling is evident from reductions in clock speed</li></ul><h3>Lets take a look at the hardware we’ll be using:</h3><h4>Aero 15x</h4><p>One of the first laptops to use NVIDIA’s Max Q chips which aim to maximise efficiency. We’ll be running this with a GTX 1070 and an i7 8750H.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*W0UtyZu91u5phTiFROnfdA.png" /></figure><h4>Coolermaster Notepal U2 Plus</h4><p>A flexible laptop cooler with 2 adjustable fans which can be variably located across the grill. It also doubles as a neat carry case to provide the laptop with additional protection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KTc1PzfaAboSDaBosG8lw.png" /></figure><h3>The Setup</h3><p>The Aero 15x has two fans, one at the top left and another at the right. Between them and shared by both components, are two heat pipes. The fans intake from the base of the laptop and exhausts from the rear. The middle has a slight exhaust due to the positive pressure in the chassis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZqpdSyspWaJCMoW.png" /><figcaption>Image courtesy of hexus.net</figcaption></figure><p>In light of this design we will logically:</p><ol><li>Load both CPU and GPU components to maximise the thermal dissipation requirements across the shared heat pipe</li><li>Direct the U2’s fans to blow air in the centre vent to cool the heat pipes directly (this is the best surface area that is accessible)</li><li>Open the laptop hinge completely so air routes under the it for an optimised air exhaust</li></ol><p>Note that, in general, it is best not to position fans over the top of each other since this can create inconsistent pressure and turbulence which impairs efficiencies of both fans.</p><h3>Benchmarks and results</h3><p>All benchmarks were conducted with the power plugged in and power targets in windows set to their respective maximum performance modes. The CPU was lightly undervolted by 150mv. The battery started at 100% charge to ensure heat generated from it was consistent across all benchmarks.</p><p>Each differing benchmark had a 5 minute break in between to allow results to stabilise for the new operating conditions. Synthetic benchmarks were not used, feel free to post a comment below if you would like to know why. The ambient temperature remained 18 degrees centigrade throughout the test.</p><p>Fan speeds were statically set to a level depending on the test. This is necessary since many manufacturers use linear (or sometimes exponential) grading in their fan profiles to variably cool components. Because we’re interested in determining the impact of the U2, this is an undesirable variable and so has been kept constant.</p><p>Three stances were considered for the testing:</p><ol><li>Directly on the table (TABLE): Aero placed on a flat table. This includes any manufacturer standoffs to slightly raise the laptop for air intake</li><li>Elevated on the U2 (RAISED): Aero placed in the U2 but with the U2&#39;s fans off. This adds more air for the laptop fans to intake (and to a lesser extent a passive sink effect) so we can differentiate between giving the Aero more air to breathe and the U2’s fans efficiency</li><li>Elevated on the U2 with fans active (ACTIVE): Raised on the U2 with the U2’s fans operating in their default state</li></ol><h4>DOTA</h4><p>Is a great candidate for inducing a moderate GPU and CPU load. Replay ID 3937609487 was used with the English spectator view starting from 20 minutes to ensure consistent load between runs. The fan speed was set to 40% which generated a tolerable but audible amount of noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*scmzsEDl2VgFBoutAPn8hQ.png" /></figure><p>The test indicates that using U2 versus the manufacturer default table stance removes all incidences of thermal throttling with a 6% increase in GPU clock and an 18% increase in CPU clock. Meanwhile temperatures dropped as much as 13 degrees or 15%.</p><h4>ASSASSINS CREED ORIGINS</h4><p>Is a great candidate for invoking high GPU and CPU load. The internal benchmark was used multiple times to ensure consistent load. Fans were set to 100%. Whilst this is not exactly tolerable noise limit, it is a representative test of whether we can enhance the laptops maximum cooling efficiency. This is particularly relevant when overclocking, operating in warmer clients or dealing with devices that are unable to cool themselves efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*j-6m_KziyvAU4m3YDmfOAA.png" /></figure><p>Similar to the DOTA benchmarks, the U2 yielded solid results even with the laptop at its maximum cooling profile. The GPU clock significantly increased and all incidence of thermal throttling were resolved. Temperatures were also down across the board.</p><h4>BONUS: ASSASSINS CREED ORIGINS (40% FAN PROFILE)</h4><p>Lets see whether its practical to relax the laptops fan profile and expect the U2 to do the majority of the cooling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*sn-o3MkRPhn1JrPapHreXg.png" /></figure><p>Whilst the U2 was able to remove incidences of thermal throttling on the GPU, it was not able to do so for the CPU. Despite this, there were significant increases in GPU and CPU clock leading to an increase in performance of 6%. The temperature improvement was not as pronounced as in previous tests, this is because the laptop still remained close to throttling.</p><h3>Conclusion</h3><p>Using a laptop cooler can yield significant results, however this is circumstantial and specific to the laptops implementation. Keep an eye out for laptops that have ventilation shafts open that are not already being utilised as an intake shaft.</p><p>Keep in mind that the outcomes of a laptop cooler vary. If you aren’t thermal throttling you will only see a reduction in operating temperatures or fan noise. In situations where your laptop is being thermal throttled due to inadequate cooling a laptop cooler can be of great benefit to performance.</p><h3>What else can we do?</h3><p>Fortunately, the journey doesn’t have to end here. We can modify the U2’s fans to increase static pressure, CFM and the amount of air pumped against the heat pipes. Also, usually of greater benefit, is changing the Thermal Interface Material (TIM) to something more conductive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2813b51b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes your server tick and what stops it form ticking]]></title>
            <link>https://medium.com/@kash./what-makes-your-server-tick-and-what-stops-it-form-ticking-7012900f05ae?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7012900f05ae</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Fri, 18 May 2018 04:13:17 GMT</pubDate>
            <atom:updated>2018-05-18T04:13:17.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding how a server ticks: CPU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BifyIaT3atJ4gf99OPrDpA.png" /><figcaption>htop, a great utility for investigating how your CPU is doing</figcaption></figure><p>I’ve spent a lot of time breaking things. In a sad twist of fate this is often not deliberate but sometimes it can be a happy moment: it means that you’re pushing things to the breaking point. Whether that’s from poorly optimised code or a legitimate use case is a discussion for another day.</p><p>Most recently I’ve provisioned a high throughput ingestion server: in the past day a single server running a single OS has written over 70TB of data to its 2TB data volume. That’s an aggregate write of 810MB continuously over a span of an entire day for non-sequential files. Its been a fun journey and as expected ALOT of things broke along the way.</p><p>Lets take a look at one of the key factors and take a brief look at its underlying hardware.</p><h3><strong>CPU:</strong></h3><h4>What is it?</h4><p>Everyone knows about this one to varying degrees, most likely at least that the Central Processing Unit (CPU) is the brain of the computer.</p><p>It processes machine code (abstracted away in most modern languages), the outputs of which determine the action of the hosting machine and your code.</p><p>Processing is done via densely packed transistors which are either on or off (depending on whether they have current flowing through them) leading to the binary nature of computing.</p><p>Without wanting to jump into <em>too </em>much technical hardware details on how it works in this article, its important to be mindful of the following factors:</p><ul><li>CPU Cores: How many simultaneous processing units there are on the CPU you are using. The more cores, the more parallel instructions can be computed and generally the greater the performance. <br>In modern terms, technologies like Hyper Threading (HT) translate a single physical core to two virtual cores for the host OS. Most tasks do not use all the modules on a CPU core simultaneously. Using this logic, even though a Hyper Thread does not physically exist, the CPU can apportion selective tasks from it to remaining capacity on the physical core to more optimally utilise it. This performance is subjective and will in practice not scale as performantly as another physical core being added.</li><li>CPU Clock speed: Generally the higher the clock speed within the same CPU series, the more Instructions Per Second for you to churn through. This is particularly relevant for single threaded applications.</li><li>CPU Cache: Tiered pools of low sized memory integrated with the CPU which can be accessed and iterated on significantly faster than RAM. t</li><li>CPU Architecture: Determines the low level instruction sets this CPU will perform. Generally if you’re talking server compute you’ll be using x64. Often compilers/virtual machines will abstract this layer from you.</li><li>Interrupts: Think event driven hardware, the CPU does not waste time polling hardware for instructions, rather hardware interrupts the CPU by sending signals directly to it which it then processes with immediacy</li></ul><p>Most cloud platforms will generally aggregate the above into a more digestible figure based on their own workload benchmarks and hypervisor performance. As an example Amazon Web Services (AWS) aggregates CPU series into tiered groups (example c4 and m4) and expresses an Elastic Compute Unit (ECU) figure which is a proxy for performance.</p><h4>When do things go wrong?</h4><p>Lets assume we haven’t provisioned our own hardware so we don’t have to worry about hardware concerns such as operating temperatures and thermal throttling.</p><p>In this case we’re predominately worried about 2 things, either giving the CPU too many instructions that it can’t process quickly enough causing latency or alternatively, letting instructions bank up.</p><p>Lets talk about CPU usage which describes our first case:</p><h4>CPU Usage</h4><p>CPU Usage in simplistic terms is the amount of time the CPU spends active processing. The higher the usage the more underlying CPU resources you consume.</p><p>Logically, there are two stats we can derive from the above, active time and idle time. Usage is then simply calculated by:</p><pre>CPU usage = active time/(active time + idle time)</pre><p>So at an aggregate we now understand how much our CPU is being utilised, but that’s not necessarily useful. Even at a high level, we would generally like to see the summation of CPU usage, that is which generally identifiable components are utilising our CPU.</p><p>To that effect we have the following which can be measured as either time or usage:</p><ul><li>Idle: Free resources on the CPU</li><li>Guest: Consumption caused by guest operating systems.</li><li>Guest (nice): Identical to guest with the exception that these tasks are low priority and will be interrupted by other processes.</li><li>Steal: Consumption that is caused from other tenants in a virtualised environment you don’t have control over</li><li>Iowait: Consumption caused by waiting for interrupts</li><li>Irq: Consumption caused by servicing interrupts</li><li>Softirq: Consumption from servicing software interrupts</li><li>System: Consumption from system processes such as kernel processing</li><li>Nice: Consumption in user mode with low priority tasks that can be interrupted by other processes</li><li>User: Consumption from users on the Host OS, typically your server application</li></ul><p>So which of the above should I care about? When is CPU usage too high?</p><p>Well unfortunately there is no easy answer, but the following general rules might help:</p><ul><li>Idle is an inversely related to consumption, generally consumption metrics are better to focus on, although idle can give you a nice indicative measure of resource availability.</li><li>Guest is particularly relevant if you run your own server cluster including hypervisors and VM’s. If you’re in the cloud you generally wont see it.</li><li>Nice measures processes that don&#39;t demand CPU: they use it when available. Generally this isn’t too troublesome from a usage perspective and doesn’t significantly compromise your apps performance</li><li>Steal is the amount of time you spend waiting for the physical CPU under the hypervisor to become available. Generally excessive steal figures indicate noisy neighbours (multiple tenants are contesting the same hardware) or quota based enforcement on the hypervisor. Differentiating between the two can often be troublesome and requires pattern analysis often across varying hardware</li><li>Iowait is generally due to latency in addressing hardware with varying levels of latency and efficiency. A key example is disk drives which can have instructions bank very quickly. Iowait can allude to ineffective queuing mechanisms. As an example, refining the queues I use to write and process files to be parallelised but evenly paced greatly reduced my Iowait and overhead to the kernel</li><li>I typically haven’t seen high irq resource consumption except when my hardware was malfunctioning. It would be worth investigating connected peripherals or drivers if your machine is physically provisioned or in the cloud checking whether irq could be consistently reproduced across multiple images and machines</li><li>System usage varies depending on how hard you push the kernel for the host OS. Generally, in microservice applications that have application processing, most overhead should be at the user level with your application as opposed to the kernel. We’ll discuss kernel and OS based limitations in a separate article</li></ul><p>As a general rule its best not to see a CPU saturated in latency sensitive scenarios. On its own though, moderately high CPU usage does not necessarily indicate an issue: we provision infrastructure to use it after all not for it to sit idle. To determine whether things are unhealthy we need to consider a complimentary metric: load average.</p><h4>Load Average</h4><p>Load average in simple terms represents the banked up instructions that are left to process. In essence, where CPU usage is the amount of time we’re spending getting our work done in, lets say a second, load average is the pile of papers on our desk that we still need to get done.</p><p>Load average is generally measured in 3 intervals: 1 minute, 5 minutes and 15 minutes. Longer periods are aggregated and more stable however in realtime scenarios shorter periods are more relevant. The greater the difference between the longer and shorter periods, the greater the volatility in the servers workload.</p><p>A load average of 1 indicates that the CPU core has banked up processing requirements of exactly what it is processing. In an ideal world, we would have 1 load average and 100% CPU usage meaning we’re utilising our infrastructure to the fullest extent: we’re doing work all the time and work is arriving at the same speed as we’re getting it done.</p><p>In reality though, latency sensitive workloads need to have a buffer for unexpected events such as variability in work load type. Even if our load profile remained consistent and so did our underlying application, hardware variances such as latency in an ECC check or a disk operation taking longer to complete can rapidly bank up instructions in this state.</p><h4>So when should I be worried?</h4><p>Whilst its subjective and varies from circumstance to circumstance, at peak load for real time scenarios, I prefer a load average of 0.7*count of cores and a CPU load of 70%.</p><p>Keep in mind though there are other important things to consider as part of this equation:</p><ul><li>Is my application multithreaded? Single threaded applications will only ever reach 100% on a single CPU core at saturation. This will not reflect in the load average nor CPU usage if you&#39;re running on multiple cores but will stop your application from scaling</li><li>What is the nature of the load? If you’re running in a JVM as an example you should be concerned if your load is originating from Garbage Collection: even if the host OS stats are okay it does not mean your application is running well</li><li>Are there inconsistencies? If your CPU usage is low but load average is high, you might want to evaluate why your infrastructure is not being appropriately utilised, right size it and use the savings to additionally provision the underperforming resource</li></ul><h4>How do I know whether I should be worried?</h4><p>There are many ways to instrument your server, we’ll save this as a discussion for the second part of this article though.</p><p>As always leave a comment with any feedback or thoughts you might have</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7012900f05ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Awaiting your Async]]></title>
            <link>https://medium.com/@kash./awaiting-your-async-6c821b7a8d2f?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c821b7a8d2f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 02:00:24 GMT</pubDate>
            <atom:updated>2018-08-13T11:45:42.550Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Just like controlling the ebb and flow of water, except in Javascript and without the water</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxO0bhRFu546Ffvipq8Vzg.png" /><figcaption>Lets investigate writing ‘stops’ in our Javascript code for correct execution sequencing</figcaption></figure><p>In my previous two blog posts we covered the basics of asynchronicity and how we can deal with it effectively with Promises. Following on from this is the async and await functionality that was introduced as part of the Node 8.</p><p>If you haven’t yet read my two previous articles and are not familiar with asynchronous paradigms in javascript or how to write a Promise, I would highly recommend starting there to get a base level of understanding before reading this article.</p><p>Async and await let us write and execute our code in a sequential order despite it being asynchronous. This lets us easily interpret the sequencing of code execution unlike callbacks which, depending on the developer, may loop around in irregular patterns and scopes.</p><p>Arguably the above issues were resolved with Promises (get it <strong><em>resolved</em></strong>) however, Promises tend to be syntax heavy and can become messy depending on how a developer chooses to nest and error handle them. The limitation of only being able to pass a single argument to the next chain instruction can also be a slight annoyance as well as scoping variables locally.</p><p>So what are async and await?</p><ul><li>Async: A declaration we attach to functions to denote that they will return a promise and use the await operator. Without an async declaration, functions using await will error at compile. Because a promise is returned by default, you will not have to manually initialize a promise yourself unless there is a specific need for you to do so.</li><li>Await: Instructs that we should wait until a returned Promise is resolved before proceeding to the next operation. Contrary to synchronous functions, this does not freeze the thread rather, it just prevents execution of the next operation within the current context. Think of it as being similar .then in a typical promise. Interestingly, we don’t necessarily have to await a promise: we can await a synchronous task. This is particularly useful when mixing synchronous and asynchronous functions.</li></ul><p>Combining the two usage scenarios above we can structure our code as follows:</p><ul><li>Adapt all our asynchronous callbacks to return Promises using constructs like the PromiseBridge or util.promisify() as discussed in my previous article. Any functions which already return a promise can be retrofitted with the async declaration and made to not explicitly return a promise since this is now inferred.</li><li>We declare an async function from where we wish to call our asynchronous operations. Within this function, any async calls can be affixed with an ‘await’ operator to ensure their returned Promise is resolved before proceeding. As this async function itself returns a promise, when all await operators are fulfilled, we can await it in other functions throughout our code.</li></ul><p>Lets take a look at how this will look in code, starting with seeing our declaration syntax for async in multiple forms:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkashs%2Fembed%2Fpreview%2FVXxWeX%3Fheight%3D600%26slug-hash%3DVXxWeX%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fkashs%2Fpen%2FVXxWeX&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1843655.VXxWeX.small.b4f8f510-45c1-46de-8384-7f2be7babb52.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/c278842eb590d2ab74a3dfda848981f8/href">https://medium.com/media/c278842eb590d2ab74a3dfda848981f8/href</a></iframe><p>Now lets see an example of async and await in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkashs%2Fembed%2Fpreview%2FwmjeGb%3Fheight%3D600%26slug-hash%3DwmjeGb%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fkashs%2Fpen%2FwmjeGb%3Feditors%3D1111&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1843655.wmjeGb.small.a9d08522-15d7-4e1d-bc88-a282f043fa6d.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d928b011894079d7940576f2a3f11339/href">https://medium.com/media/d928b011894079d7940576f2a3f11339/href</a></iframe><p>Another question would logically be, how do I error handle? In Promises I had catch, what is the magic mechanism by which I handle rejected Promises in this new uncharted territory? Fortunately its quite familiar: the try catch block.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkashs%2Fembed%2Fpreview%2FOvZgpG%3Fheight%3D600%26slug-hash%3DOvZgpG%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fkashs%2Fpen%2FOvZgpG&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1843655.OvZgpG.small.d3de072e-c1af-4dc8-86b2-3cf5abe8755e.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c3f945b4613a8678ec7a68dae78f05e/href">https://medium.com/media/8c3f945b4613a8678ec7a68dae78f05e/href</a></iframe><p>The ability to use the try catch paradigm is definitely a significant advantage. I have often seen error handling become unwieldy and downright weird from having to provision both promise catches and standard try catch blocks. In the past I have rectified this by creating an instantly resolvable “arbitrary promise” at the start of a flow allowing for all subsequent operations to be written in promise chains.</p><p>To me, async and await is a significant and much appreciated addition to the way we handle asynchronous code. It may not seem revolutionary at the start, but it definitely leans down the LOC count, syntax complexity as well as being immediately easier for new comers to understand. Its seamless integration with existing promise constructs makes it easy to leverage in any project without any trade offs in functionality or preference. Where I have the fortune of a Node 8 or greater runtime I use them extensively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c821b7a8d2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A riddle perhaps: Your drive is out of space, but its not out of space, what happened?]]></title>
            <link>https://medium.com/@kash./a-riddle-perhaps-your-drive-is-out-of-space-but-its-not-out-of-space-what-happened-c7c6eaadd099?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c6eaadd099</guid>
            <category><![CDATA[sysadmin]]></category>
            <category><![CDATA[zfs]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[filesystem]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Mon, 02 Apr 2018 09:48:17 GMT</pubDate>
            <atom:updated>2018-04-02T09:48:17.623Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Is the glass half empty or half full, or is it full but only half of water?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*u30RYEeAWkEo8ErY5u5J9Q.png" /><figcaption>The solution suprisingly is just as this glass of water</figcaption></figure><p>So you’ve been kitting out your rig with some <em>awesome </em>disk drives and its made it look like your last few paychecks never existed. No matter, a worthy trade: you’ll never run out of storage again! What a deal, all is looking good in your word!!! Or so you assumed…</p><p>One fruitful day, you get back from work and realise your applications have crashed, which is odd because of course, your applications never crash. After tracing through some logs (luckily you decided to put at least some last minute logging in) you realise its because there wasn’t enough space to write files to your disk. But how has this happened to our once glorious storage cluster? Lets investigate:</p><pre><strong>df -h</strong></pre><pre># df reports system disk space usage</pre><pre>Filesystem      Size  Used Avail Use% Mounted on<br>/dev/sda1        19G   11G  7.2G  59% /<br>/dev/sda6       778G  522G  217G  71% /application</pre><p>Our trusty friend df says there aren’t any issues with any of our mounts being at capacity (and we definitely weren’t writing a single 217GB file). Most importantly, df has <em>never</em> betrayed anyone, should we then blame our application? Well not so fast, its not just our apps, its also nginx, and nginx also never lies. Now we’re confused, so lets do the next best thing and ask the man:</p><pre><strong>man df</strong></pre><pre>-i, --inodes<br>       list inode information instead of block usage</pre><p>So the man has given us a promising lead: we probably should look at the amount of inodes on the file system which isn’t usually reported by df. Lets follow this promising lead:</p><pre><strong>df -i</strong></pre><pre>Filesystem      Inodes    IUsed   IFree IUse% Mounted on<br>/dev/sda1      1222992   348786  874206   29% /<br>/dev/sda6     51798016  5178096       0  100% /application</pre><p>So now we know the problem, 100% of our inodes are currently consumed: our glass isn’t yet full of water, but the air is getting in the way. So what are these vaporous and dastardly inodes? I’m glad you asked, lets take a quick crash course into file systems and the glory of the Operating System (OS), specifically Linux on this occasion (but don’t forget that Windows is just as fun!)</p><p>In PC architectures there are multiple kinds of devices, some provide low level access whilst others provide higher level access. Low level access generally means that the OS (which has been designated the task of interacting with hardware components), has direct interfacing to low level concerns the device may have.</p><p>Lets go off topic for a bit to explore this with an arbitrary and oversimplified example: a generic plug and play device like a webcam:</p><ul><li>We may have a point and shoot device that takes few and simple instructions from its driver such as take a picture and receive a picture. All other concerns to achieve these actions, such as aperture adjustment, shutter speed etc. are performed by the webcams own hardware. In such a case the OS is interfacing on a higher level with this device: its providing simplistic instructions and the device is doing the hard stuff via its own hardware</li><li>On the other hand we may have another device that is targeted at prosumers where control over hardware concerns like shutter speed and aperture is a feature. In this case the Original Equipment Manufacturer (OEM) would write a driver which allows the OS to send commands through an interface such as a Universal Serial Bus (USB) to modify the devices hardware. Such a device is lower level since the OS driver interfaces and provides specific hardware instructions to the peripheral device that are essential to its functioning and fulfilment of its purpose</li></ul><p>Jumping away from that example and back on track, disk drives provide low access: the operating system instructs on file schemes and locations, partitioning and write operations. The disk itself has no intrinsic understanding of the files it is writing at the hardware level: just which bits the OS wants to modify and in which sector.</p><p>There are some concerns the disk takes care of itself, specifically hardware concerns which the disk needs to fulfil to take operations from the OS. Back in the day when mechanical drives were all the rage (all our money went into an NVME SSD btw, because that’s where its at these days), the drive controlled its platter RPM as well as positioning of the mechanical head that realigned the magnetic material to change bits. Similarly, SSD’s have a controller on board which controls ECC checks, wearing as well as the write to transistors and other tasks.</p><p>Not sure why we discussed the above? Well now we understand that file system strategies are completely at the discretion of the OS! This is excellent news: since file system concerns are configurable by us within the OS we at least know we don’t need to scrap our expensive equipment! Phew!</p><p>So how does an ext4 file system work in tandem with our NVME SSD’s?</p><ul><li>A disk will present its lowest divisible unit to the OS, these are known as sectors. The sector size will vary depending on the disk</li><li>The OS clusters sectors intro addressable groups, these are generally referred to as blocks, the sizing of which can be adjusted when you create a partition</li><li>The lowest addressable unit is dictated by the block size you set. This means if you want to allocate a file of N+1 bytes (where N is your block size) you will consume 2 blocks. Newer file systems allow for block suballocation which is a separate topic.<br>(SPOILER: This is why the actual space used by a file may be different from the files actual size)</li><li>An inode bitmap block as well as inodes are created on the drive. The inode bitmap describes the inode range and an inode itself describes a singular file along with its metadata such as access permissions. A single file may require multiple inodes.</li><li>In ext4 long files can be described in ‘extents’ reducing the amount of inodes required to describe the file</li></ul><p>So because we’ve exhausted our inodes, we have no pointers to describe additional files and their metadata. This is the reason Linux is asserting that we have no free space left!</p><p>Lets move onto doing some calculations:</p><pre># Our amount of inodes (the amount of files we can describe as provided by df -i)<br>5,178,096</pre><pre># Our total drive capacity (as human readable, approx GB measurement provided by df -h)<br>778GB</pre><pre># Therefore the size of files we can describe on average to max out this volume<br>778GB/5,178,096 = ~150KB</pre><p>So Linux has assumed that our average file size would be about 150KB to fill this volume. The default amount of inodes is a delicate balancing act, since the OS has no way to estimate the amount of inodes a user may require ahead of time. My server is an extreme example since it handles many metadata and manifest files of low size but large quantity.</p><p>The more inodes we provision, the more addressable space is consumed compromising lower capacity, potentially costlier drives. Further, since the lowest unit an inode can address is a single file, it is redundant to provision more inodes than we can addressable blocks since this will exceed the amount of files we can describe anyway (at this point the volume will be marked as full with df -h as well).</p><p>Lets add this consideration to our calculations:</p><pre># Our sector size (as provided by blockdev --getss /dev/sda6)<br>512 bytes</pre><pre># Our sector count (as provided by blockdev --getsize /dev/sda6)<br>1,657,364,480</pre><pre># The maximum amount of inodes ext4 can map is limited to a 32 bit integer 2^32-1<br>4,294,967,295</pre><pre># If our minimal addressable unit is x then logically x would be the minimum of ext4’s max inode capacity and our sector count. To explain further: if an inode represents a single file and a single file can only even write to one sector, we are limited by either our sector size or a 32 bit integers upper bound.<br>1,657,364,480</pre><pre># Just as a reminder this is our currently provisioned inode figure:<br>5,178,096</pre><pre># Meaning we have room to grow our inodes in ext4 by about 320x, or more importantly, we can provision 320x more files than what we currently have at the moment</pre><pre># In actual fact, using a sector size of 512bytes, ext4 could provision an inode per sector for a resulting volume size of 4,294,967,295 * 512bytes:<br>2,199 GB</pre><p>So now that we know all this how can we move forward proceed?</p><ul><li>We can increase the amount of inodes and keep the ext4 file system: after all a 32 bit address is sufficient to address each sector individually for my 2TB FS (ignoring my smaller partition size since I will grow this later). This is even when blatantly ignoring extents and other ext4 optimisations.</li><li>Look at newer file system structures that aren’t limited by a 32 bit integer for address. One such file system is ZFS which does not use inodes. The nice thing is, since the OS is in charge of the file system not the disk, we can run multiple file systems in parallel on separate partitions and have a good play with ZFS.</li><li>We can also look at restructuring our applications. It is likely much better in most cases to store small metadata manifests in a database which writes out compressed content in larger contiguous files (SQLite comes to mind). This would also more efficiently utilise the underlying volumes since we write to sectors completely instead of partially. It also reminds me:</li></ul><blockquote>Wisdom is knowing that at the point you’re blaming the Linux kernel, you should probably be blaming yourself</blockquote><p>That said, due to intrinsic characteristics of the application I’m working on and most importantly the cool factor, I’m going to discard wisdom and pull out the big guns with a ZFS partition. Give it a few weeks and I may have a story on how this one pans out as well.</p><p>To my knowledge (which is based on alot of stack overflow links) there is no way to increase the amount of inodes on a pre-existing volume other than increasing the volumes capacity. This results in a corresponding linear and proportionate increase in inodes. If you have no capacity left, chances are you will need to repartition your data and create a new fs with mke2fs and the inode flags.</p><p>As always, if you’ve found anything inaccurate, have anything to add (I am but a humble padawan on this subject matter), or want to discuss feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c6eaadd099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Promise it’s easy: Node.js and Promises]]></title>
            <link>https://medium.com/@kash./i-promise-its-easy-node-js-and-promises-af6c1f9b6d0c?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6c1f9b6d0c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Sat, 24 Mar 2018 05:16:27 GMT</pubDate>
            <atom:updated>2018-08-18T07:36:36.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Promise it’s easy: Node.js and Promises</h3><blockquote>Node.js Promises are easier than you think, lets take a look at them together!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZO_sGuXNEtGRZRYu7SaDQ.png" /><figcaption>Don’t read into it too much yet, but this is what we have to look forward to in this article!</figcaption></figure><p>In my previous post we briefly introduced the concept of asynchronicity in node.js, the circumstances under which it happens and a few methods for dealing with it.</p><p>In this post I want to focus on one of those methods: the promise. Once we understand it thoroughly enough we can move onto the neat syntax we can layer on top: “async and await” in a separate post.</p><p>Before we start, its important to keep in mind that we’re talking about the native implementation of promises in ES6, your mileage may vary with polyfill libraries.</p><p>In every day terms a promise is a commitment to do something, this also holds true in Javascript. Lets take a look at the anatomy of a promise in code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F7100q6p8yq%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F7100q6p8yq%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F7100q6p8yq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aa6254489865cd9318441137e4c5f5b/href">https://medium.com/media/2aa6254489865cd9318441137e4c5f5b/href</a></iframe><p>Don’t panic over our second command executing before our first, for now lets infer a few things about the code:</p><ul><li>A promise is a class object and has a constructor. We can therefore identify promises via an ‘instanceof’ test and also assign them to a variable</li><li>The promise constructor takes a single callback function as an argument passing it two parameters: resolve and reject</li><li>A promise will trigger its function parameter as soon as its initialised</li><li>The thread proceeds outside of the promise if our task was asynchronous as it normally would</li></ul><p>What are resolve and reject though? When the promise calls our function it gives us these functions to use in the following way:</p><ul><li>When our async activity is completed successfully (ie. by our own definition we have fulfilled our commitment) we “resolve” our promise. The argument we pass is the success payload.</li><li>If our async activity fails (ie. by our own definition we have not fulfilled our commitment) we “reject” our promise. The argument we pass is the error payload.</li></ul><p>So far we know that a promise is a class and provides us with two arguments: one in case of failure and one in case of success. How does any of this help us when working with asynchronous code though? How can we fix the problem illustrated above?</p><p>To answer that we need to look at three of the prototypes attached to the promise. Read in simple English:</p><ul><li>then: after my promise has been fulfilled (resolved), do x operation for me</li><li>catch: after my promise has failed (been rejected), catch it and do operation y</li><li>finally: after my then and catch chain is fulfilled move onto operation z</li></ul><p>Now things are starting to make sense! Let’s fix our issue using what we’ve just learned:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fq90q724v8j%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fq90q724v8j%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fq90q724v8j%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/96822a54e4fa36299311234274ff1402/href">https://medium.com/media/96822a54e4fa36299311234274ff1402/href</a></iframe><p>That’s fixed our problem! Putting everything together:</p><ol><li>We instantiate a promise, passing through our asynchronous setTimeout function to its constructor</li><li>The asynchronous task executes</li><li>We assign the promise to the variable ourPromise. At any given time ourPromise contains the actual promise we’ve instantiated. In this case, the value of ourPromise is an unresolved promise</li><li>Our thread moves on to process other tasks</li><li>When our asynchronous setTimeout call completes, we resolve the promise</li><li>The chain of instructions we create via then, catch and finally methods executes in the order we defined them</li><li>When we finish the last then/catch/finally method the promise is marked as resolved</li></ol><p>Now lets get a bit more complicated and write up a few common but extremely important to understand scenarios:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F887ovk6p19%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F887ovk6p19%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F887ovk6p19%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e0b629c366a4313e62299d77130b45b/href">https://medium.com/media/9e0b629c366a4313e62299d77130b45b/href</a></iframe><p>Another thing to note is that there any many libraries, including node’s own native modules, which do not support promises. Libraries which use traditional callbacks can be easily adapted with minimal overhead by using something like the following:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fwnx3w78r25%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fwnx3w78r25%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fwnx3w78r25%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bfcdb900d0146d1bb4c60a9edcd0bad/href">https://medium.com/media/5bfcdb900d0146d1bb4c60a9edcd0bad/href</a></iframe><p>In the code above:</p><ol><li>We create a PromiseBridge function which itself takes a function for a parameter. We’ll put this in a utility script somewhere in our project to use elsewhere</li><li>We invoke the PromiseBridge passing a function that will call our asynchronous task. The function we pass through takes a single parameter for a callback. This callback is provided by the PromiseBridge function, we just define how we want to consume it</li><li>The promise bridge returns us a promise</li><li>When our asynchronous set timeout returns, it will consume the callback PromiseBridge creates with an error or data using the standard node callback convention (err/data)</li><li>Our callback function defined in the PromiseBridge translates the err/data into a resolve/reject action</li><li>Our code moves to any applicable then/catch/finally actions</li></ol><p>This function is generically applicable and can be applied across the board. It can also be modified to cater to non standard callbacks.</p><p><strong>UPDATE:</strong></p><p>When using NodeJS above Version 8, the util library implements a promisify method which converts functions with the standard (err, value) callback to return a promise.</p><p>This can be useful for internal node functions however may cause older libraries not using ES6 native classes to fail due to it binding this from its own context (at the time of writing the AWS SDK as an example). Adding it to the repertoire along side promiseBridge is useful.</p><pre>const util = require(&#39;util&#39;),<br>  fs = require(&#39;fs&#39;);<br>  <br>const stat = util.promisify(fs.stat); // Any time the stat function is invoked it will now return a promise</pre><pre>stat(&#39;.&#39;)<br>  .then(stats =&gt; console.log(stats))<br>  .catch(err =&gt; console.error(err))</pre><p>Finally, we’ll often need to manage multiple promises. The promise class provides a few methods for achieving this:</p><ul><li>All: Returns a promise that resolves when all sub promises are successfully resolved. A single failure will result in rejection with a singular item. Successes will return an array containing all results</li><li>Race: Returns a promise that resolve/rejects as soon as one sub promise is complete. Only data for the quickest resolving/rejecting promise is returned</li></ul><p>Both methods take an array of promises as their parameter. Their usage is demonstrated below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F346vz331q&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F346vz331q&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F346vz331q%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d41b6102c56ace4788c452656accab/href">https://medium.com/media/e6d41b6102c56ace4788c452656accab/href</a></iframe><p>And there we go, thats node’s promises explained in a nutshell. That should be enough knowledge for you to go make/break some promises!</p><p><strong>COMMON PITFALLS</strong></p><ul><li>Don’t let your promises get too nested! Try to keep them on a lean heirarchial tree by returning them to the higher chain unless there’s a need for asynchronous resolution of multiple at once</li><li>Keep in mind error handling in promises does not bubble up the same in try catch</li><li>Keep in mind that you jump to the nearest catch block when rejecting a promise and then proceed to the then immediately after (short circuit pattern). The catch does not have to be directly after your statement.</li><li>Keep in mind you can also pass one Arg to the next promise chain so you might want to declare local <em>let </em>statements up the top</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6c1f9b6d0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding “async-iness” in node.js]]></title>
            <link>https://medium.com/@kash./understanding-async-iness-in-node-js-9005a794e6b7?source=rss-a5f8bb046c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9005a794e6b7</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Kash]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 22:36:33 GMT</pubDate>
            <atom:updated>2018-08-18T07:14:56.766Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Understanding why even though you wrote poetry in JavaScript, you ended up with a horror novel</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2slCqDQdL4UcGnjqyx5ZA.png" /><figcaption>Lets go on a quest to understand why the arrows have betrayed us!</figcaption></figure><p>Javascript is a great scripting language and node.js is a powerful runtime that lets us extend it to new heights. Having worked with node for years now I am a great fan of it across multiple facets.</p><p>One of the most useful/distinguishing/disorientating features of writing javascript in node.js is the single threaded asynchronous paradigm that it enforces as a default. But what does this really mean and why do we care about it?</p><p>I want to keep this article as a tangible and practical introduction more than I want to dive into theory. There are multiple virtues (and curses) to node’s asynchronous nature though that I plan to cover in a follow up article.</p><p>Before we start it is important to understand that asynchronous operations are not truly parallel unlike multi-threaded paradigms: our javascript thread in Node is only ever doing one thing at a time, although it may delegate responsibilities to its C bindings which in turn multithread.</p><h4>Enough theory! Lets look at a simple practical example:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fz6742k4oj4%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fz6742k4oj4%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fz6742k4oj4%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/c530e44e55d6022146c4da9b42f23182/href">https://medium.com/media/c530e44e55d6022146c4da9b42f23182/href</a></iframe><p>So what’s special about the above code snippet? Well <em>nothing</em>, in fact its remarkably uninteresting!</p><p>All the operations above are <em>CPU </em>and <em>memory </em>based locally to the javascript thread (except console.log) so we executed synchronously just like almost any other language.</p><p>This is critical to understand: when we write node.js applications, we aren’t asynchronous unless we have to be: IO on CPU or memory will execute synchronously, there is <strong>no magic</strong> that goes on here.</p><h4>Lets consider something the same but different…</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fn1p9ovp06j%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fn1p9ovp06j%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fn1p9ovp06j%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbc99cc822aa6f0a07dbfeac5b2045d1/href">https://medium.com/media/cbc99cc822aa6f0a07dbfeac5b2045d1/href</a></iframe><p><strong><em>MAGIC!! </em></strong><em>What happened to our ordering?! Why is the second output first and the first output second? Why is our application not reading like a book? Is this even real life?</em></p><p>Remember how we spoke about CPU and memory IO? This time we asked for something different: we asked for Disk IO with the fs.readFile instruction which is where node starts getting fancy.</p><p>Consider that the v8 engine in node.js is also Google Chrome’s javascript engine. The need for asynchronous processing makes complete sense here: we don’t want web developers spinning up their own threads or worrying about “low level” concerns but at the same time we can’t block a thread by waiting on operations since that would make the DOM unresponsive and impractical.</p><p>The solution to this conundrum is to pass long running operations to node.js’s C++ bindings and OS kernel (via the event loop which we can cover in a later article) and provide a reference for execution upon completion (a callback). Meanwhile, our thread continues doing its thing resulting in an “incorrectly” sequenced statement.</p><p>Well then how do we deal with this? There are a few ways, lets go through them briefly:</p><h4>Callback hell? I fear no such thing!</h4><p>You’ll notice in the above example we provided two arguments in fs.readFile, the file to read and also a callback. ‘callback’ may sound like a fancy name, but its dead simple: its a function you define as being triggered when node.js’s C++ binding returns from doing its job.</p><p>The function you pass your callback into to will determine which args you receive, but in general you can expect the first arg to be an error if defined and the second to be what you wanted on a success.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F8kr473xl3l%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F8kr473xl3l%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8kr473xl3l%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/12e6a82ce006bce087487278289f10e5/href">https://medium.com/media/12e6a82ce006bce087487278289f10e5/href</a></iframe><p>Using callbacks isn’t <em>always</em> a <em>terrible </em>idea, however they scale very poorly in practice from a legibility and comprehensibility perspective. Once they start getting nested across multiple files and other callbacks, scope pollution, indented linting and provisioning for callback artuments all significantly impair our ability to write succinct and legible code. Transitioning from callbacks to promises is also a trivial task as we’ll see later on.</p><h4>Sync operators: You had the one job!</h4><p>In the below example we pass through the synchronous version of fs.readFile.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F9jmnl0kqzo%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F9jmnl0kqzo%3Fautoresize%3D1%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F9jmnl0kqzo%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5b8dde0907f6958c2d4aa0d0f66a63a/href">https://medium.com/media/a5b8dde0907f6958c2d4aa0d0f66a63a/href</a></iframe><p>When we pass through the sync version of a binding, we halt the javascript thread until its complete. Execution of all other tasks can’t begin/complete for this period. The hyperAwesome job will not execute until the file is returned, which is inefficient since it has no dependency on the readFile operation and we wanted it to execute ASAP.</p><p>Whilst file system access is generally relatively quick, consider if that was a large file or a HTTP call: we wouldn’t execute the hyperAwesome function until after the backend responded which could be of indeterminate duration.</p><p>Using sync operations is a contextual implementation: it can be okay in apps that do only one thing or for init tasks but in apps that do multiple things at once (a server asynchronously processing requests is a classic example) you are dead in the water whilst the operation completes.</p><h4>Make me a promise?</h4><p>Using promises is very compelling, they’re easy to set up and rectify callback hell as well as extending our ability to write handlers seamlessly. I’ll write an article elaborating on them shortly, but here’s a quick example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09f1e9b7d98ea084789fe2ebb4ea39cc/href">https://medium.com/media/09f1e9b7d98ea084789fe2ebb4ea39cc/href</a></iframe><p>We use <em>then </em>to define the action to perform after a promise is complete. We can keep all promises on a single nested hierarchy instead of embedding them, they also effectively standardise callback handlers which are otherwise discretionary to developer implementations.</p><h4>The async/await</h4><p>Async/await is a nice syntax sugar we can put over promises to make the code read as if it were synchronous without actually halting the thread. Some may prefer the legibility of this approach and its consistency with other languages.</p><p>The important thing to note is that the await operator does not halt the thread unlike a sync method, it just instructs that the next line should not execute until the fs.readFile operations value is assigned to the data variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a3fe31e277493a9b89c39b31fe0c8d/href">https://medium.com/media/55a3fe31e277493a9b89c39b31fe0c8d/href</a></iframe><p>If any of the above was of interest to you, keep an eye out for my follow up articles, there is alot more depth to cover!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9005a794e6b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>