<?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 Ishika Gupta on Medium]]></title>
        <description><![CDATA[Stories by Ishika Gupta on Medium]]></description>
        <link>https://medium.com/@ishika.gupta?source=rss-5f3c7140e57d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*osdRN39TCXegey2LxBkuNg.jpeg</url>
            <title>Stories by Ishika Gupta on Medium</title>
            <link>https://medium.com/@ishika.gupta?source=rss-5f3c7140e57d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:16:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ishika.gupta/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[Architectural Insights: Choosing a Web Automation Framework]]></title>
            <link>https://javascript.plainenglish.io/architectural-insights-choosing-a-web-automation-framework-a59306411891?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59306411891</guid>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[cypress-architecture]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[web-automation]]></category>
            <category><![CDATA[playwright-architecture]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 18:16:43 GMT</pubDate>
            <atom:updated>2024-03-20T01:12:47.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*EdsQyjm7vJQrIAkGH9yfIQ.png" /></figure><p>Testing takes too much time and effort. There’s no way to test everything. Most testing is clicking around every turn of your application. Sometimes it gets boring, too. It takes forever and feels like a waste of time. So… click click click and hope for the best? That’s what we’re doing? If we want to ship high-quality, well-tested JavaScript applications, there has to be a better way. We know humans are bad at complex, repetitive tasks. We also know that computers are very, very good at complex, repetitive tasks. Here comes our automation testing.</p><blockquote>Automated tests are the pro move<br>Automated tests are your backup, your muscle<br>Automated tests are your secret weapon</blockquote><h3>Web automation</h3><p>Let’s go back to 1993 when the first graphical web browser was developed. Before that, nobody knew about web automation. After 2004, Selenium RC became the first and foremost automated web testing tool, enabling users to adopt their preferred programming language. Following that, the rise of Node.js and web automation tools has also led to the development of web drivers, CDP (Chrome DevTools Protocol), and Web APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*yzV2zeQWXQFscFiCOTA-rQ.png" /><figcaption>Fig 1.1 Rise of web automation</figcaption></figure><h3>Automation Approaches</h3><p>Before delving into architecture, let’s explore some fundamental approaches and protocols commonly utilized in web automation.</p><h4>High Level — “in-process” web automation</h4><p>Tools that uses web APIs and Node.js to run test within the browser. They inject Js inside web page and drive the Js inside this page using web APIs. As depicted in Figure 2.1, this in-process automation is completely oblivious about all the different subsystems in the browser. Therefore, it provides high level api for testing.</p><p>Cypress framework use web APIs and Node.js to run tests directly in the browser. We will talk about cypress architecture later in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ne0PkjK2xPlLGcIcs3GwQ.png" /><figcaption>Fig 2.1 “in-process” web automation</figcaption></figure><h4>Low Level — “out-of-process” web automation</h4><p>Tools that need more control i.e opening multiple tabs or or simulating device mode. As depicted in Figure 2.2, they need to execute the remote commands from outside browser, to control it via protocols. The two main automation protocols are —</p><ul><li><em>WebDriver “Classic” — used by selenium</em></li><li><em>Chrome DevTools Protocol (CDP) —used playwright</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psYSAZe45omsIgn8nR24Zg.png" /><figcaption>Fig 2.2 “out-of-process” web automation</figcaption></figure><h3>WebDriver Classic</h3><p>WebDriver provides a ‘platform-and-language-neutral’ tool for automating web browser interactions. It control web browsers and allow developers to simulate user actions like clicking buttons, filling forms, navigation. It has excellent cross-browser support.</p><h4>Working</h4><p>As depicted in Figure 3.1, Automation scripts issue commands through HTTP requests to a web driver server. This server subsequently communicates with browsers using internal, browser-specific protocols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b19fycvxwlDKe6Vl.png" /><figcaption>Fig 3.1 WebDriver — using HTTP</figcaption></figure><h3><strong>Chrome DevTools Protocol</strong></h3><p>Chrome DevTools was initially designed for debugging purposes. It allow developers to control and inspect the behavior of browser instances remotely, enabling tasks such as automating web page interactions, capturing performance metrics, debugging and profiling web applications.</p><h4>Working</h4><p>As depicted in Figure 3.2, CDP establishes direct communication channels with Chromium-based browsers via WebSocket connections. This direct communication facilitates faster performance and grants low-level control capabilities such as Capturing console messages, simulating device mode and geolocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wtr5LIb3msmwgXiN.png" /><figcaption>Fig 3.2 CDP — using websockets</figcaption></figure><blockquote>WebDriver “Classic” is HTTP-based, making it slow and auto waiting functionality is often implemented using polling, which can sometimes take time. CDP, on the other hand, is WebSocket-based, supporting bi-directional messaging by default.</blockquote><h3>Automation Framework Architectures</h3><p>Our goal is to choose what test framework we want to use in order to enable us to write/introduce our first automation test. In Javascript land there’s really only two top modern choices, Playwright and Cypress. we wanted to make sure we choose the framework for us that will scale with us and fit our needs. In this article I will talk about the architecture of both the tools. This will help us in understanding the limitation of both tools.</p><h4>Cypress</h4><p>Cypress framework is a JavaScript-based end-to-end testing framework built on Mocha. Uses web APIs and Node.js to run test within the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVZ431nHMTNsHCJwMmAZ3Q.png" /><figcaption>Fig 4.1 Cypress Architecture</figcaption></figure><p>Fig 4.1: Representing the Working of Cypress Inside Browser. Let’s see the step-by-step working:</p><ol><li>Cypress testing runs on a NodeJs server, which essentially acts as a backend during the testing process. This backend opens a browser window, sets up a proxy to this window, and connects the domain to localhost.</li><li>Within the browser window, there are two iFrames: one for executing the Cypress tests themselves on localhost, and another for running our application. Since Cypress is in an iFrame with the domain localhost, which is different from the application’s domain. To enable communication between the Cypress iFrame and the application iframe, a script tag is injected, which sets its domain to localhost. This makes it possible for Cypress to access everything related to the application, including DOM, window objects, local storage, network layer, and browser DevTools.</li><li>Cypress and NodeJs also need to communicate with each other to request OS privileges, such as taking screenshots or recording videos. Communication between the Cypress backend and the Cypress iFrame is facilitated through a Websocket, rather than the traditional JSON wire protocol or HTTP requests. Cypress interacts directly with the operating system to capture screenshots, record videos, and perform basic file system and network operations.</li><li>The Proxy in this setup is responsible for proxying all HTTP requests from the test application to its backend. Every HTTP request leaving the browser is directed through the Proxy to the WEB and back to the browser. This means Cypress operates on a network layer and can control and modify every HTTP request. Using the proxy, Cypress can access the request for the test to be executed and act as the “man in the middle” to spy on, mock, or modify requests and responses as needed.</li></ol><h4>Playwright</h4><p>Playwright is a browser automation tool and the successor of the node library Puppeteer, as it has the same functionality along with several improvements such as Cross-browser testing and device emulations. Playwright is also written and maintained by the same people who created Puppeteer, and are now working at Microsoft. Playwright is designed to be aligned with the architecture of modern browsers, and it runs tests out-of-process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jd3Bb563qE1tfU-Rjmwobg.png" /><figcaption>Fig 4.2 Playwright architecture</figcaption></figure><p>Fig 4.2 Represent the working of playwright. Let’s see the step-by-step working:</p><ol><li>Playwright uses a single WebSocket connection to communicate all requests between the client and server, which provides a more efficient and reliable means of automation compared to the Selenium HTTP Connection protocol.</li><li>To establish a WebSocket connection, the client sends a request to the server via the WebSocket handshake process</li><li>The Playwright Server then communicates with the client and different web browser engines i.e chrome, safari, mozilla.</li><li>The Playwright uses the Chrome DevTools Protocol (CDP) for Chromium-based browsers, while for Firefox and WebKit, it implements its own protocols similar to CDP.</li></ol><h3>What to pick?</h3><p>The choice between these frameworks depends on the specific functionality that is important for your project. If your application testing doesn’t necessitate features such as cross-browser compatibility, multi-language support, or managing multiple tabs and iFrames, Cypress could be the optimal choice. Cypress offers robust documentation and a thriving community, facilitating easier access to assistance and solutions for challenging scenarios. On the other hand, if your application requires these advanced functionalities, Playwright emerges as a suitable option. Playwright supports parallelization, and its syntax closely resembles JavaScript, complemented by effective debugging tools. Therefore, for projects demanding such capabilities, Playwright presents itself as a strong contender.</p><p>Fig 5.1 is showing a small comparison between cypress and playwright.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBAw2FymO8Gt6H3zSkcjeQ.png" /><figcaption>Fig 5.1 playwright vs cypress</figcaption></figure><h3>Conclusion</h3><p>We’ve covered the fundamentals of web automation tools, including the architectures of Cypress and Playwright, along with their distinguishing features. For my project I am using playwright as it is faster compared to cypress. Feel free to share any additional insights you may have and your preference for which framework you’d prefer to use for your application.</p><p>That’s it and if you found this article helpful, please click the clap 👏button, and if you have any doubt, feel free to comment! I’d be happy to help .</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59306411891" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/architectural-insights-choosing-a-web-automation-framework-a59306411891">Architectural Insights: Choosing a Web Automation Framework</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP/1.X And HTTP/2.0]]></title>
            <link>https://medium.com/@ishika.gupta/http-1-x-and-http-2-0-e95b6529327c?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e95b6529327c</guid>
            <category><![CDATA[multiplexing]]></category>
            <category><![CDATA[http1]]></category>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[binary-framing]]></category>
            <category><![CDATA[head-of-line]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Wed, 10 May 2023 18:28:46 GMT</pubDate>
            <atom:updated>2023-05-10T18:35:44.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="http" src="https://cdn-images-1.medium.com/max/1024/0*-7pidhPVYKxN3rdp.png" /></figure><p>HTTP invented by Tim Berners-Lee at CERN in the years 1989–1991, HTTP (Hypertext Transfer Protocol) is the<strong><em> communication protocol</em></strong> of World Wide Web. It is an application layer protocol to transfer information between client and server . It runs on top of other layers of the network protocol stack.</p><blockquote>HTTP has five versions — HTTP/0.9, HTTP/1.0, HTTP/1.1 ,HTTP/2.0 and HTTP/3. Most common used is HTTP/1.1, and HTTP/2.0</blockquote><h3>Glossary</h3><p><strong>Protocol </strong>A protocol is a<strong> </strong><em>set of rules and guidelines for communicating</em><strong> </strong>data. Rules are defined for each step and process during communication between two or more computers. Networks have to follow these rules to successfully transmit data.</p><p><strong>TCP</strong> is a <em>connection-based protocol</em> to exchange messages over a network.</p><p><strong>Connection </strong>Header controls whether the network connection stays open after the current transaction finishes.</p><pre>Connection: keep-alive<br>Connection: close</pre><p><strong>keep-alive</strong> Header allows the sender to decide about how the connection may be used to set a timeout and a maximum amount of requests.</p><pre>Keep-Alive: timeout=5, max=1000</pre><p><strong>short-lived</strong> new TCP connection created each time a request needed sending, and closed once the answer had been received.</p><h3>HTTP 1.X</h3><p>HTTP relies on TCP (layer 4) for its transport protocol, providing a connection between the client and the server. HTTP used a single model to handle such connections. These connections were<em> short-lived.</em></p><p>Modern Web pages require many requests (a dozen or more) to serve the amount of information needed. Several messages must be exchanged between the client and the server. <em>Network latency and bandwidth affect </em>performance when a request needs sending. .</p><p><strong>SHORT LIVED CONNECTION</strong></p><p><strong>HTTP/1.0</strong> is <em>short-lived connections</em>. Each HTTP request is completed on its own connection; this means a TCP handshake happens before each HTTP request, and these are serialized(Fig 1.1).. In HTTP/1.0, this model is not used when the connection header is sent with a value other than close.</p><p><strong>Drawback</strong> opening each TCP connection is a <em>resource-consuming operation.</em>Modern Web pages require many requests (a dozen or more) to serve the amount of information needed.<em>Network latency and bandwidth affect </em>performance when a request needs sending.</p><figure><img alt="http/1.0" src="https://cdn-images-1.medium.com/max/1012/0*cwIBnKVuuhpak-YS.png" /><figcaption>Fig 1.1 HTTP/1.0</figcaption></figure><p><strong>PERSISITENT CONNECTION (</strong><em>keep-alive connection)</em></p><p><strong>HTTP/1.1</strong> is Persistent connection. It remains open for a period of time, and can be reused for several requests, saving the need for a new TCP handshake, and utilizing TCP’s performance enhancing capabilities (Fig 1.1).</p><p><strong>Drawbacks</strong>: Even when idling it consume server resources, and under heavy load can cause- DoS (Denial of Service) is a network attack that prevents legitimate use of <a href="https://developer.mozilla.org/en-US/docs/Glossary/Server">server</a> resources by flooding the server with requests.</p><p><strong>HTTP PIPELINING</strong></p><p>Multiple HTTP requests to be sent over a single TCP connection without waiting for the corresponding responses (Fig 1.1)..Pipelining improves the performance of loading times of web pages, but it suffers from <strong><em>HOL blocking issue.</em></strong></p><p><em>HOL(HEAD OF LINE BLOCKING)</em><strong>-</strong> Pipelining requires the clients to start sending subsequent requests only when previous requests were sent successfully. But these requests could be sent without waiting for their responses.It also requires the server to send responses in the order in which the requests were received. This ordering of requests and responses is required otherwise there is no way for the client and the server to figure out the corresponding requests and responses. HOL blocking can happen here if, let say, the processing of one of the requests or responses takes longer than others or is delayed due to retransmission. It would make other requests/responses wait for the previous ones to be complete (Fig 1.2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*cvgh6PAoe7lq3PIZ.png" /><figcaption>Fig 1.2 HOL</figcaption></figure><p><strong>DOMAIN SHARDING</strong></p><p>Browsers open several connections to each domain, sending parallel requests(Fig 1.3).. Default was once 2 to 3 connections, but this has now increased to a more common use of 6 parallel connections. (More can cause DOS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*9jAqUIgO5MweYOd6.png" /><figcaption>Fig 1.3 Domain Sharding</figcaption></figure><h3>HTTP 2.0</h3><p>HTTP/2 will make our applications faster, simpler, and more robust. The primary goals for HTTP/2 are to reduce latency. HTTP/2 does not modify the application semantics of HTTP in any way. All the core concepts, such as HTTP methods, status codes, URIs, and header fields, remain in place. Instead, HTTP/2 modifies how the data is formatted (framed) and transported between the client and server</p><p>HTTP/2 enables -</p><ul><li>Binary message framing.</li><li>Multiplexing</li><li>Header Compression</li><li>Server Push</li><li>One Connection Per Origin</li><li>Prioritization and Protocol negotiation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coDh-DxyjT1hrHIbXelc_g.png" /><figcaption>Fig 2.1 Browser using http/2,0</figcaption></figure><h4>Binary message framing</h4><p>HTTP/2 communication is split into smaller messages and frames, each of which is encoded in binary format (Fig 2.2). Client and server perform all the necessary framing work. our applications will be unaware of all these changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sNmm7eXlx38g75OAuRrUw.png" /><figcaption>Fig 2.2 HTTP/1.0 vs HTTP/2.0</figcaption></figure><ul><li><strong>Stream </strong>A bidirectional flow of bytes within an established connection, which may carry one or more messages.</li><li><strong>Message </strong>A complete sequence of frames that map to a logical request or response message.</li><li><strong>Frame</strong> The smallest unit of communication in HTTP/2, each containing a frame header, which at a minimum identifies the stream to which the frame belongs.</li><li>All <em>communication</em> is performed over a<em> single TCP connection</em> that can carry any number of bidirectional streams. Each <em>stream</em> has a unique identifier and optional priority information that is used to carry bidirectional messages. Each <em>message</em> is a logical HTTP message, such as a request, or response, which consists of one or more frames.The <em>frame</em> is the smallest unit of communication that carries a specific type of data (Fig 2.3)— e.g., HTTP headers, message payload, and so on. Frames from different streams may be interleaved and then reassembled via the embedded stream identifier in the header of each frame.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsIE6LbV9twGUm97wyTMUg.png" /><figcaption>Fig 2.3 HTTP/2.0 Streams</figcaption></figure><p><strong>FRAMES</strong></p><ul><li><strong>HEADERS frame </strong>carries HTTP headers .When sent by the browser to the server, signals that a request is being made. When sent by the server to the browser, signals that a response to a previous request or push promise is being sent.</li><li><strong>PUSH\_PROMISE frame </strong>is sent by the server to the browser to start pushing a resource. It also contains HTTP headers. The kind of headers present in a PUSH\_PROMISE frame are headers that would normally be present in a *request* . This is different of the *response* headers that a server would normally send.</li></ul><blockquote>The actual data for the pushed resource is sent in a fresh stream started by the server — and thus with an even number.</blockquote><ul><li><strong>DATA frames</strong> are sent in either direction to carry the actual of a resource or the contents that the browser POSTs or PUTs to the server.</li><li><strong>RST\_STREAM frames</strong> are handy in a variety of conditions, one of them is having the browser signal to the server that a pushed stream is not needed.</li></ul><h4>Multiplexing</h4><p>HTTP/2.0 enables full request and response multiplexing, by allowing the client and server to break down an HTTP message into independent frames (Fig-2.4)interleave them, and then reassemble them on the other end. It resolves the head-of-line blocking problem in HTTP/1.x and makes our applications faster. It deliver lower page load times by eliminating unnecessary latency and improving utilization of available network capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8Gh7FfBV7d69Ijbk1AmAw.png" /><figcaption>Fig 2.4 Multiplexing</figcaption></figure><h4>Header Compression</h4><p>HTTP/2 compresses request and response header metadata using the HPACK compression format that uses two simple :</p><ul><li>It allows the transmitted header fields to be encoded via a static Huffman code, which reduces their individual transfer size.</li><li>Consists of a static and dynamic tables. The size of each request is reduced by using static Huffman coding for values that haven’t been seen before, and substitution of indexes for values that are already present in the static or dynamic tables on each side.</li><li>All header field names are lowercase</li></ul><p><strong>Static</strong> table is defined in the specification and provides a list of common HTTP header fields that all connections are likely to use (e.g., valid header names)</p><p><strong>Dynamic</strong> table is initially empty and is updated based on exchanged values within a particular connection.</p><p>e.g- fields: <strong>:method:GET</strong>, <strong>:path:/</strong> and <strong>:scheme:https</strong> are always present in the static dictionary, and will each be encoded in a single byte. Then some fields will only have their names compressed in a byte: <strong>:authority</strong>, <strong>accept</strong>, <strong>accept-encoding</strong>, <strong>accept-language</strong>, <strong>cookie</strong> and <strong>user-agent</strong> are present in the static dictionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAwlevCALS6ifQtlvvWeBg.png" /><figcaption>Fig 2.5 HPACK Compression</figcaption></figure><h4>Server Push (Optional Feature)</h4><p>Ability of the server to send multiple responses for a single client request. In addition to the response to the original request, the server can <em>push</em> additional resources to the client (<a href="https://hpbn.co/http2/#server-push">Fig</a> 2.6), without the client having to request each one explicitly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8G7Mo3xa_pQN4QBCluAzEA.png" /><figcaption>Fig 2.6 Server Push</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D7x1wHbEh_JZ4vokQKO3A.png" /><figcaption>Fig 2.7 Server Push in Chrome</figcaption></figure><blockquote>Let the server push the associated resources ahead of time? The server already knows which resources the client will require; that’s server push. pushed resources must obey the same-origin policy</blockquote><p>e.g Inlining the resource (css js) into the document, Http/2.0, push that resource to the client, without waiting for the client to request it.</p><blockquote>e.g — Server receives HEADERS frame asking for index.html in stream 3, and it can forecast the need for style.css and script.js. Server sends a PUSH_PROMISE for style.css and a PUSH_PROMISE for script.js again in stream 3. These frames are roughly equivalent to a browser’s request (Once the client receives a this frame it has the option to decline the stream via a RST_STREAM frame). Server sends a HEADERS frame in stream 3 for responding to the request for index.html. Server sends DATA frame with the contents of index.html, still in stream 3. Server sends HEADERS frame for the response to style.css in stream 4 (even stream number) and then for the response to script.js in stream 6. Server sends DATA frames for the contents of style.css and script.js, using their respective stream numbers.</blockquote><p><strong>HTTP PRELOAD VS SERVER PUSH</strong></p><p>e.g Browser makes a request for index.html. browser receives the file and upon parsing it finds that it will need to request style.css and within that css file a font.tff file is referenced. Instead of requesting style.css and font.ttf sequentially, preload allows you to send a request to the server for both style.css and font.ttf at the same time. Since font.ttf is an asset that will be needed in the near future, preloading it would be an efficient way to request it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tJD-pKip3U51zGKRCkmrQ.png" /><figcaption>Fig 2.7 Preload vs Push</figcaption></figure><h4>One Connection Per Origin</h4><p>HTTP/2 connections are persistent and only one connection per origin is required. Reduced number of connections helps in improving performance of HTTPS deployments — fewer expensive TLS handshakes, better session reuse, and an overall reduction in required client and server resources.</p><h4>Stream Prioritization</h4><p>Each stream to have an associated weight and dependency</p><ul><li>Each stream may be assigned an integer weight between 1 and 256</li><li>Each stream may be given an explicit dependency on another stream</li></ul><p><em>Browser Prioritization</em>: Not all resources have equal priority when rendering a page in the browser: the HTML document itself is critical to construct the DOM; the CSS is required to construct the CSSOM; both DOM and CSSOM construction can be blocked on JavaScript resources and remaining resources, such as images, are often fetched with lower priority.</p><p>When we launch a request (create a stream). It’s possible that this stream depends on the completion of another stream before it starts.Parent stream should be allocated resources ahead of its dependencies — e.g., please process and deliver response D before response C ( Fig 2.8)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QttES8_yTc4BFWOXA1kPgg.png" /><figcaption>Fig 2.8 Prioritization</figcaption></figure><p><em>The client cannot force the server to process the stream in particular order using stream prioritization.</em></p><h4>Flow Control</h4><p>Every stream, and the connection as a whole maintains a send window, which is the amount of data that the server is allowed to send on the stream/connection. Once this window is exhausted no more data can be sent, until the remote endpoint sends a<em> window_update</em> frame that increases the send window size. This additional flow control window is on top of the flow control already provided by TCP. The default window size is 65,535 bytes. increase this in the initial SETTING frame. Flow control only applies to DATA frames. HTTP2 flow control is hop-by-hop, configured intermediaries may alter the window sizes</p><h4>HTTP/2.0 HOL Blocking at TCP layer</h4><p>TCP packet carries a unique sequence number when put on the wire, and the data must be passed to the receiver in-order . If one of the packets is lost en route to the receiver, then all subsequent packets must be held in the receiver’s TCP buffer until the lost packet is retransmitted and arrives at the receiver. Because this work is done within the TCP layer, our application has no visibility into the TCP retransmissions or the queued packet buffers, and must wait for the full sequence before it is able to access the data. Instead, it simply sees a delivery delay when it tries to read the data from the socket. This effect is known as TCP head-of-line (HOL) blocking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6gr58Xz1VPNrsqTk1M7Ww.png" /><figcaption>TCP HOL</figcaption></figure><p><strong>HTTP/3 or QUIC solves this issue by leveraging UDP instead of TCP as the transport protocol.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e95b6529327c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus — Understand PromQl]]></title>
            <link>https://blog.devops.dev/prometheus-understand-promql-e6845ebed5df?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6845ebed5df</guid>
            <category><![CDATA[promql]]></category>
            <category><![CDATA[rate]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[histograms]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 04:59:45 GMT</pubDate>
            <atom:updated>2022-09-16T09:43:34.559Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prometheus — Understand PromQl</h3><p>Prometheus is an open-source monitoring and alerting toolkit. It stores its metrics as time-series database i.e changes are recorded over time. Metrics are important as they help us to track which service has most errors , response time of requests, total active sessions, etc.</p><p>For creating graphs, prometheus has its own language which can query the data called <strong>PromQl</strong>.</p><h4>1. PromQl Terminology</h4><p>Metric Types</p><ul><li>Counters - cumulative monotonically increasing metric, whose value can only increase, remain same or reset to 0. eg. Total number of requests(http_request_total), total errors.</li><li>Gauge - Non monotonic metric that can go up and down. Eg. node memory utilisation, active sessions over time, etc.</li><li>Histogram - Sample values are put into predefined bucket i.e 0.005, 0.25, 5, 10 . It measures the frequency of samples that fall into specific buckets. eg. request duration, response size. We will discuss histogram in further detail.</li><li>Summary - Similar to histogram, it also provides total sum and count of samples. it calculates configurable quantiles over a sliding time window.</li></ul><p>Data Types</p><ul><li>String — <em>string value currently unused.</em></li><li>Scalar — <em>numeric floating point value</em>.</li><li>Instant vector — <em>single sample value for specific timestamp.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAoa_9GJylaHNzbJ7bfyXA.png" /><figcaption>1.1 Instant vector</figcaption></figure><ul><li>Range Vector — <em>multiple sample values back from the current instant</em>. it is generated by appending the time selector in [] after instant vector. ex — [5m], [60s]. How far back in time values should be fetched for each resulting range vector element.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJszaCTHFxpuoRmLpqQCTg.png" /><figcaption>1.2 Range vector</figcaption></figure><h4>2. Query Structure</h4><blockquote>function(metric_name{label=’value’, label2=’value’}[time duration])</blockquote><p>we can filter the query using <em>label</em>. Labels are defined inside the {} after the metric name. Label filters support four operators:</p><ul><li>= equal</li><li>!= not equal</li><li>=~ regex expression</li><li>!~ not matching expression</li></ul><p>Range vectors can not be graphed as they have multiple values for each timestamp. PromQl provide us functions (<a href="https://prometheus.io/docs/prometheus/latest/querying/functions/">https://prometheus.io/docs/prometheus/latest/querying/functions/</a>) that can convert range vector to instant vector which can be graphed.</p><h4><strong>3. Functions</strong></h4><p>There are many functions, more commonly used ones are :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*zWm4JZLqN80WFcCc76GC_w.png" /><figcaption>3.1 Graph</figcaption></figure><blockquote>rate(Range vector) =&gt; instant vector</blockquote><ul><li><strong>rate -</strong> can only used with counters. It calculates <strong><em>per second average rate of increase in time series</em></strong> of range vector. It requires at least two data points. Rate should only be used with slow-moving counters. E.g <em>rate(http_request_time[5m]) -&gt; instant vector -&gt; 0.29675</em></li></ul><pre><strong><br>rate(http_request_total[1m]) -  current time is at 60s</strong><br>Refer 3.1, it is calculated as average of: <br>(50–30)/(60–45) <br>(30–15)/(45–30) <br>(15–10)/(30–15)</pre><ul><li><strong>irate</strong> can only used with counters. It calculates <strong><em>per second instant rate of increase in time series </em></strong>of range vector. irate is expected to capture spikes when graph has volatile, fast-moving counters.E.g i<em>rate(http_request_time[5m]) -&gt; instant vector -&gt; 0</em></li></ul><pre><strong>irate(http_request_total[1m]) - current time is at 60s</strong><br>Refer 3.1, it is calculated as : <br>(50–30)/(60–45)<br>it only goes to the first step and ignore the others</pre><pre><strong>for 135 to 75s  irate(http_request_total[1m])</strong><br>Refer 3.1, (100–100)/(135–120) = 0 <br>this doesn’t capture spike. <br><em>this is only used in case when graph is volatile, fast-moving counters.</em></pre><ul><li><strong>increase</strong> calculates the increase in the time series in the range vector. E.g increase<em>(http_request_time[5m]) -&gt; instant vector -&gt; 10</em></li></ul><pre><strong>increase(http_request_total[1m])  -  current time is at 60s</strong><br>Refer 3.1, 50–15 = 35</pre><ul><li><strong>avg_over_time</strong> this is used with gauges. The average value of all points in the specified interval.</li></ul><h4>4. Aggregation Operators</h4><p>it is similar to group by clause in sql. eg — <em>sum</em> (calculate sum over dimensions), <em>topk</em> (largest k elements by sample value).</p><blockquote>aggregation_op(instant vector) =&gt; instant vector</blockquote><p>These operators can apply to instant vector and return instant vector. As shown in 4.1 and 4.2 it calculated the sum which is grouped by bucket and pick top 3 values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ee2AxVGreNYWYNFzoQxsZg.png" /><figcaption>4.1 sum operator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rpn7GAQQn408D_T8k0nJA.png" /><figcaption>4.2 topk operator</figcaption></figure><h4>5. Histogram</h4><p>Interesting part in this is buckets. Default buckets values are [0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,+inf]. These are counters which form cumulative histogram. Buckets are defined as le — less than or equal to.(refer 5.2)</p><p>eg. response time 5s goes in 5, 10 and+inf buckets. 2.5 s goes in 2.5, 5, 10 and +inf buckets. Bucket 2.5 value is 1, 5 value is 2, 10 value is 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-dxpbM1FIEnF7fSNTNUNUw.png" /><figcaption>5.1 histogram bucket</figcaption></figure><p>Histogram exposes:</p><ul><li><strong>_sum suffix in metric</strong> — It track the total sum of observed value. Refer 5.1 http_request_duration_seconds_sum is 7.5(2.5+5)</li><li><strong>_count suffix in metric</strong> — Total number of observation. Refer 5.1 http_request_duration_seconds_count is 2 (total 2 request)</li><li><strong>_bucket suffix in metric</strong>— Return Cumulative counters for buckets {le} as shown in 5.4 , 5.1— e.g http_request_duration_seconds_bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSRBsX6GawUqyH4A3N9lvg.png" /><figcaption>5.2 histogram buckets</figcaption></figure><pre>From Histogram we can also calculate the average of observation. </pre><pre>average of request duration =   rate(http_request_duration_seconds_sum[5m])<br>/<br>  rate(http_request_duration_seconds_count[5m])</pre><p><strong>6. Histogram Quantiles</strong></p><blockquote>histogram_quantile(φ scalar, b instant-vector) . b is count of observation in each bucket.</blockquote><p>This can be used to calculate response time of request. For e<em>g. response time within which you have served 95% of request.</em></p><blockquote>histogram_quantile(0.95, sum(rate(http_req_duration_sec_bucket[5m]))) by (le))</blockquote><p>It shows frequency of observed value in each bucket (refer 6.1). and histogram_quantile will pick bucket value that is serving 95% request (refer 6.2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSRBsX6GawUqyH4A3N9lvg.png" /><figcaption>6.1 histogram buckets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSTsrnu8moJkdbr-6dRO-Q.png" /><figcaption>6.2 histogram quantile</figcaption></figure><p>if quantile is located in highest bucket i.e Inf, It returns the upper bound of second highest bucket otherwise linear interpolation is applied within that bucket as explained below(lower limit of lowest bucket is assumed to be 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*1EYcwgHRkapb4kqLf6hALA.png" /><figcaption>6.3 graph</figcaption></figure><pre>total req count = 0.06666. (Refer 6.1)<br>0.95 quantile value is 0.063 (number of request)</pre><pre><strong>0.063</strong> <strong>requests serve under x ms. find x?</strong></pre><pre>slope = (0.066–0.044)/(0.1–0.05) = 0.44 (Refer 6.3)</pre><pre>As we have slope value.we can calculate x<br>slope = (0.063–0.044)/(x-0.05) = 0.44<br>x = 0.05 + ((0.063–0.044)/0.44) = 0.0931 (approximately due to change in timestamp)</pre><h4>7. Other Queries</h4><pre><em>Errors count</em><br>sum(rate(http_incoming_request_count{status=~”[4,5].*”}[1m])) by (status) *60</pre><pre><em>Response time<br></em>histogram_quantile(0.95, sum(rate(http_req_duration_sec_bucket[5m]))) by (le)) * 1000</pre><pre><em>Top 3 errors status with route</em><br>topk(3, sum(rate(http_incoming_request_count{status=~”[4,5].*”}[1m])) by (status, route) *60)</pre><h4><strong>8. Graph Step Size</strong></h4><p><strong>step</strong> is calculated using the time range and the width of the graph (the number of pixels).For eg, when the time range is last 1 hour and the graph is full screen, then the step size is 2m. If the time range is 6 months and the graph is full screen, then the step size might be 1d</p><blockquote>while creating graph we might loose data with high time duration i.e last 6 hours, last 12 hours , last 24 hours, last 1week (as step size increases)</blockquote><p>Data Points —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*E6Z8MER_iFGEjEiTJY1wtA.png" /><figcaption>8.1 data points</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*4VXaxCTslka2fHjr_v1l3g.png" /><figcaption>8.2 graph</figcaption></figure><pre><strong>current time = 01:00<br>Find active_user_session[1h] </strong>(refer 8.1/8.2)<br><strong>For Last 5hours</strong> - step size is 1h (x axis time interval)<br><br>time duration is [1h] (took values back from the current instant)</pre><pre><em>Point on x axis - 09:00  10:00  11:00  12:00   01:00</em></pre><pre>calculate count - (20-10)(40-20) (40-40)(30-40) (20-30)</pre><pre><strong>For Last 10 hours</strong>- step size is 4hour<br><strong>Find active_user_session[1h]<br></strong>time duration is [1h] (took values back from the current instant<em>)</em></pre><pre><em>point on x axis (time) - 01:00 05:00 09:00 01:00</em></pre><pre>for calculating count at 01:00 we pick 12:00 to 01:00<br>or calculating count at 09:00 we pick 08:00 to 09:00</pre><pre><strong><em>we will miss the peak which is at 10:00 and 11:00</em></strong></pre><pre><strong>Find active_user_session[4h]</strong><br>for calculating count at 01:00 we pick 09:00 to 01:00<br>we are considering peak also</pre><pre><strong><em>solution is to use interval same as step size and keep min interval 1m<br></em></strong><a href="https://grafana.com/blog/2020/09/28/new-in-grafana-7.2-__rate_interval-for-prometheus-rate-queries-that-just-work/">https://grafana.com/blog/2020/09/28/new-in-grafana-7.2-__rate_interval-for-prometheus-rate-queries-that-just-work/</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6845ebed5df" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/prometheus-understand-promql-e6845ebed5df">Prometheus — Understand PromQl</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Javascript (Event Loop)]]></title>
            <link>https://medium.com/gradeup/asynchronous-javascript-event-loop-1c8de41298dd?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c8de41298dd</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[macrotask]]></category>
            <category><![CDATA[micro-tasks]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 15:00:34 GMT</pubDate>
            <atom:updated>2020-08-13T15:00:34.831Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Javascript is a single-threaded</strong> language at runtime which means only one thing can happen at a time. That is, the JavaScript engine can only process one statement at a time in a single thread. It also means you can’t perform long operations such as network access without blocking the main thread.That’s where asynchronous JavaScript comes into play. <strong>Using asynchronous JavaScript </strong>(such as callbacks, promises, and async/await), you can perform long network requests without blocking the main thread.</p><p>When you open a website in the browser, it uses a single JavaScript execution thread. That thread is responsible to handle everything, like scrolling the web page, printing something on the web page, listen to DOM events (<em>like when the user clicks a button</em>), and doing other things.</p><blockquote>How can JavaScript be single-threaded and non-blocking at the same time?How about when we run timers? Loops?</blockquote><h3>How Does Asynchronous JavaScript Work?</h3><p>To understand how this code is executed we have to understand event loop.</p><h4>EVENT LOOP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*jBHb1fFqLuoDyYCe.png" /><figcaption>fig 1.1 : Event Loop</figcaption></figure><p><strong>Terminology used in JavaScript’s Event loop :</strong></p><p><strong><em>HEAP</em> </strong>is the place (memory) where objects are stored when we define variables.</p><p><strong><em>STACK</em> </strong>which is a usual call stack that contains all called functions. When we call a function for its execution, we are pushing it into the stack. It is popped out of the stack when the execution is completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*881ARE28eUt-uPGI.gif" /><figcaption>fig 1.2 Call Stack</figcaption></figure><p><strong><em>WEB APIs</em> </strong>are responsible for filling the callback queue, providing many features such as the ability to make an AJAX request, setTimeout, DOM events.When we use these APIs, we utilise an <strong>event table</strong>. The event table keeps track of callbacks for their respective events. Once an event occurs, ie an asynchronous operation is completed, then the callback of that event gets enqueued into the callback queue.</p><p><strong><em>CALLBACK QUEUE</em></strong><em> </em>is also known as, Message Queue or Event Queue.With this queue, we have the callbacks from event table. The functions are waiting to be dequeued and put on the Call Stack.</p><p><strong><em>EVENT LOOP</em> </strong>is a process that checks whether call-stack is empty and does the callback queue contains pending task to process if it is — calls top event handler and removes it from queue.</p><blockquote>The event loop understands this and makes sure that the callbacks from the Callback Queue are added to the Call Stack, once the Call Stack is empty.</blockquote><blockquote>The <strong>event loop</strong>, the <strong>web APIs</strong> and the <strong>callback queue </strong>are not part of the JavaScript engine, it’s a part of browser’s JavaScript runtime environment.</blockquote><h4>Execution of setTimeout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*ei7v4GRKyJc5OHkJ.gif" /><figcaption>fig 2.1 setTimeout works</figcaption></figure><p>Refer fig 2.1- On the first line, the engine encounters the greet(). It gets added to the call stack, after which it logs the value . The method gets popped off the call stack. The engine encounters the setTimeout method, which gets popped on to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*Fd5fMsC7io3r81d6.gif" /><figcaption>fig 2.2 setTimeout works</figcaption></figure><p>Refer fig 2.2-setTimeout callback function will get added to the Web API, until the timer (1 sec ) is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*mOBhNixOlXX60QuF.gif" /><figcaption>fig 2.3 setTimeout works</figcaption></figure><p>Refer fig 2.3- Timeout callback gets added to the callback <strong>queue (macrotask queue) </strong>after 1 sec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*aPVGMj7axRtfrPOn.gif" /><figcaption>fig 2.4 setTimeout works</figcaption></figure><p>Refer fig 2.4 - The engine sees the call stack is empty now. setTimeout callback gets pushed on to the call stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*i-DdmXrtqnvFt_8s.gif" /><figcaption>fig 2.5 setTimeout works</figcaption></figure><p>Refer fig 2.5- The callback function return string.The setTimeout callback get popped.</p><p><strong>ZERO DELAYS </strong>doesn’t actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0(zero) milliseconds doesn’t execute the callback function after the given interval.</p><pre>const bar = () =&gt; setTimeout(() =&gt; console.log(&quot;Second&quot;)<br>, 0);<br>const foo = () =&gt; console.log(&quot;First&quot;);</pre><pre>bar();<br>foo();</pre><p><strong>Here First get log then Second </strong>The execution depends on the number of waiting tasks in the queue. The delay is the <em>minimum</em> time required for the runtime to process the request (not a <em>guaranteed</em> time).</p><h4>Execution of Promises</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*K34WRV6lB-JN5wYLFOJ_zw.png" /><figcaption>fig 3.1 promises</figcaption></figure><blockquote>In what order should the logs appear?</blockquote><blockquote>script start<br>script end<br>promise1<br>promise2<br>setTimeout</blockquote><blockquote>Why promise1 and promise2 get print before setTimeout?</blockquote><h4>ES6 Job Queue/ Micro-Task queue</h4><p>ES6 introduced the concept of job queue/micro-task queue which is used by Promises in JavaScript. M<strong>acrotask </strong>or just called the <strong>task queue</strong> is code which needs to be executed after execution stack is empty. Macrotask are non blocking in nature. <strong>setInterval, setImmediate, setTimeout, I/O tasks, DOM Manipulation use the macrotask queue </strong>to run their callbacks<strong>.</strong> <strong>Promises, MutationObservers, IntersectionObservers etc. use the microtask queue </strong>to run their callbacks.The difference between the message queue and the microtask queue is that the microtask queue has a higher priority than the message queue, which means that promise jobs inside the job queue/ micro-task queue will be executed before the callbacks inside the message queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*amvxdM3oz4BDUy-V.gif" /><figcaption>fig 3.2 Execution order</figcaption></figure><blockquote>sync tasks → micro tasks → macro tasks</blockquote><ol><li>All functions in that are currently in the call stack get executed. When they returned a value, they get popped off the stack.</li><li>When the call stack is empty, <em>all</em> queued up microtasks are popped onto the. call stack one by one, and get executed! (Microtasks themselves can also return new microtasks, effectively creating an infinite microtask loop ).<strong><em>Microstask also execute at the end of each macrotask </em></strong>.</li><li>If both the call stack and microtask queue are empty, the event loop checks if there are tasks left on the (macro)task queue. The tasks get popped onto the call stack, executed, and popped off!</li></ol><blockquote><strong>Microtask are kind of blocking in nature. Unlike macrotasks, the main thread will be blocked until microtask queue is empty.So if you keep queuing tasks in the microtask queue forever, your browser will become unresponsive. You can’t click a button, can’t scroll, nothing…, GIFs stop, animations stop etc.</strong></blockquote><p><strong>Example Explain</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*ToQPqRfpBk1NlpBm.gif" /><figcaption>fig 4.1 how promises work</figcaption></figure><p>Refer fig 4.1-On the first line, the engine encounters the console method. It gets added to the call stack, after which it logs the value start! to the console. The method gets popped off the call stack, and the engine continues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*DwUy1yS1DoYzqe0v.gif" /><figcaption>fig 4.2 how promises work</figcaption></figure><p>Refer fig 4.2-The engine encounters the setTimeout , which gets popped on to the call stack.its callback function will get added to the Web API, until the timer is done. Although we provided the value 0 for the timer, the call back still gets pushed to the Web API first, after which it gets added to the <strong>macrotask queue.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*IE6xgHSwX132LjXQ.gif" /><figcaption>fig 4.3 how promises work</figcaption></figure><p>Refer fig 4.3-The engine encounters the promise method. The promise method gets added to the call stack then its callback function will get added to the Web API . when promise resolve, its callback function gets added to the <strong>microtask queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*4y0hBh5y-BFsigM-.gif" /><figcaption>fig 4.4 how promises work</figcaption></figure><p>Refer fig 4.4-The engine encounters the console method. It gets added to the call stack immediately, after which it logs the value End! to the console, gets popped off the call stack, and the engine continues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*QtSyfEsyUKWOCxnV.gif" /><figcaption>fig 4.5 how promises work</figcaption></figure><p>Refer fig 4.5-The engine sees the call stack is empty now. it’s going to check whether there are queued tasks in the <strong>microtask queue</strong>! And yes there are, the promise then callback is waiting for its turn! It gets popped onto the call stack, after which it logs the resolved value of the promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*HMNxUG9rIjy30Cfn.gif" /><figcaption>fig 4.6 how promises work</figcaption></figure><p>Refer fig 4.6-The engine sees the call stack is empty, so it’s going to check the microtask queue once again to see if tasks are queued. Nope, the microtask queue is all empty.The setTimeout callback gets popped on to the call stack. The callback function returns the console method.The setTimeout callback get popped off the call stack.</p><h3>Conclusion</h3><p>So we have learned how asynchronous JavaScript works and other concepts such as call stack, event loop, message queue/task queue and job queue/micro-task queue which together make the JavaScript runtime environment.</p><p>That’s it and if you found this article helpful, please click the clap 👏button, and if you have any doubt, feel free to comment! I’d be happy to help .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c8de41298dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/asynchronous-javascript-event-loop-1c8de41298dd">Asynchronous Javascript (Event Loop)</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks]]></title>
            <link>https://medium.com/gradeup/react-hooks-d23402bf9c12?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d23402bf9c12</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[usecallback]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 10:21:33 GMT</pubDate>
            <atom:updated>2023-08-12T18:07:06.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn React Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*XmlRdy-RyRVeUgoZ" /></figure><p>Hooks are a new addition in React 16.8. They allow us to use React features without writing a class based components. There are 3 Basic Hooks and other hooks are either variants of the basic ones , or only needed for specific edge cases.</p><p>In this article we cover almost all hooks.</p><ul><li>useState</li><li>useEffect</li><li>useContext</li><li>useReducer</li><li>useMemo, React.memo</li><li>useCallback</li><li>useRef, callbackRef, forwardRef</li><li>useImperativeHandle</li><li>useLayoutEffect</li><li>useDebugValue</li></ul><h3><strong>BASIC HOOKS</strong></h3><h4><strong>1. useState</strong></h4><p>Returns a stateful value, and a function to update it</p><pre>const [state, setState] = useState(initialState);</pre><p>The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.If your update function returns the exact same value as the current state, the subsequent re render will be skipped completely.The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded (fig 1.2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*DQbG9qrmeiBSAp72SD3dQA.png" /><figcaption>fig 1. 2 useState</figcaption></figure><h4><strong>2. useEffect</strong></h4><p>The function passed to useEffect will run after the render is committed to the screen.useEffect Hook can express all combinations of these <strong><em>componentDidMount, componentDidUpdate, componentWillUnmount.</em></strong></p><pre>useEffect(didUpdate);    useEffect(()=&gt;{},[dependencies])</pre><p>If we write the useEffect without square brackets then the function passed to useEffect will run on every render.</p><blockquote>initial rendering happens before mounting. Rendering returns the elements which are supposed to be mounted in the DOM. Mounting a react component means the actual addition of the DOM elements created by the react component into the browser DOM for the first time.The main difference between mounting and rendering is that mounting happens once, but rendering can happen any number of times.</blockquote><ul><li>Function Passed to useEffect will run on every re render if no dependency is passed (fig-2.1).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*pdfoOUHzujar5RP-_vbU3g.png" /><figcaption>2.1 useEffect without dependency</figcaption></figure><ul><li><strong>componentDidMount and componentWillUnmount </strong>If dependency is an empty array then it will behave like componentDidMount and componentWillUnmount (fig- 2.2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*i1BJ8ClS-uTpVSlhp0Qdng.png" /><figcaption>2.2 useEffect mount and unmount</figcaption></figure><ul><li>if we only want to re render the component in change of any state or prop then pass the state or prop in dependency array (fig 2.3).</li><li><strong>componentDidUpdate </strong>sometimes we want the function to run only on update not on mount then we can write like fig 2.3. Here <strong>Did Update</strong> will only log when ‘click’ change its value. it will not print in its first render.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*OHcUN9vDvj3kQNqxLC8Lmg.png" /><figcaption>2.3 useEffect did update</figcaption></figure><blockquote>if we pass object , array and function in dependency then the function passed to useEffect will run on every render. Object reference will change on every re render.</blockquote><h4><strong>3. useContext</strong></h4><p>Context provides a way to pass data through the component tree without having to pass props down manually at every level like <strong><em>user, theme, or preferred language.</em></strong></p><pre>const value = useContext(MyContext)<br>const ContextName = React.createCotext(initialvalue);</pre><p>When the nearest &lt;MyContext.Provider&gt; above the component updates, this Hook will trigger a re render with the latest context value. Here theme object is passed as a context. we can access its value without manually passing the props at every level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*I4S6Ey6JJVQwdYxxWEcdRA.png" /><figcaption>fig 3.1 useContext</figcaption></figure><h3><strong>Other Hooks</strong></h3><h4><strong>4. useReducer</strong></h4><pre>const [state, dispatch] = useReducer(reducer, initialArg, init);<br>(state, action) =&gt; newState</pre><blockquote>Why useReducer, If useState can also update the State</blockquote><p>when there is<strong> </strong>complex state logic that involves multiple sub-values or when the next state depends on the previous one and also to optimise the performance that has deep updates because we can pass <strong>dispatch</strong> down instead of callbacks. Dispatch reference will not create on every re render but callback reference will create in each re render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*GRoGlibmNa3Fm9Cp30IOEw.png" /><figcaption>fig 4.1 useReducer</figcaption></figure><ul><li><strong><em>Use useState whenever you manage a JS primitive</em></strong></li><li><strong><em>Use useReducer whenever you manage an object or array</em></strong></li></ul><blockquote><em>sometimes we want to manage the state at top-level but want to trigger state changes somewhere deep down in our component tree. It’s possible to pass both the updater function from useState or the dispatch function from useReducer as a props in component tree but using </em><strong><em>context</em></strong><em> may be a better alternative to avoid prop drilling (passing props through each component level). In that case, having one dispatch function with different action types and payloads may be a better option than using multiple updater functions from useState that must be passed down individually. The dispatch function can be passed down once with useContext Hook.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MFYAFsChqCKtV77C" /><figcaption>fig 5.0 optimisation</figcaption></figure><p>React.memo , useMemo and useCallback hooks are used for optimisation. Their motive is to prevent unnecessary renders.</p><p><strong>React.memo </strong>similar to pureComponent in class components and used for a performance boost in some cases by memoizing the result. This means that React will skip re rendering the component, and reuse the last rendered result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*GvQqqjiTSWFH4f8zF1po8Q.png" /><figcaption>fig 5.1 React.memo</figcaption></figure><p>In fig 5.1 we update the value of count1 and component will re render but one thing you notice , &lt;Count&gt; does not use ‘click’ state but &lt;Count&gt; still re render because React Says that if parent re render then its child also re render until we used any optimisation. In order to prevent the re rendering of &lt;Count&gt; we can use React.memo. It checks for props changes and will skip re rendering the component if props value are same. In this example &lt;Count&gt; will not re render if we use React.memo.</p><blockquote>If we pass object, array or function as a prop then React.memo will not work because their new reference will create on each re render and React.memo uses reference equality to prevent unnecessary renders.</blockquote><h4><strong>5. useCallback and useMemo</strong></h4><pre>const memoizedCallback = useCallback(<br>  () =&gt; {<br>    doSomething(a, b);<br>  },<br>  [a, b],<br>)<br>const memoizedValue = useMemo(() =&gt; computeExpensiveValue(a, b), [a, b]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*fJZHLWFJZ9idIxRdlNK4Rw.png" /><figcaption>fig 5.2 useCallback and useMemo</figcaption></figure><p>In fig 5.2 you can see that the main difference is , React.<strong>useMemo</strong> will call the Function and return its result while React.<strong>useCallback</strong> will return the function without calling it .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Pti14VbRQNiUZfq54ZwnkQ.png" /><figcaption>fig 5.3 useCallback</figcaption></figure><p>In fig 5.3 Function is passed as a prop in &lt;Actions&gt; and on changing the state of ‘check’ &lt;Actions&gt; will re render . In this case we can not use React.memo because new reference of function will generate on each re render. we want that the function reference will not create until some dependency will change.If function is pass in <strong>useCallback</strong> then the function reference will not generate. Function reference will only generate if any state or props passed in the dependency array will change.</p><p><strong>useMemo </strong>returns memoized value.Imagine that you’ve got a function that synchronously calculates a value which is computationally expensive to calculate.With useMemo, we never have to calculate the same value twice .we can use same value again until dependencies array’s values will change. If our dependencies array is empty, there is no possibility of memoization and it will compute a new value on every render.</p><h4><strong>6. useRef</strong></h4><p>It can used as a way to access the DOM. If we pass ref object to React with &lt;div ref={myRef} /&gt;.useRef can persist a value for a full lifetime of the component.</p><pre>const refContainer = useRef(initialValue);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*YAeABDOyRt3y8-dv9niYEQ.png" /><figcaption>fig 6.1 question</figcaption></figure><p><strong>Here question is if createRef exist then why there is need for useRef.</strong></p><blockquote><strong>createRef</strong> will return a new ref on every render.Every invocation of createRef will generate a new object. It is perfect for a class component’s constructor.while <strong>useRef</strong> will return the same ref each time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*TVTsoi4S5qX8ZuXNbewJdQ.png" /><figcaption>fig 6.2 useRef</figcaption></figure><p>In fig 6.2 on click we set the current property of ref and component will not re render that means useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render.</p><p>We can use <strong>useCallbackRef</strong> , the callback ref will be invoked when a component mounts and be set to null when the component un mounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TQMwdq8a2zbpkFLNvDQYyQ.png" /><figcaption>fig 6.3 useCallbackRef</figcaption></figure><p>In fig 6.3 ‘ref set’ will log when &lt;input&gt; added to DOM and will log again when &lt;input&gt; tag unmount.</p><p><strong>useImperativeHandle </strong>before this we need to know about <strong>useForwardRef.</strong></p><blockquote>can we pass ref as a prop?</blockquote><blockquote>No, ref is a reserved word like key. We can’t pass it like a prop. Ref forwarding is a technique for automatically passing a ref through a component to one of its children. In fig 7.1 we create a ref in &lt;Hello&gt; and pass it to &lt;RefCom&gt; using forwardRef.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*gCz0vGjHDHoxzy7XluHwdA.png" /><figcaption>fig 7.1 forwardRef</figcaption></figure><h4><strong>7. useImperativeHandle</strong></h4><p>It should be used with forwardRef.Expose limited DOM methods (such as select, focus, click, etc.) to callers and provide normal methods to callers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*98ZwYIIxPyyK3j5Pg8Squg.png" /><figcaption>fig 7.2 useImperativeHandle</figcaption></figure><p>In fig 7.2 we can use extra function log() using useImperativeHandle i.e It customises the instance value that is exposed to parent components when using ref .use useImperativeHandle to expose a handle with only the methods that you want the parent component to call. We should only use refs for <em>imperative</em> behaviors that you can’t express as props: for example, scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.</p><h4><strong>8. useLayoutEffect</strong></h4><p>If you need to mutate the DOM and do need to perform measurements.Your code runs immediately after the DOM has been updated, but before the browser has had a chance to “paint” those changes.</p><blockquote>Difference between useEffect and useLayoutEffect?</blockquote><p><strong>Only differs in when it is fired</strong>.The function passed to useEffect fires <em>after layout and paint</em>, during a deferred event.The function passed to useLayoutEffect fires<em> before paint</em> like componentDidMount<strong><em>.</em></strong></p><h4><strong>9. useDebugValue</strong></h4><p>The main purpose of this hook, is to help with debugging.It works with React Developer Tools to show the value of the hook that is useful for us to understand the state of the Component that our hook is managing</p><pre>useDebugValue(value, [optional formatting function]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*_NUfFXsH_FPImIwpnQMn_w.png" /><figcaption>fig 9.1 useDebugValue</figcaption></figure><p>In fig 9.1 second is not correct way because formattedDate value will always calculate.useDebugValue function is only called if the Hooks are inspected. It receives the debug value as a parameter and should return a formatted display value.</p><h3>Last words</h3><p>Feel free to convert Class based component to React Hooks. Make your code more readable, optimised and short. Please let me know if something isn’t clear, and I’d be happy to chat about your concerns.</p><p><em>Thanks for Reading !!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d23402bf9c12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/react-hooks-d23402bf9c12">React Hooks</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truecaller Integration Guide for M-web]]></title>
            <link>https://medium.com/gradeup/truecaller-integration-guide-for-m-web-b6fbd6377ec?source=rss-5f3c7140e57d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fbd6377ec</guid>
            <category><![CDATA[truecaller]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Ishika Gupta]]></dc:creator>
            <pubDate>Mon, 19 Aug 2019 06:13:14 GMT</pubDate>
            <atom:updated>2019-08-19T06:38:30.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pb1jXoB9RssJaTj6joyg_A.png" /></figure><h3>Problem</h3><p>It is important to validate a user either through email or phone. But phone verification is more effective than email. It is easier to create a lot of fake accounts than creating a fake phone number. Conventionally, we use the following techniques for verification :</p><ul><li>OTP (One Time Password)</li><li>Missed Call</li></ul><p>But it is a multi-step process and it breaks the user flow. One solution is, we can use <em>Truecaller SDK </em>which is free and can verify user in just one tap.</p><h3>Steps to integrate Truecaller</h3><p>you can find official documentation on <a href="https://truecaller4developers.gitbook.io/truecallersdk/mobile-websites/implementing-user-flow-for-your-mobile-website">https://truecaller4developers.gitbook.io/truecallersdk/mobile-websites/implementing-user-flow-for-your-mobile-website</a></p><ol><li>Register on <a href="https://developer.truecaller.com/dashboard">https://developer.truecaller.com</a></li></ol><p>2. Create app (Refer fig 1.1) for Web</p><figure><img alt="Fig 1.1" src="https://cdn-images-1.medium.com/max/1024/1*OXQongARW63a3Q61cpdtBg.png" /><figcaption>fig- 1.1</figcaption></figure><blockquote><em>Callback URL </em>corresponds to an endpoint of backend where truecaller will post the access token for us to fetch the user’s profile. Every access token can be used to fetch the profile only of the related user granting the authorization to our app.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZbYnx136jNf6q9QRMeAaw.png" /><figcaption>fig-1.2</figcaption></figure><p>3. Use generated app key (refer fig-1.2) in partner Key of Truecaller’s Deep link’s(refer fig-1.3)</p><blockquote><em>RequestNonce</em> should be a unique requestID that you need to associate with every verification request you trigger. The minimum length of the request ID parameter should be 8 characters and maximum length can be 64 characters</blockquote><blockquote>You can use userid in requestNonce , to indicate that this request id belongs to particular user.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*qt_9BwhZ2N9_gyyCgOYG5g.png" /><figcaption>fig-1.3 . truecaller’s deeplink</figcaption></figure><p>4. Truecaller’s deeplink (refer fig 1.3) pops up this modal, (refer fig 1.4) if truecaller is present in user’s mobile else we can use another method for verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*Rv7j-toQZPfmWydEObln9Q.png" /><figcaption>fig 1.4</figcaption></figure><p>5. If user clicks on “continue” or “ use another mobile number”(refer fig 1.4) then truecaller posts request id and access token to callback URL and backend will use this access token to fetch user’s profile by making API call to end point.</p><p>6. Once User’s profile is at backend we need to setup a proper communication mechanism between frontend and backend. We can use these methods for this purpose.</p><ul><li><strong>polling</strong> we can make a long polling request or make a specific number of periodic requests [ say every 3 seconds ] to our backend to check if the user’s profile data has reached our backend or not. This kind of request can hold until a particular threshold time so that it waits for the profile response from your server.</li><li><strong>subscription</strong> we establish a two-way, persistent connection between our client and the server. server push data back to client when event happens on server(user’s profile fetch)</li></ul><p><em>We can use any method according to our requirement.</em></p><h3>Using Subscription (GraphQl)</h3><p>you can find official subscription’s documentation on <a href="https://www.apollographql.com/docs/react/advanced/subscriptions/">https://www.apollographql.com/docs/react/advanced/subscriptions</a></p><ol><li>Initialise web socket link for two way persistent connection.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*w1PfzbqC2LSbIi3NmhoDGg.png" /><figcaption>fig- 1.5</figcaption></figure><blockquote>Note : use ‘wss’ for Web host because it use https</blockquote><p>2. Write GraphQl query for subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*zv52tO-Bl0IZbfZENEOdXg.png" /><figcaption>fig 1.6</figcaption></figure><p>3. Once the user’s profile is fetched, server pushes the data to client and onSubscriptionData(refer fig 1.7) will be triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*FKCF0chiYbMCmkrdQXtG8w.png" /><figcaption>fig 1.7</figcaption></figure><p>4. You can use this subscription data(refer fig 1.7) as per your requirement.</p><blockquote>Note : Make two apps in developer.truecaller.com. One for localhost, and the other for web host because domain name is different. Two app keys will be generated. Don’t forget to change the app key while hosting.</blockquote><h3>Last words</h3><p>If you find other issues and you figure out how to fix them, let me know and I will update this guide.</p><p><em>Thanks for Reading !!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fbd6377ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gradeup/truecaller-integration-guide-for-m-web-b6fbd6377ec">Truecaller Integration Guide for M-web</a> was originally published in <a href="https://medium.com/gradeup">BYJU’S Exam Prep Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>