<?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 James Dockeray on Medium]]></title>
        <description><![CDATA[Stories by James Dockeray on Medium]]></description>
        <link>https://medium.com/@james-dockeray?source=rss-f4631e424964------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HHJfQ4kn8sszrLW03dNBPA.jpeg</url>
            <title>Stories by James Dockeray on Medium</title>
            <link>https://medium.com/@james-dockeray?source=rss-f4631e424964------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:24:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@james-dockeray/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[Five Lessons Learned from Implementing OpenTelemetry]]></title>
            <link>https://james-dockeray.medium.com/five-lessons-learned-from-implementing-opentelemetry-50154645ca6c?source=rss-f4631e424964------2</link>
            <guid isPermaLink="false">https://medium.com/p/50154645ca6c</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <dc:creator><![CDATA[James Dockeray]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 09:59:26 GMT</pubDate>
            <atom:updated>2025-01-24T10:02:01.340Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover five key lessons from implementing OpenTelemetry in micro services.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBQQqDBmnnnBt2ZeSjgMbA.jpeg" /></figure><p>We set out to implement Open Telemetry (OTel) across our microservices running on Kubernetes. OTel is a Cloud Native <a href="https://www.cncf.io/projects/">incubating project</a>. Otel originated from the merger of two earlier open-source projects focused on observability: <a href="https://opentracing.io/">OpenTracing</a> and <a href="https://opencensus.io/">OpenCensus</a>. Today, it forms a collection of open-source APIs, SDKs, and tools that you can use to instrument software behaviour and performance.</p><p>Here are five lessons learned along the way.</p><h3>1: One Schema To Rule Them All</h3><p>Initially, we wanted to implement a shared logging schema across our services. We considered the<a href="https://www.elastic.co/guide/en/ecs/current/index.html"> Elastic Common Schema</a> and<a href="https://opentelemetry.io/docs/specs/semconv/"> Semantic Conventions</a>. Elastic has donated the Elastic Common Schema to the OTel project to create one standard open schema.</p><p>Semantic Conventions are great once you know how to use them, but initially, the documentation can feel overwhelming. OTel gives you lots of choices in how you use it. It is beneficial to look at some of the example projects and read through the<a href="https://github.com/open-telemetry/opentelemetry-specification/blob/v1.31.0/specification/logs/data-model.md"> specifications</a> in the GitHub repo (I found this more straightforward than going through the documentation on the website).</p><h3>2: Not All Observability Backends Are Equal</h3><p><a href="https://www.datadoghq.com/">Datadog</a>,<a href="https://www.dynatrace.com/"> Dynatrace</a>,<a href="https://sentry.io/welcome/"> Sentry</a>,<a href="https://sentry.io/welcome/"> Elastic Cloud</a>,<a href="https://grafana.com/"> Grafana</a>,<a href="https://opensearch.org/"> OpenSearch</a>,<a href="https://aws.amazon.com/cloudwatch/"> and CloudWatch are just</a> a few of the many Software as a Service (SaaS) observability products on the market. While they may superficially offer similar services, delving into their different offerings can save you time in the long run.</p><p>My current experience is using GrafanaCloud and OpenSearch. Both tools support log aggregations and Application Performance Monitoring (APM). The APM and tracing features function more smoothly in Grafana Cloud. Additionally, Grafana Cloud offers native support for the OpenTelemetry Protocol (OTLP). Grafana Cloud bills on usage, and in OpenSearch, you are charged based on a fixed compute cost.</p><h3>3: All Roads Lead to the Otel Collector</h3><p>The OTel Collector is a spaghetti junction for your telemetry data, streamlined through easy-to-use YAML configuration. It can scrape Prometheus endpoints, format log files, and receive data in various schemas. Additionally, it provides debugging tools with features like<a href="https://github.com/open-telemetry/opentelemetry-collector/blob/main/extension/zpagesextension/README.md"> zPages</a>. Exploring its full capabilities is highly encouraged, as many more functionalities are available.</p><h3>4: The Devils in the Detail</h3><p>It is not always clear what the hurdles will be before implementation. An example of an unexpected challenge that came up in the implementation phase is that the observability backend we used, OpenSearch, does not directly ingest telemetry data formatted in Semantic Convention schema; it requires conversion to the <a href="https://opensearch.org/docs/latest/observing-your-data/ss4o/">Simple Schema for Observability (SS4O) </a>that is part of the OpenSearch project. OpenSearch offers tools like Data Prepper to facilitate the ingestion of OpenTelemetry data into SS4O format. However, using tools to convert between schemas clashes with the OTel portability principle. In the future, I will prioritise backends that natively support Semantic Convention ingestion over OTLP.</p><h3>5: Beware Burdening Engineering Teams</h3><p>There are various methods to deploy OpenTelemetry. We chose to use <a href="https://opentelemetry.io/docs/collector/deployment/agent/">agents</a> that export logs directly from our application via OTLP. This approach eliminates the need for an intermediary, is portable due to minimal supporting infrastructure requirements, and is well-suited for cloud functions. Additionally, it provides greater control over the structure of our telemetry data since we are exporting directly from the source.</p><p>However, integrating agents into the applications adds cognitive load for engineers, as they are responsible for installing and maintaining the code. I recently realised that one of the principles of the twelve-factor app states, “a twelve-factor app never concerns itself with routing or storage of its output stream.” In hindsight, using a pull approach — where logs are written to stdout and collected by external agents — may be more advantageous. This method reduces the burden on engineering teams and accelerates the process of collecting logs.</p><p><strong>Closing Thoughts</strong></p><p>I will use OTel again and follow the project closely. In the future, I hope that more observability backends support OTLP because integrating with OpenSearch was not as seamless as I hoped. OTel helped the team achieve a unified approach to application observability using vendor-agnostic tooling to capture logs, traces, and metrics.</p><p><em>This </em><a href="https://content.red-badger.com/resources/five-lessons-learned-from-implementing-opentelemetry"><em>article</em></a><em> was initially published on the Red Badger website.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50154645ca6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rock Around the Clock: Part 1: The Diffie-Hellman Key Exchange]]></title>
            <link>https://james-dockeray.medium.com/rock-around-the-clock-part-1-the-diffie-hellman-key-exchange-e3324d0a2e04?source=rss-f4631e424964------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3324d0a2e04</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[James Dockeray]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 10:34:13 GMT</pubDate>
            <atom:updated>2023-11-11T10:39:25.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCh5ejC7yxQbbCsUGO1bkA.jpeg" /></figure><p>In this article, I will discuss the Diffie-Hellman Key Exchange (DFKE), a public key algorithm based on Discrete Logarithm Schemes. Other examples of such algorithms include ElGamal encryption and the Digital Signature Algorithm.</p><p>I will start by providing the historical context of DFKE and explaining how it works, showcasing how simple mathematics can lead to powerful ideas. Finally, I will summarise some key points on group theory and its relationship with the discrete logarithm problem (DLP).</p><h4><strong>Background</strong></h4><p>The dawn of the computer age at Bletchley Park ushered in a new era of cryptanalysis. In the 1960s and 1970s, innovative forms of symmetric-key encryption, such as the Data Encryption Standard (DES), made strong encryption a part of everyday life. However, although the algorithms were unbreakable, a problem remained regarding how to share keys used for encryption and decryption. Every link in the transportation chain was a possible attack vector.</p><h4><strong>Humpty Dumpty Functions</strong></h4><p>Whitfield Diffie and Martin Hellman developed an asynchronous key exchange protocol that relied upon one-way functions to securely transmit a key without interception. The correct one-way process would be easy to compute but difficult to undo. The analogy of mixing paint is an excellent way to think about a one-way function. Whilst it is simple to mix colours together to create new colours, it is hard to reverse this process to see what colours were combined to create the colour.</p><p>One way functions have been nicknamed ‘Humpty Dumpty functions’ after the well-known nursery rhyme because once Humpty falls down, ‘all the king’s horses and all the king’s men, couldn’t put Humpty back together again’.</p><p>Modular mathematics, also known as clock arithmetic, is a branch of mathematics widely used in computer science and has a specific relevance in cryptology. It is rich in one-way functions, making it a valuable tool for encryption and decryption. Modular functions follow particular laws that allow for predictable results when used by the sender and receiver. These functions are commutative, associative, and distributive. The DFKE is one example of an encryption algorithm that uses modular mathematics. Additionally, modular functions are also used in integer factorization schemes like RSA.</p><h4><strong>The Diffie-Hellman Key Exchange</strong></h4><p>Let’s break down the DFKE to understand it better. Let’s use the colour analogy we used in the previous section to simplify things. It’s also the right time to introduce Alice and Bob.</p><p>Alice and Bob are fictional characters often used in thought experiments related to cryptography. They first appeared in the paper introducing RSA asymmetric cryptography, ‘A Method for Obtaining Digital Signatures and Public-key Cryptosystems’. In DFKE, Alice and Bob need to exchange a message, which is a cryptographic key.</p><p>We also need to add another character to the story, and her name is Eve. Eve is a passive attacker who wants to listen to Alice and Bob’s communication and steal the message. A passive attacker in network security is an attacker who tries to break a system based on observed data.</p><h4>A Colourful Conceit</h4><p><strong>Phase 1: The setup</strong></p><p>During the first phase of DFKE, Alice and Bob will agree to use two numbers over an insecure channel. To use a mixing paint analogy, they would choose two colours, such as blue and yellow. However, as the line is insecure, Eve also takes note of the values.</p><figure><img alt="Alice, Bob and Eve plus the values Y and P" src="https://cdn-images-1.medium.com/max/156/0*Cxf-qqy3sk5GRra2" /></figure><p><strong>Phase 2: The exchange</strong></p><p>Next, Alice and Bob pick their secret colour; in the diagram below, I labelled them A and B. They will not share these values with anyone:</p><figure><img alt="Alice and Bob and their secret colours" src="https://cdn-images-1.medium.com/max/232/0*J_1Dc8Y9j1Py-onD" /></figure><p>Alice and Bob both need to create a colour that can be shared. They blend the initial values Y and P with their secret colours, A and B. This results in Alice having the colour AYP and Bob having BYP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*Hx1H--Yt-xQADDln" /></figure><p>Now, Alice and Bob can exchange AYP and BYP. Eve can listen but cannot deduce A and B.</p><figure><img alt="Alice and Bob exchanging public numbers with eve listening" src="https://cdn-images-1.medium.com/max/439/0*xwatCwvFMVAyfneh" /></figure><p>Finally, Alice and Bob add their secret to the exchanged value:</p><figure><img alt="Alice and Bob mix their colour to get the same colour" src="https://cdn-images-1.medium.com/max/413/0*r4vfX7-gVz6haBia" /></figure><p>Alice and Bob have successfully exchanged values over an insecure communication line and ended up with the same secret key. The reason for this is that both keys are constructed by using the same colours. This is an example of the power of one-way functions, as Eve, who does not know A and B, would have no way of deriving the key.</p><h4>I’ve got your number</h4><p>It’s time to show how modular arithmetic makes this possible, starting with phase 1. Instead of two colours, Alice and Bob choose a large prime for Y and a number less than Y for P. Here are the steps</p><p><strong>Diffie-Hellman Set-up</strong></p><ul><li>Choose a large prime Y</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*Mx-XGlCy8kgEOpv-" /></figure><ul><li>Choose an integer P less than Y. P should also be a primitive element to Y.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*yBIoOLrbxFjWVQi8" /></figure><ul><li>Publish P and Y</li></ul><p>The parameters P and Y are sometimes referred to as the domain parameters. Once the domain parameters have been agreed upon, Alice and Bob can generate the secret key using the following technique:</p><p><strong>Diffie-Hellman Exchange</strong></p><ul><li>Alice and Bob both choose numbers <em>a</em> and <em>b</em> that are less than the large prime <em>Y</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*bLlKf7VE60gSXgRR" /></figure><ul><li>Alice and Bob now calculate <em>P </em>to the power of their numbers and work out the modulo of <em>Y. </em>Alice stores the result in a variable called aδ and Bob stores the result in a variable called <em>b</em>δ<em>:</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/0*CxgrR_KfkmNfvrFV" /></figure><ul><li>Alice and Bob can now exchange aδ and bδ.</li><li>Alice and Bob raise the exchanged numbers to their private ones and calculate the modulo:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/0*hlcGrV7OpjOKWhi5" /></figure><p>This works because modular arithmetic is commutative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*SuaVCpohEzFaBTaj" /></figure><p>To help illustrate this, let’s take out the modulo Y from the equations and work through an example using the most minor possible numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*7kG7ZxN3tq6jon2d" /></figure><p>As we took out the modulo we are now just calculating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/0*3Zj8Z4rwAacpiXsM" /></figure><p>If we add back in the modulo operator we still have the same commutative relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*yFPGFz_nCsq2R7xg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*81-aD3A1l0rUWvNi" /></figure><p>It may seem like we don’t need the modulo group. If Eve wants to steal Alice and Bob’s numbers, she can easily reverse-engineer them. In the first case, if Eve knows that aδ is (2³) = 8, to calculate a, she would simply work out 3 = log2 8. In the second example, if Eve knows that aδ is 7^a mod 11 = 2, she would need to run through powers of P mod 11 until she arrives at 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*4Wc50GiqG1sQiPoN" /></figure><p>Both examples are equally insecure. When dealing with the set of all numbers, some strategies allow for the logarithm to be quickly computed even for large numbers. However, for a large prime number Y and a number P that is primitive to it, there is no easy way to compute the logarithm for the set of numbers of powers of P mod Y. This is commonly known as the discrete logarithm problem.</p><h4><strong>The Discrete Logarithm Problem</strong></h4><p>The discrete logarithm problem is a mathematical concept that falls under group theory. To better understand this problem, let me first provide examples of finite cyclic groups and their properties, such as the generator and identity element.</p><p>A group in maths is a group of numbers and an operator that abides by specific rules. An additive group uses the additive operator, and a multiplicative group uses the multiplication operator. We will look at multiplicative groups. The multiplicative group of powers 2’s would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/0*4ydZoPYn9brbm6Ae" /></figure><p>Cryptography is primarily concerned with bounded groups. A group is said to be bounded when its elements are constrained within a given range. An example of a bounded group is the additive group mod a number n, denoted as (Z/nZ). Here’s an example of how this group works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*v5AFGBcpSCoSEJ3r" /></figure><p>The cardinality of a group is the maximum number of unique elements. In the group above, the cardinality would be 2. The order of a group is the number of times the group operation needs to be executed to return the identity element. In group theory, the identity element (or neutral element) is the unique element in a group that, when combined with any group element using the group operation, results in the same element. The identity element is practical when finding the order of an element in a group. To find the order of an additive group, you calculate <em>n </em>multiplied by <em>e </em>until the result equals 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*_LyMa95Jt17-25xS" /></figure><p>The identity element of multiplicative groups is 1. To find the order for a given element we raise that element to incrementing powers until we reach 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*fyW2jjnQEcshPnAT" /></figure><p>So, the order of 2 in the multiplicative group mod 5 is 4 as 2⁴=1. An attractive property of this group is that it contains all the natural numbers of mod 5 (1, 2, 3, 4), and it generates them in a seemingly random order. A number that generates all group members is known as a <strong>generator or primitive element</strong>.</p><p>Euler’s totient function, or phi (φ) function is a way to find the maximum order of a group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*6xvu5yikHCpLnVGJ" /></figure><p>For any given group, if the operator is modulo a prime number, it will have an order of that number minus one. Prime numbers always contain at least one number that generates the entire group. For example, we saw that with number 5, the powers of 2 mod 5 generated the whole group. Groups formed by calculating the mod of a prime number are called prime fields.</p><p>Another attractive property of these groups is that the order of the subgroups within them will contain orders that are divisors of the order of the group. For example, 5 has an order of 4, and multiples of 4 are 1, 4 and 2. So we know that the order of the subgroups will be 1, 4 and 2. We can prove this out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*3l0C7fB0Q7aiSzNg" /></figure><p>Here, we can see that for mod 5, we have groups of order 1 (powers of 1), groups of order 4 (powers of 2 and 3) and groups of order 2 (powers of 4).</p><p>These cyclic subgroups have a particular property. If a cyclic subgroup has φ(order), which is prime, then every group member that is not 1 will be a generator for that group.</p><p>The discrete logarithm problem states that given a finite cyclic group over a prime field and a primitive element of that group as well as another number. Calculate the primitive element raised to that number mod the field’s prime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3324d0a2e04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construct Binary Tree from Inorder and Postorder Traversal]]></title>
            <link>https://james-dockeray.medium.com/construct-binary-tree-from-inorder-and-postorder-traversal-2d88b7b4eba4?source=rss-f4631e424964------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d88b7b4eba4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[James Dockeray]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 17:15:52 GMT</pubDate>
            <atom:updated>2025-01-24T10:05:56.686Z</atom:updated>
            <content:encoded><![CDATA[<p>Solving <a href="https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/">leetcode 106</a></p><h4>The Problem</h4><blockquote>Given two integer arrays, inorder and postorder, where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.</blockquote><h4>Quick Recap</h4><p>In case you have forgotten, inorder traversal visits nodes by visiting the left, parent and then the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PricG1cyF88eYuh5NCsHLg.png" /></figure><p>In contrast, postorder traversal visits the left and right children and then the parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_LEQw2ndMVKQLLecSc3pA.png" /></figure><p>The above diagrams show the completed trees; we only receive the visited lists as inputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0tdx4g5EouwvQOQPCm-pw.png" /></figure><h4>Getting Started</h4><p>Let&#39;s start by exploring the problem domain with a simple input list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxjDDUGD1O0wrI9WKY850A.png" /></figure><p>If the list represents a postorder collection, it will visit the children first and then the parent. So from the simple example, we can tell that the tree is a parent node with one child. However, we cannot know whether the tree has a right or a left child. So assuming the list is in postorder, then the following trees are possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMW5wIn2hbkjm2w3wRVO5g.png" /></figure><p>Similarly, If the list is inorder, the tree&#39;s shape is one parent with a single child. However, unlike in postorder, we have no way of knowing which one is the parent, as can be seen by looking at the possible combinations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YS3Sne2i4b1S4D4uW8NjQ.png" /></figure><p>To conclude, with <strong>postorder:</strong></p><ul><li>We <strong>can</strong> Find the parent and child.</li><li>We <strong>cannot</strong> discern what side the child is on.</li></ul><p>And with <strong>inorder</strong>:</p><ul><li>We <strong>can</strong> find the side if we know the parent.</li><li>We <strong>cannot </strong>know to tell the parent and child apart.</li></ul><p>Now let&#39;s combine these findings. The postorder findings give the parent, applied to inorder gives us the side of the child node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMDpLezLBikX7Cn1zQNnqQ.png" /></figure><p>So using this simple example, we have proven that it is possible to calculate the tree&#39;s shape if we have both inorder and postorder lists. In the next section, I will collate these findings to show the solution to the problem.</p><h3>Solution</h3><p>In the last section, we showed where to find the parent node in a postorder list, which is always the last node visited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DbX91KArQam7A1uego0Lw.png" /></figure><p>In list form, this looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzyHYjCgP45zYRm58zNXGQ.png" /></figure><p>If we know the length of the left and right groups, postorder always visit them in the order of all the left nodes, then all the right nodes and finally the highest parent node. In the left and right groups, the last node is always the highest and so will be the direct child of the parent you are comparing to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed6v3y5HR3XXvAIAsQMJXA.png" /></figure><p>You can use inorder to find the size of the left and right groups. This is because inorder traversal always visits the highest node between the left and right sides, as we can see in this tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAlu_cqQ9fbVK-UJyURZcw.png" /></figure><p>In list form, this looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_LhRQJACtmeSWl0yYhrRw.png" /></figure><p>As we can see, we have two groups, which we can now use in the postorder list to find the parent&#39;s direct left and right child, as once you know how big the left and the right group is, the immediate child is always the last node of that group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCtgEB4hXz5K2dTTV8w3NA.png" /></figure><p>The above algorithm outlines the steps needed to calculate any tree node&#39;s children. To find the right children on the right side of the root node, you take the right groups of both inorder and postorder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrjmfmrJ8Wie7TC5qR0edQ.png" /></figure><p>Now the highest node is C (the most right node of post order)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61g3IKclNtGOkW0dC5PJ5Q.png" /></figure><p>To find the children, we use inorder to split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7R4Oe0JdHWNWMtkXLar2Q.png" /></figure><p>And reapply to postorder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiIv_Z66v-yA-IinICbcVw.png" /></figure><p>This allows us to draw in the children into the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pw_i7pcbFRsZIXXQ0TdPxw.png" /></figure><p>As the left and right groups for the next level are of size one, they must be leaf nodes, so the tree&#39;s right side must be complete.</p><p>The exact process applies to find the top node&#39;s left side. Start by taking the left groups:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOcGodm7FO4TdkelnKE93g.png" /></figure><p>Use postorder to identify the current node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqflcpRO6m4g1pxac9yhlg.png" /></figure><p>Use inorder to split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNGHjajYBKpOMgnNMuZNnA.png" /></figure><p>At this point we can reapply to postorder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4as8QROsVeFMi0es3joohQ.png" /></figure><p>That last step isn&#39;t strictly needed, as we know that there is only one node. However, the rules we have outlined work for any length so its better to be consistent.</p><p>Now we are ready to complete the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3VU7XDRkZiOPoZKyj7svA.png" /></figure><p><strong>Appendix</strong></p><p>To show how this works in code, I have added my Java solution below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4c3fdb1c5e56c9a6605e16590013139/href">https://medium.com/media/c4c3fdb1c5e56c9a6605e16590013139/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d88b7b4eba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manual Mocks in Jest]]></title>
            <link>https://james-dockeray.medium.com/manual-mocks-in-jest-c4d00f415b3b?source=rss-f4631e424964------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4d00f415b3b</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[James Dockeray]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 09:02:31 GMT</pubDate>
            <atom:updated>2022-08-22T15:58:06.989Z</atom:updated>
            <content:encoded><![CDATA[<h4>Level up your unit tests</h4><p><strong>Table of Contents<br></strong>– <a href="#f7c4">Intro</a><br>– <a href="#1af4">Jest Mock Method</a><br>– <a href="#f36f">The Mocked Function Object</a><br>– <a href="#6cc4">Mock Factories</a><br>– <a href="#7c41">Composition</a></p><h4>Intro</h4><p>Mocking modules in itself is not hard. However, in my experience, mocking code can become overly complicated and be a drain on engineering time. Although it is not the most exciting topic, it is worth spending time understanding the different ways to mock a module. If a developer has a solid understanding of the mock function, it can serve as a cornerstone of their test strategy and speed up time spent writing tests.</p><p>Part of my reason for writing this article is selfishness. I often get tripped up by nuances involved in mocking a module and end up on stack overflow or combing through the Jest documentation, so I wanted to create a reference to use in the future. I hope you also find it helpful.</p><p>The methods outlined here are not front or backend specific, but my examples assume you use ES modules alongside typescript. They will still work if you have a different setup, but you may need to modify them appropriately.</p><h4><strong>Jest Mock Method</strong></h4><p>In this article, I will look at two techniques for mocking. The first technique will call the mock function with one argument, while the second involves calling the mock function with two arguments. Both methods do similar things. The second parameter (a factory function) allows for more customisations and control.</p><p>Let’s look at technique one, calling the mock function with one argument.</p><pre>jest.mock(&quot;../lib/track&quot;)</pre><p>Here I am mocking a module which contains one default export. The default behaviour is to set a module’s default and non-default exports to a Jest function object. Later the article will cover the factory method in more depth, but let’s briefly look at it to help show how the object will look.</p><pre>jest.mock(&quot;../lib/track&quot;, () =&gt; {<br>  return {<br>    __esModule: true,<br>    default: jest.fn(), // default is set to a mock function object<strong><br></strong>  };<br>});</pre><p>Both methods do the same thing. But in the second, we explicitly set the mock implementation via a factory function.</p><p>Now that we have scratched the surface of the mock method, it would be an excellent time to dive into more detail about the mocked function object.</p><h4><strong>The Mocked Function Object</strong></h4><p>The mock function object contains methods for mocking return values and spying on function calls. We will look at 3 key features of the mocked function object: accessing it, spying on it and setting mock implementations.</p><ol><li><strong>Accessing the mocked function</strong></li></ol><p>Mocking a module sets the module’s properties to a mock function object. However, we need a way to access this object. To access the mock function object, import the mocked module at the top of the file.</p><pre>import track from &quot;../lib/track&quot;</pre><pre>jest.mock(&quot;../lib/track&quot;)</pre><p>In the example above, track is a mocked function. However, before we use the method to make assertions in our tests, we need to do one last bit of housekeeping. Typescript will not be able to pick up that this is a mocked function; to take full advantage of the type system, we need to use the mocked function from Jest.</p><pre>const mockTrack = jest.mocked(track)</pre><p>The mocked method tells the editor that this is now a mocked function.</p><p>2. <strong>Spying on arguments</strong></p><p>The code is now ready to make assertions on:</p><pre>expect(track).toBeCalled()</pre><p>Because track is a void function, there is no need to set a return type. In the above example, Jest spies on the mocked function.</p><p>3. <strong>Mock implementation and return types</strong></p><p>When a module needs to return a data type, the mock function methods can be used to mock the return value or the implementation. Refer to the <a href="https://jestjs.io/docs/mock-function-api">Jest documentation</a> for a complete list; I frequently use mockReturnValue, mockResolvedValue, mockRejectedValue and mockImplementation.</p><p>Let’s take a look at how this works in practice.</p><pre>mockFetchData.mockResolvedValue([&#39;hey&#39;])</pre><p>In the test itself, mockResolvedValue is used to set a predictable return type which can then be tested in the “expect” clause.</p><p>The same technique works for non-default exports. First, import the non-default export at the top of the test:</p><pre>import { refetchData } from &quot;../lib/fetchData&quot;</pre><p>Then it can be mocked using precisely the same method as the default. Start using the jest.mocked approach to ensure the correct typings.</p><pre>const mockRefetchData = jest.mocked(refetchData)</pre><p>And then, the return value can be mocked using the mockResolvedValue method as this is an async function.</p><pre>mockRefetchData.mockResolvedValue([&quot;refetch&quot;])</pre><p>Here is the complete code sample for both examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7b93ef3fa5a60457c58dfa3db4f4bd8/href">https://medium.com/media/c7b93ef3fa5a60457c58dfa3db4f4bd8/href</a></iframe><h4>Mock Factories</h4><p>As well as setting return types using inline functions, it is possible to use a factory function in the mock constructor. A factory could be a good choice if the return type does not need to change throughout the test.</p><p>Using factories, there are a couple of syntactical quirks to be aware of.</p><p>Start by importing the module at the top of the file:</p><pre>import * as fetchData from &quot;../lib/fetchData&quot;</pre><p>Notice the import using the * as syntax. I think this is because jest.mock is designed to be used with commonJS, and using the * as creates a type of object more in line with that standard.</p><p>Now let’s look at the arguments for the jest.mock function.</p><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; { ...</pre><p>The path in the first argument is the same as the auto-mocking methods in the last section. The second argument is where all the action is; it’s a factory function which will return an implementation of the module. The module implementation has a lot of flexibility. You can set all the exports to bear a jest.fn or just some of them, set specific methods to simplified or noop procedures and require the original method implementation. You can also mix all of these to create different combinations. Now let’s look at the types of properties a mocked modules method can be set to:</p><ol><li><strong>Mock functions</strong></li></ol><p>Here’s the process with the default mocked implementation members set to jest.fn:</p><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    __esModule: true,<br><strong>    default: jest.fn(() =&gt; Promise.resolve([&quot;hey])),<br></strong>  };<br>});</pre><p>Note the funky __esModule syntax and assignment to default as per the <a href="https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options">Jest docs</a>:</p><blockquote>“ This property is normally generated by Babel / TypeScript, but here it needs to be set manually.”</blockquote><p>The default property is added to represent the default function. To add a non-default method, just add the name of that method. In the example below, the refetchData property shows how to do this:</p><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    __esModule: true,<br>    default: jest.fn(() =&gt; Promise.resolve([&quot;hey])), <br><strong>    refetchData: jest.fn(() =&gt; Promise.resolve([&quot;refetch&quot;])), <br></strong>  };<br>});</pre><p><strong>2. Normal functions</strong></p><p>For both the default and non-default, we are setting it to the jest.fn object. However, it is not essential to set this property to a jest.fn; depending on the use case, a more straightforward method could be used. If you don’t intend to spy on the function, try using a simpler one.</p><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    __esModule: true,<br><strong>    default: async () =&gt; &quot;simples&quot;, <br></strong>    refetchData: jest.fn(() =&gt; Promise.resolve([&quot;refetch&quot;])), <br>  };<br>});</pre><p>In the code above, the default is set to a simple implementation. We would test this implicitly by checking the return result of getData,</p><pre>const data = await getData(false)</pre><pre>expect(data).toEqual(&quot;simples&quot;)</pre><p>unlike the refetchData property, which is set to the jest.fn object and which would be tested explicitly via checking what arguments it was called with:</p><pre>expect(mockRefetchData).toBeCalledWith(true, {max: 100, min: 5})</pre><p><strong>3. Original module</strong></p><p>In rare scenarios, you may want to only mock part of a module. To do this, Jest has a function called requireActual, which needs to be used inside the factory function:</p><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    __esModule: true,<br><strong>    default: jest.requireActual(&quot;../lib/fetchData&quot;).default, <br></strong>    refetchData: jest.fn(() =&gt; Promise.resolve([&quot;refetch&quot;])), <br>  };<br>});</pre><p>The default is set to the default export of fetch data, and “refetchData” is set to a jest.fn.</p><p>Here are the code samples from this section (with the first default mock and the simple mock commented out) so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7fb3cc7b652f17ff8ba2c8b43ce6aae/href">https://medium.com/media/d7fb3cc7b652f17ff8ba2c8b43ce6aae/href</a></iframe><p>4.<strong> Pointers</strong></p><p>The final factory property is when we want to set a mocked module property to a named variable:</p><pre>const mockMethod = jest.fn()</pre><pre>jest.mock(&#39;path&#39;, () =&gt; {<br>  default: mockMethod // This will not always work!<br>...</pre><p>Have a look at the code above; looks legit right? It’s conceptually the same as using an anonymous mocked function. However, the Jest mock method gets hoisted to the top of the file by most compilers. In some scenarios trying to run this code will result in an error that says, “Cannot access before initialisation”.</p><p>I have found no good way around this. The first option is to define the const at the top of the file before the imports.</p><pre><strong>const mockRefetchData = jest.fn()</strong></pre><pre>import * as fetchData from &quot;../lib/fetchData&quot;;</pre><pre>jest.mock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    refetchData: <strong>mockRefetchData</strong>,<br>...</pre><p>The other option is to use the doMock function, which explicitly avoids the hoisting behaviour. However, note that you will need to define the mock before the imports, which looks a bit weird:</p><pre><strong>const mockRefetchData = jest.fn()</strong></pre><pre>/**<br> * * manual mock with factory<br> */<br>jest.doMock&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  return {<br>    refetchData: <strong>mockRefetchData</strong>,<br>  };<br>});</pre><pre><strong>import</strong> * as fetchData from &quot;../lib/fetchData&quot;;<br>...</pre><p>In this case, combining techniques from the default mocking mentioned earlier in the article with the factory implementation would be better. In the final section, this is what I will now look at.</p><h4><strong>Composition</strong></h4><p>We have seen how using factories can be a good way of grouping mocked methods but can be challenging if you require a pointer to spy on a process. At the start of the article, we used imports along with the Jest mocked and mock return type functions. Let’s combine these approaches to achieve a better way of spying on factory methods.</p><p>Start by importing the module:</p><pre><em>import</em> * <em>as</em> fetchData <em>from</em> &quot;../lib/fetchData&quot;;</pre><p>Create a factory and set a default implementation.</p><pre>jest<em>.mock</em>&lt;typeof fetchData&gt;(&quot;../lib/fetchData&quot;, () =&gt; {<br>  <em>return</em> {<br>    __esModule: true,<br><strong>    refetchData: jest<em>.fn</em>(() =&gt; Promise<em>.resolve</em>(&quot;default&quot;))<br></strong>...</pre><p>Let’s use the jest.mocked method to create a pointer (like we did earlier in the article).</p><pre>const<em> mockRefetchData </em>=<em> jest.mocked</em>(<em>fetchData.refetchData</em>);</pre><p>In our tests, refetchData will return “default” by default, but we can use the mockRefetchData const to access the jest.fn and spy on and modify its return value.</p><p>Here is the complete example</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b4cb6a7d3718a12b6b66a66b0d51f4/href">https://medium.com/media/b9b4cb6a7d3718a12b6b66a66b0d51f4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4d00f415b3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React, Apollo, and the mystery of the canceled requests]]></title>
            <link>https://james-dockeray.medium.com/react-apollo-and-the-mystery-of-the-canceled-requests-694712b62cc8?source=rss-f4631e424964------2</link>
            <guid isPermaLink="false">https://medium.com/p/694712b62cc8</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[James Dockeray]]></dc:creator>
            <pubDate>Mon, 10 May 2021 15:03:12 GMT</pubDate>
            <atom:updated>2021-05-10T15:03:12.232Z</atom:updated>
            <content:encoded><![CDATA[<p>The React app I’m working on was firing multiple Graphql Requests when there should have only been one. With the earlier identical requests being canceled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmBtbLgwCLOgQmHAfRuLKg.png" /><figcaption>canceled network requests</figcaption></figure><p>My hunch told me this was an issue with react rendering and prop updates. Being new to the apollo client library I didn&#39;t really know where to start, so I worked inside out.</p><p>First I looked at my use of the `useLazyQuery` hook, which hands more granular control over when the graphql request is made. Being a god-fearing developer I decided that here was where the problem lay and changed the hook to the other apollo client API `useQuery`.</p><p>I reloaded the page and…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*BU5i8GOvtBOiNINYZQb_jw.png" /></figure><p>I had actually made the problem worse, now I had 3 more requests. This at least suggested the original hook `useLazyQuery` was doing something.</p><p>After another detour looking at the `useApolloClient` hook and trying to query using `client.query`, I started to hone in on the origin of the problem which was further up the component tree.</p><p>We are using OAuth to authenticate, retrieving a token, and then passing that through to the Apollo client</p><p>What was happening was the container which checked to see if a user was authenticated and then initiated Apollo client, was rendered more than expected after a user had been authenticated (I hope to be able to expand this article with more info once I actually figure out what happened in the render update cycle). The effect of this was that Apollo Client was being initiated twice. Hence the first set of canceled requests.</p><p>The quick and dirty way I fixed this problem was to use memoize from lodash to cache the return object of the getApolloClient function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d11e3ca79949fe81c18090deddeb7c5/href">https://medium.com/media/5d11e3ca79949fe81c18090deddeb7c5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694712b62cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>