<?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 Jaroslav Šmolík on Medium]]></title>
        <description><![CDATA[Stories by Jaroslav Šmolík on Medium]]></description>
        <link>https://medium.com/@grissius?source=rss-b6348cffca53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eRhdscmU19NhkFuG.jpg</url>
            <title>Stories by Jaroslav Šmolík on Medium</title>
            <link>https://medium.com/@grissius?source=rss-b6348cffca53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:45:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@grissius/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[Maintainable Apps With Hexagonal Architecture]]></title>
            <link>https://medium.com/ackee/maintainable-apps-with-hexagonal-architecture-826f1cd2fafc?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/826f1cd2fafc</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ports-and-adapters]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 16:09:38 GMT</pubDate>
            <atom:updated>2023-01-23T16:09:38.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y-MDmgwdpiQb5v5Z.png" /></figure><p>In software, things are bound to change. Our assumptions crumble, product evolves, naive implementations from the prototype phase fail to scale, libraries and integrated services are swapped. It is our job to make the changes possible, without suffering more stupidly than we have to. Let’s find out which design concepts of hexagonal architecture (a.k.a. ports and adapters) can help us achieve that.</p><h3>Anticipating changes with DDD</h3><h3>Changes leave an artifact</h3><p>If you’ve ever been in a situation where you had to incorporate last minute changes, you probably know that changes, especially when done under pressure, leave an artifact in the code: maybe naming no longer makes sense, the documentation is out of date, there is a skipped test nobody knows whether it’s safe to delete, a legacy unused enum value that will cost someone 20 minutes to figure out why it was added, when it’s not used anywhere, etc. All of the things mentioned above are avoidable with enough resources, preparation or anticipation.</p><h3>Some changes are more difficult than others</h3><p>Another fact about the changes is that some of them are super easy, but some are difficult, difficult, lemon difficult. For example:</p><ul><li>Cut off segment of a large tight monolith so it can be scaled independently: difficult</li><li>Scale independently one service in a well managed monorepo: easy</li><li>Exclude a word from text analyses performed by a 3rd party: hard</li><li>Extend custom existing list of stopwords for text analyses: easy</li></ul><p>Sometimes, the difficulty is just because of the conflict with the current solution and had we known about the change earlier, this extra difficulty would simply not exist. If we only knew at the beginning that X should be configurable, we’d not hardcode it; if we knew that API A would have just a fraction of traffic compared to API B, they would not be on the same server so we could scale B differently, if we knew right away we’d need real-time communication we would have used a different communication protocol.</p><p>Of course some things are just difficult, because they are inherently difficult.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*4TDntTW4L3HXIoVo" /><figcaption><a href="https://xkcd.com/1425/">https://xkcd.com/1425/</a></figcaption></figure><p>We can’t do much about the inherent difficulty. What we can do however, is to shift things in our favor, that is, minimize the operational effort caused by the state of the current solution (the effect of technical debt or now irrelevant design decisions): make all changes easy to integrate. The problem is you cannot optimize everything for change and nobody knows what the future holds and if the product knew about changes ahead, they would surely tell you. What should we optimize for change then?</p><h3>What to optimize for change</h3><p>Software typically automates, manages or solves real life problems. These can be trivial (sharing photos of cats with friends) but also extremely complex (banking, insurance, logistics, …). The core of the business that exists without the software is the domain and the great thing about it is that it does not change that much! That’s why <a href="https://martinfowler.com/bliki/DomainDrivenDesign.html">DDD</a> suggests (pardon the vulgar simplification) that the design of the software and its architecture should be decided by the domain (the objects, functions and structures representing the domain objects and processes) rather than anything else (The very same concept applies in <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a> and others).</p><p>Now that we know what “changes less often” and also what is arguably vital for the business, let’s make some generalizations: <strong>The domain code doesn’t have any dependencies.</strong> In other words, in the domain code, you cannot import anything outside the domain (but your other code can import the domain). This is just an (extreme) application of the Stable-Dependencies Principle (SDP), but it has a cool implication: You never need to change your domain code because of external changes. Changing the RESTful API to gRPC does not affect your domain. Changing the database does not affect your domain.</p><h3>Zero-dependency domain</h3><p>Having no dependencies in your domain is something that takes some getting used to. For that reason, here are a few key side notes on the topic.</p><h3>Three-Tier architecture</h3><p>Yes, this actually contradicts (<em>extends</em>?) the familiar concept of a “layered” or (both relaxed and strict) n-tier architecture. In these classical patterns, your core is protected from the changes from the upper layers (typically UI), but you can easily make your domain layer totally dependent on the base layer (typically data persistence).</p><h3>Isolating the data layer</h3><p>Here is my favorite quote that sounds very reasonable, but is (in my opinion) very wrong:</p><blockquote><a href="https://gajus.medium.com/stop-using-knex-js-and-earn-30-bf410349856c">If you are building software from the first day with a consideration “What if we are going to need to migrate from MySQL to PostgreSQL?” then there is something fundamentally wrong with your technical planning.</a></blockquote><p>I understand it tries to prevent you from overengineering things and makes you Avoid Hasty Abstractions (AHA). The same way you don’t start with architecture or a solution that can handle the future upscale (I bet Netflix did not start streaming on a solution based on hundreds of microservices), you won’t get the storage right. Migrating from one SQL database to another might sound silly, but replacing (typically partly) your data layer is not madness, but usually a necessary and pragmatic step. Here are some examples:</p><ul><li>Move read-only event data from PostgreSQL to BigQuery, once we reach a velocity of thousand inserts per day, compared to couple a week</li><li>Replace “resource locked” indicator from column in SQL to Redis</li><li>And finally: Replace MySQL database with PostgreSQL, because we need to add geo queries, migration is not that painful for us and PostGIS is an excellent choice.</li></ul><p>Yes, changing the data layer, even part of it, can be hard. But it gets harder when you need to update your whole domain logic as well.</p><h3>Saving data from domain</h3><p>With the knowledge of three-tier architecture, it might sound counterintuitive to make the domain independent of the data layer. How do we save data then? You need to import and call the database object. This is the Inversion of Control (IOC) problem of course: Instead of importing a database into the domain and using it (and being forced to do changes when the database changes), we define (in the domain) an interface we need the database to have and use it. The data layer imports the interface from the domain (dependency is there, but reversed) and implements it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*ilhFSLpgiE1uAajt" /></figure><h3>Ports &amp; Adapters</h3><p><em>Ports &amp; Adapters</em> are an alternate name for the hexagonal architecture and it describes the second core concept: how to manage the non-domain code.</p><p>In hexagonal architecture, the isolated domain communicates with the outside world (API, database, notifications, database, MQ, …) via well defined contracts, which we call <strong>ports</strong>. Ports are defined in the domain (must be, because they are used by the domain) and they describe the interface of the interaction (in code: interface, abstract class, etc.). Ports have specific implementations (in code: classes implementing or objects conforming to the interface), called <strong>adapters </strong>(note: yes, it is an implementation of the familiar adapter design pattern).</p><p>An example of such a port-adapter pair is a ”<em>Cat Repository</em>”. It defines a behavior to ”<em>get cat</em>”, that returns an object from the domain entity<em> ”cat”</em>. Notice that the domain demands what to work with (inputs and outputs) and defines the behavior of the adapters, albeit on a very abstract level. Cool thing about the isolation and zero outside dependencies is that your domain works regardless of the specific implementation, which allows you to fairly easily swap the adapters and the core of the system remains untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*PnfBmS5sBAZ-bjSG" /></figure><p>We usually distinguish between primary and secondary “adapters” (if an adapter is secondary, the port is as well, so the attribute could just as well be given to the port, or the port-adapter pair, sometimes referred to as actor). The only difference is where the interaction initiates.</p><ul><li>For secondary adapters, the interaction is initiated by the domain (domain code calls “get cat”)</li><li>For primary (a.k.a. driving) adapters, the adapter initiates the interaction by calling the port (e.g. on empty food bowl the webhook is initiated and port ”<em>Bowl notification</em>” is called with <em>“refill”</em> and domain processes the event)</li></ul><p>For primary actors, the adapter pattern does not seem to be as helpful as for secondary and in practice, the isolation can be faked a bit without much loss to the advantages, because you don’t “swap implementations” as you might with the secondary adapters. The distinction is still valid for testability and Interface Segregation Principle (ISP).</p><p>Visualizing the domain core as hexagon, the ports as its edges and adapters as bubbles by the edges, you get the familiar graphical representation of the architecture. The author’s article can be found <a href="https://alistair.cockburn.us/hexagonal-architecture/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*FifJ3gDdkZ24RW6v" /></figure><h3>Summary: Why is it worth it and when?</h3><p>There are two main concepts:</p><ul><li>Separate your domain to be self-sustainable without dependencies;</li><li>Strictly isolate the “outside world” through abstractions and have things plug into your domain, not the other way around.</li></ul><p>Adhering yields the following advantages:</p><ul><li>Fast adaptation to adapter changes (changing database, API, 3rd party integration — everything is easier, because the expected behavior is explicit and well defined)</li><li>Easy testability (adapters and domain can be tested separately, domain can be sufficiently tested by unit tests by definition)</li><li>The design of your system makes sense and is not bent to the need of the integration (isolation makes it easier to define your domain the way you want, you can leave all adapter details outside of the domain)</li></ul><p>There are few in numbers, but great in significance and will make the difference between “yes” and “no, we must completely rewrite this” in a year in the development.</p><p>Following the hexagonal architecture takes a lot of work at first, especially on the domain isolation. You are going to need a lot of abstraction you did not need before and will do much more data mapping and transformations than you used to. What’s more, it feels super awkward on a green-field project, because the data typically looks the same from every angle (e.g. controller, domain, database). That’s alright, resist the temptation to deduplicate. The duplication is there, but an <a href="https://anthonysciamanna.com/2018/07/28/the-dry-principle-and-incidental-duplication.html">accidental duplication</a> rather than careless or copy-paste duplication. It’s not worth squashing the changes and the rewards will come in due time.</p><p>Finally, is the hexagonal architecture worth it every time? When I asked the question at a conference, I heard the opinion that “probably yes (maybe with an exception of some non-domain projects, like drivers, libraries etc.)”. The harsh truth is that the overhead is significant and all the benefits save the changes to the domain, therefore I would not recommend it for projects that are either not going to be maintained (one-time applications) or projects where the adapter complexity would exceed or be comparable to the domain (see <a href="https://www.martinfowler.com/bliki/AnemicDomainModel.html">anemic domain model</a>), especially for small scale projects. It is a tool that has its place and purpose.</p><p>There is a lot of fuzz around the hexagonal architecture. I myself had a lot of questions about it and the more I know about the topic, the more I think details don’t really matter (Should I have services or use case objects? Should I use classes or interfaces? How granular should the ports be?). Read about the concepts and start. Don’t be afraid if you don’t have a reference project for your technology, you will learn it on the fly. That’s why there are no practical tips, but only the core concepts. Here are some recommendations for further reading:</p><ul><li>Introductory <a href="https://blog.octo.com/en/hexagonal-architecture-three-principles-and-an-implementation-example/">article</a> to Hexagonal architecture with examples</li><li>Demo-<a href="https://github.com/Sairyss/domain-driven-hexagon">repository</a> (good for inspiration, few shortcuts, e.g. Queries, breaking the fundamentals, making it hard to recommend for learning the concepts)</li><li>DDD <a href="https://martinfowler.com/bliki/DomainDrivenDesign.html">introduction</a></li><li>Clean architecture <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">summary</a></li><li>Practical examples <a href="https://medium.com/@TonyBologni/hexagonal-architecture-structuring-a-project-and-the-influence-of-granularity-df4e0851ab5c">article</a> discussing port granularity</li><li>Motivation and high-level <a href="https://www.youtube.com/watch?v=th4AgBcrEHA">introduction talks</a></li></ul><p>Separate your domain code and don’t have any stinking adapter telling you how to interact with it. Farewell and let <a href="https://www.linkedin.com/in/jaroslav-smolik/">me</a> know directly or in the comments if you have any questions or would like me to cover more topics!</p><p><em>(originally posted at </em><a href="https://www.ackee.agency/blog/maintainable-apps-with-hexagonal-architecture"><em>https://www.ackee.agency/blog/maintainable-apps-with-hexagonal-architecture</em></a><em>)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=826f1cd2fafc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/maintainable-apps-with-hexagonal-architecture-826f1cd2fafc">Maintainable Apps With Hexagonal Architecture</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture Is Principally Good]]></title>
            <link>https://medium.com/ackee/hexagonal-architecture-is-principally-good-4a8681519004?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8681519004</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[ports-and-adapters]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 16:07:55 GMT</pubDate>
            <atom:updated>2023-09-13T13:10:22.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZLKjOCIfrK8VS91.png" /></figure><p>We humans tend to like and promote things not because they are good, but because we are momentarily charmed by them or just because we don’t want to be wrong. I know it because I do it myself. To stay out of trouble in my professional life, I try not to rely too much on my instincts, but rather discuss the pros and cons, which is the thing I started doing myself on code review to avoid “that’s not the way I would do it” comments. In over a year I became super interested in software architecture and especially Hexagonal architecture. And it made me wonder, why is it good? Let’s find out.</p><h4><strong>Single Responsibility Principle (SRP)</strong></h4><p>According to SRP, the objects (classes, modules, …) in your system should have no more than one responsibility, i.e. only one reason to change or serve only a single actor (user, component etc.) in the system. The hexagonal architecture helps you see the responsibilities more clearly, because it forces you to define the ports separately for the implementations (without it, the communication is implicit in the implementation). Not only that, but with the link to adapters, you inherently respond to a single entity most of the time, because typically, each actor has a custom adapter to interact with the system, though not every single time. You can definitely go against it by bulking up the ports into large facades, but at least at that point, it will be painfully obvious. When talking about system architecture, a more fitting rule is the <strong>Common closure principle (CCP)</strong>, which is pretty much analogous to the SRP.</p><h4><strong>Open Closed Principle (OCP)</strong></h4><p>This is an inherent feature of the hexagonal system on the domain — infrastructure (adapters layer is usually called infrastructure as a counterpart to the domain) level. All adapters are by definition replaceable and interchangeable.</p><h4><strong>Liskov Substitution Principle (LSP)</strong></h4><p>If you are new to the concept of hexagonal architecture, it might seem odd to have an adapter pattern for a single implementation. The core benefit of the isolation is testability and to achieve that with enough cool, you want to test the parts isolated with mocks or fakes, that is your code will run at least with two adapters for each port: the production one and the testing one. Breach of LSP is usually a problem with:</p><ol><li>hidden (yet observable) behavior nuance</li><li>the need to “type-cast” or handle a special case in the user code</li></ol><p>Preventing the first one is difficult, but avoiding breaking the second is actually easier, because you typically handle both adapters when implementing it, noticing the exceptions soon enough to realize the presumptions of the initial design were flawed.</p><h4><strong>Interface Segregation Principle (ISP)</strong></h4><p>This is for free. This is the direct, obvious implication of the hard work you put in. All contracts are separated from the implementation and well defined. Not only it brings independence but also it helps you get rid of the clutter that is not essential for the interaction. This is one of the good reasons to keep the ports discipline on the driving side as well.</p><h4><strong>Dependency Inversion Principle (DIP)</strong></h4><p>Again, obvious success: The zero dependency policy in the domain takes care of the dependency orientation being aligned with the abstraction level. With the secondary ports, you naturally apply the inversion of control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*WvZjwj1n-gQdGkNq" /></figure><h4><strong>Common Closure Principle (CCP)</strong></h4><p><em>“Don’t force users of a component to depend on things they don’t need.”</em> This is again a return to the similar concept of SRP or ISP. By keeping the ports small and single-purpose, you can allow the interactors (domain or adapters) to have only “what they need” and no more.</p><h4><strong>Acyclic Dependency Principle (ADP)</strong></h4><p>Hexagonal architecture does not prevent you from doing cyclic dependencies (speaking from experience), in fact it’s really not that hard, especially with port implementations in the domain. However if you use a language or framework where you can practically import anything from anywhere (looking at you JavaScript), you will need to take the dependencies more seriously, because they are to play a much larger role. You will likely face them, but at least you have a higher chance of noticing them early on.</p><h4><strong>Stable Dependency Principle (SDP)</strong></h4><p>SDP suggests that “less stable” components should depend on “more stable” components, and not vice versa. By more or less stable, we mean stability by measuring ingoing and outcoming dependencies: <em>(number of dependencies on current module) / (number of dependencies on current module + number of dependencies of current module)</em>. Let’s look at two components from our imaginary app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b60e18a02d5222b8cbfc5fb7fd44cbd/href">https://medium.com/media/6b60e18a02d5222b8cbfc5fb7fd44cbd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a48fc39cf41775db277de9469bdea6/href">https://medium.com/media/c3a48fc39cf41775db277de9469bdea6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b3263faada8d0095c96576fa0894f69/href">https://medium.com/media/7b3263faada8d0095c96576fa0894f69/href</a></iframe><p>There are three simple code snippets, a cat entity, port for the cat repository and its PostgreSQL adapter.</p><ul><li>Entity stability: 1 / (0 + 1) = 1</li><li>Port stability: 1 / (1 + 1) = 0.5</li><li>Adapter stability: 0 / (0 + 3) = 0</li></ul><p>As expected, the direction of dependencies is aligned with the stability score. The core objects in the domain have no dependencies (meaning no reason to change), so they are highly stable. Port definitions have only few dependencies (because they can only import other domain objects) and finally the adapters that import various libraries are the least stable. The fact that the stability is aligned with the dependency direction is not a coincidence, but a natural implication of isolating the domain and shifting all I/O details to adapters.</p><h4><strong>Stable Abstraction Principle (SAP)</strong></h4><p>SAP combines the concept of stability with a new metric: <em>abstractness</em>: a ratio between abstract objects (abstract classes, interfaces) and all objects in the module. Modules with only abstract objects have <em>abstractness</em> of 1, whereas only implementation modules have <em>abstractness</em> of 1<em>.</em></p><ul><li>Entity abstractness: 1 / 1 = 1</li><li>Port abstractness: 1 / 1 = 1</li><li>Adapter abstractness: 0 / 1 = 0</li></ul><p>The SAP suggests that stability should be linear to abstractness: the more abstract, the more stable it tends to be. This linear scale is marked as “main sequence” on the following diagram and the blue dots are our three components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*OrsDo6MTVBH5d8fg" /></figure><p>Notice that:</p><ul><li>Adapter completely follows the expectations: it is minimally stable and minimally abstract (concrete implementation)</li><li>Entity is the direct opposite, maximally stable, maximally abstract. Entity and adapter will likely nicely conform to the main sequence. Notice however, that if you changed the entity to a specific class, the situation would be a lot different and it would fall into the “Zone of pain” (because typically, modules that are non-abstract, but stable, tend to be rigid and hard to change). The simple switch from interface to class, does not make the architecture bad, in fact, it is one of the known “exceptions” to the rule (the other being low-level helper functions or std lib), as suggested by Robert C. Martin in <em>Clean Architecture</em>:</li></ul><blockquote><em>“Some software entities do, in fact, fall within the Zone of Pain. An example would be a database schema. Database schemas are notoriously volatile, extremely concrete, and highly depended on. This is one reason why the interface between OO applications and databases is so difficult to manage, and why schema updates are generally painful.”</em></blockquote><ul><li>That is exactly our case, but with an important advantage: this entity shall not change as the database is migrated.</li><li>The port is the only module that falls out of the main sequence, which is caused by the small example here. In a real scenario, the abstraction would likely stay the same, but stability would increase (because the dependants would increase at least by one: the testing adapter)</li></ul><p>Overall, it is a good sign that even on the small sample we can see that there is the expected correlation between abstractness and stability.</p><p>Well, it’s been a ride. At this point I think I discussed all principles mentioned in the Clean Architecture, except one, which I think is frankly not relevant (Let me know which I missed in the comments if you know!). But for all others, the hexagonal architecture either pushes you (sometimes a great deal) in the right direction, punishes you for bending the principles or at least makes it more obvious when you break them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*lDOEBVuzV5aX5MkP" /></figure><p>However as I mentioned in my <a href="http://www.ackee.agency/blog/maintainable-apps-with-hexagonal-architecture">previous post</a> I don’t think it is a recommended go-to approach for all systems, especially the ones with non-dominant domain logic. For complex systems that are going to live a long time it could be an essential friend in your developer or architect journey! Farewell and let <a href="https://www.linkedin.com/in/jaroslav-smolik/">me</a> know directly or in the comments if you have any questions or would like me to cover more topics!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8681519004" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/hexagonal-architecture-is-principally-good-4a8681519004">Hexagonal Architecture Is Principally Good</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Academy: An Expert Crowd-learning Practical Course]]></title>
            <link>https://medium.com/ackee/typescript-academy-an-expert-crowd-learning-practical-course-9e3ffda2bd0c?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e3ffda2bd0c</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[academy]]></category>
            <category><![CDATA[course]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 07:43:22 GMT</pubDate>
            <atom:updated>2022-08-12T05:25:12.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uBbjmJWl_fFZ9Mtb.png" /></figure><p>We spent over five months sharpening our TypeScript-fu in a crowd-learning program to go above and beyond your regular coding needs. Read more about our journey and what we have learned.</p><h3>Motivation</h3><p>I’ve had a whale 🐳 of a time attending our and crowd learning <a href="https://medium.com/ackee/%C5%A1kola-gou-aneb-jak-jsem-v-ackee-zalo%C5%BEil-vlastn%C3%AD-%C5%A1kolu-2d217d65b462">Go</a> and Flutter program and ABCH’s <a href="https://github.com/antoninkriz/Ackee-Blockchain-SSoS">SSoS</a> and so I tried refreshing the concept with a subject dear to me: TypeScript. Let’s see how it went, what we did well, and what could be improved.</p><h3>Why TypeScript?</h3><p>When we started adapting TypeScript about 4 years ago, I was actually one of the few who objected. At that time, <a href="https://flow.org/">Flow</a> was still a popular choice and there were many other projects adding typing to JavaScript, like <a href="https://reasonml.github.io/">ReasonML</a>, <a href="https://www.purescript.org/">PureScript </a>, etc. At that time it was not obvious that TypeScript would be the one to take off, but luckily I was wrong and people were right not to listen to me and keep on moving our stack to TypeScript.</p><p>In a few months, we all were quite happy with the transition and kept our love for all projects ever since. After a while, our frontend team began the adoption as well. So having two developer teams actually working with TypeScript, learning it could prove much more influential than trying out new technologies, like in the previous examples.</p><p>The Go and Flutter schools were both “true” crowd-learning experiences: several people without any formal knowledge of the topic and very light management would teach themselves. All of us made a great leap, but being all beginners, we could hardly get to any advanced topics.</p><p>With TypeScript Academy I wanted to take an alternative route: Being fairly proficient in TypeScript I felt confident to organize an advanced education project, hence the cocky name Academy. I do not say that lightly: when you say to your colleagues (among which are super capable people you work with on daily basis in the same technology) that they can join the “TypeScript Academy” to learn and improve, you’d better have something that even the best of them can learn, which means, ultimately, to prepare something where even you can learn yourself. Nobody wants to be teased into an advanced course just to read the docs and do basic examples.</p><p>Also having (at least) two teams worth of people that know the technology fairly well and could actually use any obtained skills in their daily tasks was a great opportunity to set the bar higher and make the course not about “learning”, but “mastering”.</p><h3>TypeScript: The course</h3><p>Mastering TypeScript is not just about writing “your regular useful code” (which mostly anyone attending could do well anyway), but rather about meta-programming in types, which allows you to write generic code. For this purpose, I decided to use even without <a href="https://github.com/type-challenges/type-challenges">Type Challenges</a>: an excellent project that provides a list of puzzles, and tasks with increasing difficulty. The puzzles are like code katas, but instead of writing logic for a runtime environment, you implement it in the static type system. It might sound odd, but you can do one-sided equality checks, branching with ternaries, and iteration with recursion, so you can do “algorithms” because the <a href="https://github.com/Microsoft/TypeScript/issues/14833">type system is Turing complete</a> even without JavaScript in it.</p><p>In the beginning, we usually prepared the puzzles at home and live-coded or explained the existing solution. In the second phase of the course, puzzles were accompanied by short presentations on advanced topics (e.g. <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a>, <a href="https://www.typescriptlang.org/docs/handbook/namespaces.html">namespaces</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html">decorators</a>, <a href="https://stackoverflow.com/questions/56737033/how-to-define-an-opaque-type-in-typescript">opaque types</a>, …), and in some of the last sessions, we spent mob-coding the hardest puzzles in a group of few people, like <a href="https://github.com/type-challenges/type-challenges/tree/main/questions/00741-extreme-sort">Sort</a> and <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00476-extreme-sum/README.md">Sum</a> in the type meta language and <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00462-extreme-currying-2/README.md">Generic currying</a>.</p><p>We decided to meet once a week and take turns (in full rotations, so everyone periodically has a contribution) in short (5–30 minutes) presentations or live-coding sessions. There were 8 (including myself) brave souls (5 backend, 2 frontend, and one DevOps) attending the vast majority of the lessons with 3 additional visiting representatives of PM, DevOps, and backend, who showed up for a lesson or two to see what it’s like (also it was a bit difficult to drop in as the course went on).</p><p>All in all, we had 17 lessons with not-so-shabby attendance, with only 3 people attending 11/17 lessons or less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uv6Dx4Uiqfao5ZWP.png" /></figure><h3>Happiness evaluation</h3><p>During the course I did two feedback forms, one after the fourth lesson, and the second one at the very end. The first one was to see if it was what everyone expected and to see if there are some ways to improve the rest. There were three major standouts:</p><ol><li>The course met the expectations and people were generally content with it (which is really cool, because not only I proposed a reasonable direction of the course, but explained it well enough in the first lesson and also we managed to follow it for a few weeks, so yay!)</li><li>Sticking with only puzzle-solving and coding was too narrow for some people (that’s why we added the “presentations” as mentioned)</li><li>From the different approaches, people were generally most content with live-coding as a form of presentation, as seen in the following chart.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BTZHZeMuXKA0FUVA.png" /></figure><p>I was really excited about the results from the second form because it was an opportunity for me to get feedback on the project that has been going on for over five months and required my focus for even a little longer than that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ApX60Yh_SLnR6Gkb.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NoqcP_SJBkQgn2HT.png" /></figure><p>Excitingly, as the charts show, we were able to lift ourselves (by our own anonymous definitions) from average TypeScript level 4 (out of 10) to level 7.625 (non-integer levels don’t have the ring to them, do they?) and the complete beginner climbed up to level 5!</p><p>Another goal for me was to grow a team of problem solvers: before the course rarely anyone besides me helped people stuck on complex types, advanced generics, and cryptic transpilation errors. At the end of the course, ⅞ people helped a colleague solve a problem they had with TypeScript, which is lovely.</p><p>At the end of the course, we decided to reward ourselves with a memento. We scrambled a t-shirt design at <a href="https://www.wordclouds.com/">wordclouds.com</a> with authentic words from the markdown file with our shared notes and met at a retrospective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fTToizW2KDUjsV4j.png" /></figure><p>The retrospective discussion provided the following highlights:</p><ol><li><strong>We lacked a moderator</strong>: I didn’t think we’d need one since over 90% of the time someone was live-coding or presenting, but in the end, we figured it would probably make the flow of the lessons swifter and more enjoyable if we had a moderator and take turns on that role.</li><li><strong>We nailed the concept of short presentations </strong>(approx 20 minutes), which are preferable to long lessons. Hour-long lessons are sometimes harder to follow or catch up on if you get lost. Of course, this concept was available to us since we did most of the work on the zero-setup TypeScript <a href="https://www.typescriptlang.org/play">playground </a>. Everyone could start it instantly in the browser and puzzles had no prerequisites.</li><li><strong>Automation for assigning presentations and puzzles would be better than volunteering. </strong>I have considered assigning the puzzles, but I thought if people signed up for the specific ones, it would be better because of the different levels of experience. We agreed that having something assigned externally forces you more to complete the task, compared to the pressure to sign up by yourself for a topic, which people find easier to resist. Welp, we are a lazy bunch, we developers.</li><li><strong>Puzzle repo was great material to follow, but sometimes we lacked a goal. </strong>Without a thought-out curriculum, it was easy just to lean on the goal to “finish all puzzles”. We were not sure how many lessons it would take us and we lacked some defined milestones. Spanning over 17 weeks, however, I feel like we kept the dynamics of the course very well.</li></ol><h3>The taste of the types</h3><p>Since we spent so much time cracking katas and live-coding, it would be rude to leave you empty-handed. Let’s look at one puzzle more closely: <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00741-extreme-sort/README.md">Sort</a></p><p>The goal is to implement a meta-type that receives a tuple of number literal types (all constant) and returns a constant tuple type, containing the same number literals, but sorted.</p><pre>Sort&lt;[2, 4, 7, 6, 6, 6, 5, 8, 9]&gt; //  [2, 4, 5, 6, 6, 6, 7, 8, 9]</pre><p>Since you cannot do any imperative constructs you are probably used to, you cannot really implement any compare and swap algorithms. Instead, you have to get by with whatever is available, which sometimes tests your creativity. Here are two authentic solutions we have from the course (we mob coded the first one in three people and I’ve written the other one myself)</p><p><a href="https://www.typescriptlang.org/play?#code/PQKgsAUABFDsAsBGKBaKBlA9gJwC6RhSOJQKgCMBPDAcygAoABAZwFcBLAYwEMBKKAMQBTAB65sQgLZDB7AHYAzIdkHds2bpTJkBuqAEVWQ5rnaY526FACScqLgAW7ZlE4PuAGw9C5NIQBooSkxWKDUZCQBHDgkAE3tMKGYcXCg5blxWDQ801klyZTD1TRd5KCF2R0LuZk4feJxYwpwoJtqfVMblADpLGABBdrkG7CaVUW5JAAdvZgAuMgADZdxmMiw8AB4AbQBdAD4oYGAoPfWUncQDo5Ptq-Ot7YAmQPhA2ECANi+fqABWQIADkCAE5rscYM9XoEAVBvnDfh8oMCoGClss+lAACoOGSLDa4Rb2ShTGTMBwhDzxTzJMKcOpTVLcCiYTDebh2XAkoTdKAAdVxdkqUGcUEW4iMi0CVSSKSE8QkbA8qXJlPiBRFdjadTknVGPQwmGk5REkxmxgWVnR4rWVgJOwAzIEXlArtLsEZDhDtk6oC77naLj7nYEAAyBRBhqNQUO7d2em6nX3+6PhmNh3bWzEAUTEGlc7i8Pj88zIiF56FYUymKTSGSynly+WULgA7pUHK6-gBqVrsGiVZi9KxPCtVmt4KAKDyYDJNgrYIeYw4ANXYQlbUHMUAA4pUABKschzKAOXC4KbzY6rNzdABWQ5wNGACEQkBAwEgX4goCgAH0AMAoDAKgABNEIVAAYUwJooH3ZQZGApCAKgD9vy5UlDS2LETVweoXDkPIFz2QIABFjE4XD8JZNkhA5KAAF4pxpAIsLw+JRDw4YCKI5Q9kY044ygSCsmwABZMpOOowjmxUJiJLkfpikoTYsX2Q4mJwqTuNOeQlBUeDuFiQJulMvTCgAJWMXBdigMgAH42M2XNOA8VgmgAOTyVTAhE9QFP2MiKMCbZTO6Al5V80SFIOMgT3I2oqJ0iUZEcqyADcWyETYItiQ4T1y79IAwmQMqy1SktiFwOUoEioH6elKuquRatspi9g07Emt0xRCkM4yoDC8yVCskxbLSoRMsXbLRtwEL+pM0yGs4a4T2W4ruWxbh2A8CrtKqsIWo6gStLEajthqxbumGqBZvG27rKgE8zggErdx8DzNg87qZIXQJlu6mr+Pa64mO+-aXGW7YAHJvF8RxofugGTx3D6vpCsLlozfYNswly3M87zTq4g7fr4oSPKEeVvB+3jsH+xqIfncmBOOzTuu2G6FpgIbepG6zbIcqBKepmQmf6qBHNCpb6Suu6nqgfH3KELzJE2WbAhF2JvAxmXOECfrYqsE85Em5QAG50M2hSlI0FTiekum6oUldPCMWnZJO7ZY06h2dM5vm4Logbef0h6xrsqxHKgG3lPV6zAgUzZUbkT7+sC97U82F23aEDPuZzty85x42Y-kV2i6tzCk4AGSEBRUiZoGhIs-sz0Bo6W7ojw64bj2-oezxW5odumbJ7BOt73AYbhmgEdspnQ0lwee-r1ITynmfi3n7rh7PLf4YcRHl7IKyh7b9ey7kVTtt2qeM73uaV6nwIz48R+S8gX9kKQ7FHsgmoxh-w-yAqhT8EB2DTFrAAb0VtETwgRcykk4KkAAvlObARooDQ0YCVFAbhPCz2MMAVgpgPDMGhrjGQWIcJMXtFCV0Rs3o8GYEA9qZAYBIKECg5y8Ddr0IOCFA4gUOGKxEMg3AvDWCeBykGK4Gc7jCP8KIrhPDsx8NkY8f0gjTiRj9EolR4juGSPUdI-hQY0yWJ0d7VMBirCcKMWojR9C9EugdNY1xgR3HqWUfYsREipEyPocmCMHiQxQG8SIvxqiTHOKDCE10zowl+nCZE3xMAHEBNMUE+J4S0x6MsdjEKhT0ylM8REuxGT-HGMCeYrR0I4C-HhPCWEKIwQKJdG8f4TTERAlBJUjJMTamaMkXcCM4S9GTPGYkxhCipkzPmYspJPjDFZLiY8ISKUFEDMyTU7JdTRlunsB6POIV5FRKqUM-ZIydjaPjKc042iVnRMcbEsxNybGlNjPchRJSfYXMGa84ZLjUmbJOQohJ5z0mArWe84JEywWehCpCnZ1SnFwtySkmZTxEUPODFip5ALdnopyY8BJ+TUwZh+ciiZlKvmoques0ZnT3g9IRN05E-TqWnBBH0xp7LmkwgaTi9SkBMwQCKj+EAwCQEoQAGJZCqCodAeFLwytlWAr+4ArCHHQO4CQQQIKyjcqYcw8xTznkvHMa8tQHD3kfNgZ8r5gAcmYK2ZQZBVzrk3MkE1Zg5DmrPBeK8wAbx2ofN0J8L4kDAF9aQ-1toYCHDEjgGQkFCxEMDZakNYb7WRsde+cBkAgA"><strong>Insert-sort inspired</strong></a></p><ol><li>Find minimum using accumulator and recursive walk-through tuple</li><li>Append minimum to the resulting tuple</li><li>If the input tuple is empty, return accumulator (from 2), otherwise, remove the first occurrence of the element found in (1) and call recursively with the updated input tuple.</li></ol><p><a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBA4hB2AZAlgZ2AHgHIBooEEoIAPYBAE1SgEN4QBtAXSgF4omA+VqLI0iqvnoByADYIA5sAAWw5gH4CUAFywEKdNjz0ADHgB0h-Iw4BYAFAWA9FYLlyUUWmBUA9gDMoqZAC8Iq+gBGPAAmZgBaLnog7QB9RkZtELi8eISLUEgoAFFiMFpyDAAVPjJ4Sho6Tm4SkjKK+mR4dwgAJygACQhqcgNDJpb2gCUIdEYLKChFaK6evDgkZwxZ8g5EqEN9XPzyjBH0NYmVdnHLcxsoABFW1zAoV3hodxuAWyJqAGNpR2c8VogXq4AG7QADu0lc4ig+WQ7XcrnaALAoACMXYaW0ehO63oyXRqQSESiaKYOLx9DSp0y0Gut3w5QAYshRGRWsUuGxavxylRGs02lAma10H19AMBftgKdJoohehSgJ2LQQNp0uZJjKrjcwPTyEyWW09qNgGZ1RrVHLgAqeexxe1cEq6KK7TwhtkAMpFNUajXTegOrBuz3rTa0nWM5mso0HaU+45MI4BU4XaLBbFJOKEqCRdiBKngaBM8rZF7IkDsmrWhouy3O-nDY2x2Ww+V1RV8wY8VWxzX+0VF8glsvRk0944DoegEemyZJizWWzuhFWkg7cgQcgZAtQADCD3X8FQEGKVd58AAri8AEZtPDK0lMPD7c8s09QC-XtpMbjVTlvhNmooz4somu77ggR4YGGur6lGRQcNomzAcA-ZNIOpZTvBJjzuY1JQCMILCsehBtja94mNwJHctW9adHWnZelM7BIRAhGQfBeAdMwc64duS6tJgXL1FQ5FPtw7jUKIR4cvhb7AK057QEBrFtJBe7lBBx7bAU7IcFwqjqQekHabs8GmnhVpsARqnHvQADMoR4GmYSmtYABUUCxF53k+d5UBFMau7UEeVC+WFXlQG5VgWMgpbLlAADeOQAI7npJeDbBAHxWgAvlAzyuG8wgAALUuEXySeI8ASKMVjnsAzKoMIOF4R8wWjD+RyTJl2UYNkqWSRg-GYJwqp6TgXU5HkWWYP1aWiENy4YEEJjaHm42TT1s0DQtw3LXi61raEJgIZt029XNg17boeBYjoq3sHdt0nRNZrded23zYtAnLc5eB2Q9aJ4gDG1vVNkAXTt30jQ5UAHYDf1QCDp1g1tfVQ9dsMHcdCG5o5cP-S9Z0Q59V1LfZ+NYmmT1QPduM3bTt1M1AiPI69Ppo5du3k3iAAseAAOx4AAbCLYtQAArHgAAceAAJyA3zeBS1Aouq+LQtQLLUAK6DHMfejX3XWmiMm055ss05CMW2blt27bLko-rJOG2TP2PlA8mKfTROowbXPQ796xexA9PrU7GqcxjPNW3gIf0-DeuR-70fuzT91xwpoeYszdMR+9LsB8b+MA5n3vaFjVtJwXM2u9z7uVyzwdZ-Tjfh+zyeF6nMP485zfl+wjeJ-n4O10X5ON1TufPWX2eD730+M7TvvO2P3f7Xg-NQJrau78rMvy-3c-0HLB-b+Le+S5vOOmqcFhAA"><strong>Counting-sort inspired</strong></a></p><ol><li>Enhance each element with an accumulator tuple of length equal to the element (for “3” add a tuple with 3 elements)</li><li>Append all elements with an empty accumulator to the result tuple</li><li>Pop one last element from all remaining accumulators</li><li>If the array is not empty, repeat from (2)</li></ol><p>I bet you would not use any of the algorithms in the language of your choice, right?</p><h3>TypeScript Academy: Summary</h3><p>The whole academy was an awesome experience for me (though a challenging one!). We all made some sacrifices in our free time to make it work and I feel it was worth it. It was a wonderful journey and I am extremely grateful for all the good people who joined and helped us create this collaborative learning experience together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sT9298KpjG5ICHgQ.png" /></figure><p>Would you be interested in doing a similar project in your team and need help? Let <a href="https://www.linkedin.com/in/jaroslav-smolik/">me</a> know. If you have any troubles doing complex types in TypeScript, we now have a squad of people willing to help you out, so feel free to <a href="https://www.ackee.cz/kontakt">reach out to us</a>.</p><p><em>Originally published at </em><a href="https://www.ackee.agency/blog/typescript-academy-an-expert-crowd-learning-practical-course"><em>https://www.ackee.agency</em></a><em> on August 10, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e3ffda2bd0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/typescript-academy-an-expert-crowd-learning-practical-course-9e3ffda2bd0c">TypeScript Academy: An Expert Crowd-learning Practical Course</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Use Cases for SQL Window Functions in a Real-Life Cat System]]></title>
            <link>https://medium.com/ackee/5-use-cases-for-sql-window-functions-in-a-real-life-cat-system-c9b06c1b144b?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b06c1b144b</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[row-number]]></category>
            <category><![CDATA[aggregation]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Fri, 27 May 2022 09:34:39 GMT</pubDate>
            <atom:updated>2022-06-06T07:57:01.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GkPY1LpHdUakF22l.png" /></figure><p>Window functions are an advanced SQL construct that you will likely come across when working with relational databases. Today I want to share a couple of real-life problems where window functions are beneficial or even essential.</p><p>Throughout the whole article, we’ll be working with the simplified schema from a cat information system. Assume a simplified schema with a single table:</p><pre>CREATE TYPE class AS ENUM (&#39;warrior&#39;, &#39;mage&#39;, &#39;rogue&#39;, &#39;scientist&#39;);<br>CREATE TABLE public.cats (<br>    id bigserial NOT NULL,<br>    &quot;name&quot; text NULL,<br>    birth_date timestamptz NULL DEFAULT CURRENT_TIMESTAMP,<br>    class class null,<br>    level int8 NOT NULL,<br>    CONSTRAINT user_pkey PRIMARY KEY (id)<br>);</pre><h3>Introduction: WTF WF?</h3><p>Window functions are a construct that (as the name suggests) allows you to operate on a data window in your selection with standard familiar aggregate functions or special window functions.</p><p>Let’s look at the basic syntax in a simple example, finding the max level across all cats.</p><pre>SELECT MAX(level) as max_level from cats;</pre><pre>max_level|<br>---------+<br>       12|</pre><p>Window function allows you to use aggregations to get multiple, potentially different results, operating on a defined window data.</p><pre>SELECT name, level, MAX(level) OVER() as max_level from cats limit 5;<br><br>name      |level|max_level|<br>----------+-----+---------+<br>Cosmomeowt|    6|       12|<br>Meowrrior |    2|       12|<br>Ulysses   |    1|       12|<br>Axe       |    8|       12|<br>Motley    |    2|       12|</pre><p>Notice that</p><ul><li>we got the same result (12), but we got the result for each row,</li><li>aggregation works as expected, even though the cat with level 12 did not get to the final result due to limit restriction,</li><li>we could use the aggregate function without familiar GROUP BY,</li><li>the result is the same for all rows.</li></ul><p>The syntax (preview is barbarically simplistic) allows defining the following statement as a part of the SELECT statement:</p><pre>/*&lt;advanced aggregation expression&gt;*/ OVER(/*&lt;optional window expression&gt;*/)</pre><p>Getting the same result does not seem particularly useful, but the power comes from using known and special aggregation functions over multiple defined windows with custom filtering and order, as we’ll see below! With the introduction out of the way, let’s check a few real-world examples.</p><p>You can try all SQL queries on the same data in <a href="https://www.db-fiddle.com/f/r6RQzePDNSqDq8EXQocPwq/1">DB Fiddle</a>.</p><h3>Showcase kittens from all classes: Balance ORDER BY for different types</h3><p>Let’s assume that we need to display on our homepage a preview of our freshest feline newcomers. We can’t afford to manipulate the future of the cat population by favoring one profession over the other.</p><ol><li>Show preview of 8 kittens. The youngest kittens must appear on the list.</li><li>An equal number of representatives from each class must be on the list, if possible. This criterion takes precedence over the first one.</li></ol><p>We need to push older cats back, but they can cut the queue by being representatives of an unpopular class.</p><p>This problem is fairly difficult to solve without window functions. One more naive solution is to use UNION, spell out all types and control the subselect using LIMIT based on the number of class types.</p><pre>(select * from public.cats where cats.&quot;class&quot; = &#39;warrior&#39; order by birth_date desc limit 2)<br>union<br>(select * from public.cats where cats.&quot;class&quot; = &#39;mage&#39; order by birth_date desc limit 2)<br>union<br>(select * from public.cats where cats.&quot;class&quot; = &#39;rogue&#39; order by birth_date desc limit 2)<br>union<br>(select * from public.cats where cats.&quot;class&quot; = &#39;scientist&#39; order by birth_date desc limit 2)</pre><p>Or a “dynamic” solution would be to use JOIN with LATERAL subselect</p><pre>select distinct classes.class, cats.*<br>from public.cats as classes<br>join lateral (<br> select * from public.cats<br> where cats.&quot;class&quot; = classes.&quot;class&quot;<br> order by birth_date desc<br> limit 2<br>) cats on (true)</pre><p>The latter is more obscure, but allows paginating the result in a single place, without having to control all subselects. The LATERAL allows us to define custom subselects to join for each value.</p><p>The solution with window functions that presents itself solves the problem not just more eloquently, but more efficiently, using a single pass through data (Note on efficiency: Efficiency is not immediately obvious, so I ran the queries on a larger dataset of 8K cats. <a href="https://explain.dalibo.com/plan/m6Q">LATERAL</a> is extremely slow due to the required looping over the data, <a href="https://explain.dalibo.com/plan/03b">UNION</a> is “okay”, but you can see that the execution plan grows in SEQ SCANs with each value of the class. Finally the <a href="https://explain.dalibo.com/plan/Qjz">WINDOW</a> solution uses a single SEQ SCAN regardless of the variability of class).</p><pre>select * from public.cats<br>order by row_number() over (<br> partition by class<br> order by birth_date desc<br>)<br>limit 8</pre><p>All three approaches give us the same kitties. Here you can see the output (if we include the ROW_NUMBER, which is used for sorting)</p><pre>name      |class    |birth_date                   |row_number|<br>----------+---------+-----------------------------+----------+<br>Una       |warrior  |2022-10-22 00:00:00.000 +0200|         1|<br>Cosmomeowt|scientist|2021-04-02 00:00:00.000 +0200|         1|<br>Cato      |mage     |2021-05-30 00:00:00.000 +0200|         1|<br>Sanjay    |rogue    |2021-03-09 00:00:00.000 +0100|         1|<br>Meowrrior |warrior  |2022-01-02 00:00:00.000 +0100|         2|<br>Uzi       |mage     |2020-07-06 00:00:00.000 +0200|         2|<br>Endmund   |rogue    |2021-03-02 00:00:00.000 +0100|         2|<br>Whipple   |scientist|2021-01-30 00:00:00.000 +0100|         2|</pre><p>ROW_NUMBER is the first special function we can use in the window functions. It simply assigns a number that increments for every row in the result.</p><p>For the first time, we can see the window expression as well! PARTITION BY allows us to create “multiple” windows, which allows us to create multiple series of ROW_NUMBER (for each ). Finally ORDER BY provides instructions on how to sort data within the windows. For each class, we want to pick the youngest kittens. As a result, the youngest cat from each class will have row_number 1. The second 2 etc. Sorting the whole set by this number elegantly solves the problem.</p><h3>Processing all cats on a memory-constrained computer: Limit by accumulative size</h3><p>For the next case, we need to process all the cats in the database. The problem is, we are running on a potato PC and we know that we’d better not take a batch of data that is larger than X bytes.</p><p>The problem is that some cats are really small in terms of size in bytes, and some cats will take the whole size limit for themselves. If there is a single cat that exceeds the limit, we want to take just a single cat and make an exception to the rule, so the scrolling is not stuck in a “deadlock”.</p><p>Note: Lengths of different rows can be different because of the dynamic field TEXT.</p><p>In Postgres, we can get the size of a row in bytes with the following query.</p><pre>select id, pg_column_size(cats.*) from public.cats limit 4<br><br>id|name      |pg_column_size|<br>--+----------+--------------+<br> 1|Cosmomeowt|            72|<br> 2|Meowrrior |            72|<br> 3|Ulysses   |            64|<br> 4|Axe       |            64|</pre><p>It roughly makes sense: id 8 + date 8 + class 4 + something for the name. Does not add up. Probably some padding, nevermind, we’re here for window functions, not nerdy byte counting.</p><p>Unfortunately, we cannot use an expression in LIMIT. But with window functions, we can limit the result in this fashion using a WHERE statement.</p><pre>select * from (<br> select<br> cats.id, cats.name, pg_column_size(cats.*) as &quot;size&quot;,<br> SUM(pg_column_size(cats.*)) over (order by id) as acc_size<br> from public.cats<br>) cat_sizes<br>where &quot;acc_size&quot; &lt; 300 or &quot;acc_size&quot; = &quot;size&quot;</pre><p>We need to use subselect to be able to reference the acc_size in the WHERE statement. To avoid deadlock, we allow the special case where acc_size is the same as size (matches the first row only). This condition is overshadowed by the first most of the time, which keeps capturing rows as long as the acc_size does not reach the defined limit.</p><p>The process is more obvious if we look at the data sample:</p><pre>id|name      |size|acc_size|<br>--+----------+----+--------+<br> 1|Cosmomeowt|  69|      69|<br> 2|Meowrrior |  69|     138|<br> 3|Ulysses   |  61|     199|<br> 4|Axe       |  61|     260|</pre><p>The acc_size keeps progressively growing as the window grows larger. This is a problem that is inherently based on the window functions and I don’t think there is an alternative solution.</p><h3>Talented cats from each year say goodbye: Deduplicate rows with preference</h3><p>For all cats born in the same year, we must select the most leveled-up cat for each class to lead a course of their craft: e.g. For all cats born in 2008, we need the cat with the highest level in their class.</p><p>This problem is fairly similar to the first one but so common it’s worth mentioning. Alternative phrasing is to “deduplicate rows with the same X, keep only rows with Y, discard the <a href="https://www.ackee.agency/blog/glossary/rest">rest</a> “. This is again fairly complicated for multiple values of X, but as you can probably see now, it is relatively easy with window functions. Again using the ROW_NUMBER.</p><pre>select *,<br>row_number() over (<br> partition by date_part(&#39;year&#39;, birth_date), class<br>      order by level desc<br>) from public.cats</pre><p>This will assign number 1 for all cats in focus, while others will have increasing series in the group. If this was a case for deduplication (all cats from same year and class are considered as duplicate, we want to keep only those with the highest level), we could easily filter out the cats to keep (row_number = 1) and those to remove (row_number &gt; 1).</p><h3>Voting groups: Divide rows in selection into X clusters</h3><p>As the elections draw near, we must prepare the voting points. We have overall 5 workers validating the IDs and we must somehow assign all cats in the system to one of them. We also need each worker to have a consecutive line of cats (ordered by the name), e.g. 1) gets cats with names A-F, 2) G — Lm, 3) Ln — O, etc. The problem is that if we set the letters as fixed, the distribution of cats can cause an overload of some workers, while others slack.</p><p>For this, we can use another special function NTILE, which assigns appropriate cluster numbers for a given window. Its argument determines the number of clusters.</p><pre>select *, ntile(5) over (order by name) from public.cats</pre><pre>id|name      |birth_date                   |class    |level|ntile|<br>--+----------+-----------------------------+---------+-----+-----+<br>29|Arieh     |2020-04-11 00:00:00.000 +0200|rogue    |    3|    1|<br> 4|Axe       |2006-02-02 00:00:00.000 +0100|warrior  |    8|    1|<br>19|Belphegor |2019-12-04 00:00:00.000 +0100|warrior  |    1|    1|<br>31|Bephelgor |2021-02-12 00:00:00.000 +0100|warrior  |    2|    1|<br>32|Cato      |2021-05-30 00:00:00.000 +0200|mage     |    1|    1|<br>11|Chubby    |2013-11-24 00:00:00.000 +0100|warrior  |    2|    1|<br> 1|Cosmomeowt|2021-04-02 00:00:00.000 +0200|scientist|    6|    1|<br>21|Dynas     |2020-11-17 00:00:00.000 +0100|rogue    |    1|    2|<br>30|Elephant  |2021-06-02 00:00:00.000 +0200|warrior  |    1|    2|<br>...</pre><h3>CLCS (Cat Level Competitive Score): Relative score</h3><p>Cats are rewarded based on their CLCS. That is a score depending on the relative position you take with your level compared to all the cats in the system: a relative level. We expect all the cats with the highest level (we already know it’s 12) to have a score of 1. All the cats with the lowest level should have a score equal to the relative size of the group sharing the level (0.1 if there are 10% of cats on the minimum level).</p><p>A window function (cumulative distribution) solves the problem for us again.</p><pre>select *, cume_dist() over (order by level) from public.cats</pre><p>In the result we can see that ¼ of cats have level one.</p><pre>id|name      |class    |level|cume_dist|<br>--+----------+---------+-----+---------+<br>21|Dynas     |rogue    |    1|     0.25|<br>20|Uzi       |mage     |    1|     0.25|<br>19|Belphegor |warrior  |    1|     0.25|<br>32|Cato      |mage     |    1|     0.25|<br> ...</pre><pre>14|Mimi      |warrior  |   11|  0.96875|<br>13|Lashpaw   |rogue    |   12|      1.0|</pre><h3>What about the performance?</h3><p>Window functions by their definition require an “iterative” scan over the data, so you might easily run into trouble when querying large tables.</p><p>Most of the time, your best shot is to reduce the data through index search and window scan only the necessary portion. In some cases, a <a href="https://explain.dalibo.com/plan/XBb">full scan with a window</a> could be far better than <a href="https://explain.dalibo.com/plan/GtG">combined complex queries</a>, as I’ve learned recently when running the deduplication case.</p><h3>Summary</h3><p>We learned what window functions are and showcased several practical ways to use them. I encountered almost all of them in one form or another in my job. The sad truth is, however, that I am not working on a cat system (but if you happen to work on one, let <a href="https://www.linkedin.com/in/jaroslav-smolik/">me</a> know, I might join you!)</p><p>Till then, I hope you liked it, reach me out if you have any questions or some other topic you’d like to read more about.</p><p><em>Originally published at </em><a href="https://www.ackee.agency/blog/5-use-cases-for-sql-window-functions-in-a-real-life-cat-system"><em>https://www.ackee.agency</em></a><em> on May 27, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b06c1b144b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/5-use-cases-for-sql-window-functions-in-a-real-life-cat-system-c9b06c1b144b">5 Use Cases for SQL Window Functions in a Real-Life Cat System</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node Testing Frameworks: The Good, the Bad, the Slow and the Hungry]]></title>
            <link>https://medium.com/ackee/node-testing-frameworks-the-good-the-bad-the-slow-and-the-hungry-ce50f0bba29b?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce50f0bba29b</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[ava]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Thu, 19 May 2022 16:08:18 GMT</pubDate>
            <atom:updated>2022-05-19T16:08:18.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u82ROd-6rlnqoM31.png" /></figure><p>Recently our Jest integration tests crashed on insufficient memory (the V8 “heap out of memory” error). It turned out it was not an anomaly and that the tests steadily accumulated so much memory that the single Node.js process hit the default <a href="https://nodejs.org/api/cli.html#--max-old-space-sizesize-in-megabytes">limit</a> of 4 GB set for V8 for heap size (we explicitly run them in sequence, that’s why there is only a single process). We have about 450 tests together in 50 suites, which are mostly integration tests: simulated HTTP requests are resolved on the server which communicates with the Postgres database running in Docker. This is the reason for sequential run, since we don’t have an isolated storage for each suite. After we found several issues with Jest matching our diagnoses (pick your favorite here: <a href="https://github.com/kulshekhar/ts-jest/issues/1967">ts-jest#1967</a>, <a href="https://github.com/facebook/jest/issues/10550">jest#10550</a>, <a href="https://github.com/facebook/jest/issues/11956">jest#11956</a>, <a href="https://github.com/facebook/jest/issues/12142">jest#12142</a>, <a href="https://github.com/facebook/jest/issues/7311">jest#7311</a>, <a href="https://github.com/facebook/jest/issues/7874">jest#7874</a>, <a href="https://github.com/facebook/jest/issues/11956">jest#11956</a>), one of the actions we took was to find out whether migrating to an alternative framework would solve our issues.</p><p>Let’s find out together where <a href="https://jestjs.io/">Jest</a> stands in memory requirements and performance against its competitors: <a href="https://github.com/avajs/ava">AVA</a>, <a href="https://mochajs.org/">Mocha</a> and <a href="https://node-tap.org/">Tap</a>.</p><h3>Measuring methods</h3><h4>Memory sampling in Node.js</h4><p>If you are running a single threaded Node.js app in a single process, you can sample memory in each tick of the event loop with the following snippet:</p><pre>let memStats = {}; // global accumulator<br><br>process.nextTick(() =&gt; { // register function for each &quot;tick&quot;<br> const current = process.memoryUsage(); // get memory usage info<br> for (const key in current) {<br>   // for each key val pair store max value<br>   memStats[key] = Math.max(memStats[key] || 0, current[key]);<br> }<br>});<br><br>process.on(&quot;exit&quot;, () =&gt; {<br> // when the process is done, log once the maximum values<br> console.log(memStats);<br>});</pre><p>This approach becomes problematic if one of your testing subjects (looking at you AVA) cannot be forced to run in a single process and single thread. Even though you can configure the thread pool size, you cannot have a global setup for the process, but only for individual workers, making the measures skewed.</p><p>It goes without saying that this has performance impact and is not to be used in any production code.</p><h4>Time util</h4><p><a href="https://www.gnu.org/software/time/">GNU implementation of time command</a> (usually needs to be invoked with full path, e.g. /usr/bin/time to avoid using your shell override of time) has a verbose option that gives you detailed information about not only time, but also resources used by the process.</p><pre>$ /usr/bin/time -v npm run test<br><br>    User time (seconds): 4.39<br>    System time (seconds): 0.45<br>    Percent of CPU this job got: 7%<br>    Elapsed (wall clock) time (h:mm:ss or m:ss): 1:06.7<br>    Average shared text size (kbytes): 0<br>    Average unshared data size (kbytes): 0<br>    Average stack size (kbytes): 0<br>    Average total size (kbytes): 0<br>    Maximum resident set size (kbytes): 95012 # this is what we&#39;re after, same as &quot;rss&quot; from &quot;process.memoryUsage()&quot;<br>    Average resident set size (kbytes): 0<br>    Major (requiring I/O) page faults: 0<br>    Minor (reclaiming a frame) page faults: 60030<br>    Voluntary context switches: 6206<br>    Involuntary context switches: 499<br>    Swaps: 0<br>    File system inputs: 0<br>    File system outputs: 8<br>    Socket messages sent: 0<br>    Socket messages received: 0<br>    Signals delivered: 0<br>    Page size (bytes): 4096<br>    Exit status: 0</pre><p>As long as we can limit the frameworks to a single process, time gives a uniform approach to measuring speed and memory consumption. Let’s do some testing!</p><h3>Results: Jest vs. Mocha vs. AVA vs. Tap</h3><p>Before we go over the highlights, if you are interested in more nerdy details, see <a href="https://github.com/grissius/jest-is-a-rude-needy-clown-and-eats-lot-of-memory">this repository</a>. You can even clone it and run your own tests. Find more details in the readme.</p><h4>Horde of tests!</h4><p>The simplest to measure was a scenario with many trivial tests: 100K tests (in 1K suites). Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v1ZZru8kUt4cffYz.png" /></figure><p>As you can see, there are a couple of takeaways for this scenario:</p><ul><li>Jest requires more than 3x more memory than average</li><li>Tap and AVA are astonishingly slow</li><li>Tap has by far the lowest memory requirements (10x less than Jest!)</li><li>Mocha is super fast</li></ul><h4>Async tests</h4><p>First test was very unfavorable to any work distribution, since there was no pending IO. It comes as no surprise that Mocha would outperform others. This time, we shall try a scenario closer to our integration tests: Imagine that each test performs a 500 ms IO operation and let’s also reduce the number of tests to 100 (in 10 suites).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0d64u53ogTHvyjIx.png" /></figure><p>(The memory of multi process runs is challenging to measure, so the values are missing.)</p><ul><li>AVA has the worst memory performance, but adequate to unmatched speed (individual tests run in parallel)</li><li>Mocha still has best memory requirements and outperforms Jest slightly in both sequential and parallel runs</li><li>Tap has a similar memory to Jest. It doesn’t run tests concurrently like AVA, but manages to outperform Jest and Mocha, most probably by using the master process as a worker as well (on my 4 cores, both Jest and Mocha processed in parallel 3 + 3 + 3 + 1 suites, whereas Tap did 4 + 4 + 1, bringing the whole time down by 5s)</li></ul><h4>Leaking bucket</h4><p>To be frank, we’re not exactly doing black-box testing. We know what we’re here for and we know that Jest leaks some memory in-between the suites and after inspecting the heap dumps we sort of knew what to look for: module cache. Therefore in the last test we introduced some imports. For this test (all variants), there is no wait and 1K suites, each with a single test.</p><p>Simple run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sPgQIik5_lvRdeKC.png" /></figure><p>Import standard Node modules: path, crypto, os, fs in each test and call one function of each:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CTRLQr5X9wYTpmq6.png" /></figure><p>Atop of that, leave a “hanging” setInterval (possibly simulating opened connection) in the suite:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*HEuALsqc0p7SovVp.png" /></figure><p>In the last run, Tap’s timeout was set to 1 ms, because otherwise it would not start a new suit, waiting for the current one to finish.</p><ul><li>Importing modules does not significantly affect memory for AVA, Tap or Mocha, while Jest more than doubles the memory.</li><li>Mocha keeps by far the lowest memory profile and best performance.</li><li>Mocha and AVA stay stable regardless of open handles, while Jest goes crazy with memory.</li><li>Tap does handle the opened handles worse memory-wise, but not as bad as Jest.</li></ul><h3>Summary: Most efficient Node testing framework</h3><p>If performance is your key requirement, go with Mocha. It has in all tests the smallest memory footprint and surpasses all competitors in both serial and parallel mode.</p><p>AVA might be an interesting choice if you don’t plan to go with an extreme number of tests. Its default parallelization of tests within the suites is unique. It requires a lot of discipline to write tests without race conditions and makes integration tests over a shared resource challenging, but it might be worth your time.</p><p>Tap has poor time performance with an extremely large number of tests (same as AVA, but for AVA it is reasonable to have inferior performance due to running tests concurrently, whereas for Tap it is not obvious why it is so much worse than Jest for example). Surprisingly enough, it is the only runner that uses all available cores for test execution.</p><p>And lastly, everyone’s favorite Jest is outperformed by its competitors in almost every tested scenario in memory and usually in time as well.</p><p><em>Originally published at </em><a href="https://www.ackee.agency/blog/node-testing-frameworks-the-good-the-bad-the-slow-and-the-hungry"><em>https://www.ackee.agency/blog/node-testing-frameworks-the-good-the-bad-the-slow-and-the-hungry</em></a><em> on February 18th, 2022</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce50f0bba29b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/node-testing-frameworks-the-good-the-bad-the-slow-and-the-hungry-ce50f0bba29b">Node Testing Frameworks: The Good, the Bad, the Slow and the Hungry</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Welcome to gRPC, Please Follow Me…]]></title>
            <link>https://medium.com/ackee/welcome-to-grpc-please-follow-me-fed8a80bf5dc?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed8a80bf5dc</guid>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[grpc-web]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Wed, 11 May 2022 10:28:26 GMT</pubDate>
            <atom:updated>2022-06-06T08:03:13.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dW4uZ4tI5Gf0WxME.png" /></figure><p>Have you ever used a Google SDK, e.g. Firebase on a client or backend? Do you want to know more about the underlying technology? Let’s learn more about the basics of gRPC, a modern high-performance multi-platform RPC framework. We will discuss the types of communication, how it affects your API design and how known concepts translate to gRPC.</p><p>When starting with gRPC, it can be challenging to answer what it actually is. A transport protocol, a software framework, a methodology? Officially it is an “RPC framework”, but when you read <em>”framework”</em>, think about it in a more general sense, not like the Ruby on Rails framework. The best way to set up our expectations for now is to think of it as an alternative to REST and GraphQL.</p><h3>gRPC is a web API design</h3><p>RESTful API design centers around resources and a finite set of defined operations — “methods” (get method on resource collection lists, update method on resource detail changes it, …). GraphQL solves the problem of resource shape and its relations (a graph definition the user can query), limited operations (custom mutation definition), error codes and more. It even describes a protocol where simple request-response communication is not enough (subscriptions).</p><p>While both approaches proved flexible for many scenarios by the test of time, an alternative RPC design allows the interface to be more versatile. The server defines services with custom procedures that the clients can remotely invoke. It is by no means a revolutionary concept, you might be familiar with this approach from “older” technologies like <a href="http://xmlrpc.com/">XML-RPC</a>, <a href="https://en.wikipedia.org/wiki/SOAP">SOAP</a> or <a href="https://docs.oracle.com/javase/tutorial/rmi/overview.html">RMI</a>.</p><p>REST and GraphQL designs give you more guidelines and rules, which is usually a great thing, but sometimes it slows you down or forces you to go against them (take a second to think of a purist RESTful API design for user authentication). With RPC, you have more freedom to model the API, making it easier to fit it to your domain, but it is more difficult to keep your design consistent. It removes the friction of the communication protocol and allows you to call the web API almost as if you were calling a function in your code.</p><p>Let’s look at an example.</p><h3>gRPC is a communication protocol</h3><p>Ok, we need custom services and custom-defined procedures. These are typically defined in Protocol Buffers: a language for defining a schema for messages ,services and mechanism for serialization. Here is a simplified schema of a service:</p><pre>message GetCatRequest { string name = 1; }<br>message Cat { string name = 1; }<br>service CatService {<br>   rpc GetCat (GetCatRequest) returns (Cat);<br>}</pre><p>The schema describes all required information for both the client and the server to communicate.</p><ul><li>The client knows which services (service CatService) and procedures (rpc GetCat) are available</li><li>Request (GetCatRequest) and response (Cat) messages are known from the schema</li><li>Messages are defined independently of the server or client implementation and describe the format with data types, making the schema a recipe for serialization and deserialization</li></ul><h4>Data types</h4><p>It only makes sense for the <a href="https://developers.google.com/protocol-buffers/docs/proto3#scalar">primitive data types</a> to reasonably cover the broader needs, even for e.g. systems language. That is why you can find both signed and unsigned variants of integers and you are forced to specify the size variant (e.g. uint64). As for the non-scalar types, apart from defining your messages that can be nested, you have several composite types, such as enum, maps, unions, a <em>repeated</em> modifier for collections and several <a href="https://developers.google.com/protocol-buffers/docs/reference/csharp/namespace/google/protobuf/well-known-types">official messages</a> for timestamp, duration etc.</p><h4>Call types</h4><p>In the example, we only saw a “request-response” RPC type. However, there are altogether 4 types of communication:</p><pre>message GetCatRequest { string name = 1; }<br>message WatchCatsRequest  {}<br>message FeedCatsRequest { string food = 1; }<br>message ShareLocationRequest { int32 lng = 1; int32 lat = 2; }<br>message ShareLocationResponse { float travelled_meters = 1; }</pre><pre>service Cat {<br>   rpc GetCat (GetCatRequest) returns (Cat);<br>   rpc WatchCats (WatchCatsRequest) returns (stream Cat);<br>   rpc ShareLocation (stream ShareLocationRequest) returns (ShareLocationResponse);<br>   rpc FeedCats (stream FeedCatsRequest) returns (stream Cat);<br>}</pre><ol><li>Unary GetCat: The client sends GetCatRequest and receives a Cat</li><li>Server streaming WatchCats: Client sends WatchCatsRequest (empty, they are just happy to watch some cats) and server sends a stream of Cat objects through the open connection. The timing is on the server, it can send a hundred cats right away in a busy hour, send one each minute or not send any at all if there is none around. Both client and server can end the call.</li><li>Client streaming ShareLocation: The client (a cat in this case) opens a stream and can send location updates (for example, as it wanders through the neighborhood). This is the “inverse” of server streaming. When the client ends the call, the server can react with a response, for example sending the statistics on how long the journey was.</li><li>Bidirectional streaming FeedCats: This call is a combination of both streaming options. Client initiates the call and can both send and receive messages. Sometimes you just throw food to feed the cats, but they don’t come. Sometimes you have a single morsel of tuna and two cats show up or you have nothing at all and seven cats are already there waiting for the nibble.</li></ol><h4>Additional properties</h4><p>Atop of the communication means described, there are also some concepts you are familiar with</p><ul><li><a href="https://grpc.github.io/grpc/core/md_doc_statuscodes.html">status codes</a></li><li>and <a href="https://grpc.io/docs/what-is-grpc/core-concepts/#metadata">metadata</a>, which is a counterpart to HTTP headers in every way you can think of (they are actually also transported in HTTP headers). There are a few types of metadata, but the difference becomes really important only when you use non-unary call types, which is rarely the case.</li></ul><h4>Standard services</h4><p>There are a few common domain-independent problems people generally solve when implementing a web API, that is why there are standards for that as a part of the framework.</p><ul><li>Is the server or service running? See <a href="https://github.com/grpc/grpc/blob/master/doc/health-checking.md">GRPC Health Checking Protocol</a></li><li>What is your schema? See <a href="https://github.com/grpc/grpc/blob/master/doc/server-reflection.md">GRPC Server Reflection Protocol</a></li></ul><h3>gRPC is a transport protocol</h3><p>As we already know now, communication is not just about messages coming in and out. If you inspect the HTTP activity of a gRPC communication, you will probably see some requests and responses with Content-Type: application/grpc+proto. These messages (in brief) contain the binary serialized Protocol Buffers messages and status codes in payload and metadata (in headers and payload).</p><p>The streaming features are actually implemented via HTTP/2 streams, which is basically great news unless</p><ol><li>There is poor support of HTTP/2 for you platform (this is most probably not the case)</li><li>One of your clients is a web client.</li></ol><p>You are unlikely to face technological issues with HTTP and gRPC on server, desktop or app technologies, because you are typically provided full access to the network. This is not the case for the web, where your code obviously cannot have full access to anything for security reasons and must interact with the system through a set of APIs. This control <a href="https://grpc.io/blog/state-of-grpc-web/#the-grpc-web-spec">does not allow fine-grained control</a> over HTTP/2 frames within a stream and therefore full gRPC support is not possible at this time for the web.</p><p>Sacrificing client-side &amp; bi-directional streaming call types, you can connect your web clients through a sidecar proxy, typically <a href="https://www.envoyproxy.io/">Envoy</a>.</p><p>More nerdy details regarding the transport can be found in the <a href="https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md">specification</a>.</p><h3>gRPC is a “framework” you install and use</h3><p>We have covered many parts of “what gRPC is”. Finally, it is a set of tools and libraries for various platforms you should use for gRPC communication.</p><h4>The tools</h4><p>The communication is handled by software available for supported platforms. Implementations usually offer both dynamic (invoke RPC with dynamic name) and static invocation (invoke RPC on a generated object). Usually, on a larger project, you will be using the static invocation to get the benefit of type checking against your schema. Codegen tools helping you with stub generation will be the most important ones you will use.</p><h4>The library</h4><p>After the setup, your code will typically invoke generated stubs, as seen on the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mnxj6DAYczVueKs8.png" /></figure><p>Let’s take a look at a simple code example. The following TypeScript server code uses <a href="https://proto.cat/">proto.cat</a> framework for brevity and showcases a simple unary RPC call implementation on the server and client invocation. This could be either a web browser (though there are some complications that were already mentioned) or another server: two backend services communicating together.</p><pre>import { ProtoCat } from &#39;protocat&#39;<br>// Generated service definition<br>import { CatService } from &#39;../dist/cat_grpc_pb&#39;</pre><pre>app = <strong>new</strong> ProtoCat()<br>app.addService(CatService, {<br>   getCat: async <em>call</em> =&gt; {<br>       const cat = await getCatByName(call.request?.getName() ?? &#39;&#39;)<br>       call.response.setName(cat.name)<br>           .setHealth(cat.health)<br>           .setLevel(cat.level)<br>           .setClass(cat.profession ?? &#39;warrior&#39;)<br>   }<br>}</pre><pre>app.start(&#39;0.0.0.0:3000&#39;)<br>// Generated client<br>import { CatClient } from &#39;../../../dist/test/api/v1/cat_grpc_pb&#39;<br>// Generated message<br>import { Cat } from &#39;../../../dist/test/api/type/cat_pb&#39;<br>import { ChannelCredentials } from &#39;@grpc/grpc-js&#39;</pre><pre>const client = <strong>new</strong> CatClient(ADDR, ChannelCredentials.createInsecure())<br>const cat = await <strong>new</strong> <em>Promise</em>&lt;<em>Cat</em>&gt;((<em>resolve</em>, <em>reject</em>) =&gt; {<br> client.getCat(<strong>new</strong> GetCatRequest().setName(&#39;Proto&#39;), (<em>err</em>, <em>res</em>) =&gt;<br>   err ? reject(err) : resolve(res)<br> )<br>})</pre><pre>console.log(`[${cat.getClass()} ${cat.getLevel()}] ${cat.getName()}`)</pre><h3>Q&amp;A</h3><p>Let me try to quickly address some questions that might arise, if you’re new to gRPC.</p><p><strong>How to invoke an RPC?</strong></p><p>The tooling got better, but being a binary protocol, you need server reflection or linking the schema, so it’s a bit trickier than REST or GraphQL. There is CLI <a href="https://github.com/fullstorydev/grpcurl">grpcurl</a>, or GUI <a href="https://github.com/bloomrpc/bloomrpc">BloomRPC</a> (which does not support reflection and response metadata) and my recommendation: <a href="https://github.com/rogchap/wombat">Wombat</a>. Recently Postman <a href="https://blog.postman.com/postman-now-supports-grpc/">added support</a> for gRPC, but maintaining its current workflow, which forces you to create a “request” object for every call, is just burdensome and does not really fit the RPC model.</p><p><strong>How to distribute schemas?</strong></p><p>For “internal” API, we went with syncing the proto files through cloning a git repository, which works ok for developers, but gets complicated when you want to drag in PM, QA, third parties etc. Luckily, I ported the <a href="https://github.com/AckeeCZ/grpc-server-reflection">server reflection for Node.js</a>, so you can use it with any JS gRPC server. The trouble still is the public environment, where you probably don’t want to have it enabled. Sharing schema files is still probably the best option there.</p><p><strong>Best practices recommendations?</strong></p><p>There are a ton of resources for REST and GraphQL, but not that many for gRPC, since there are not so many people using it. For the first API we did, we were just learning a lot and did not pay too much attention to conventions. After revaluation, we studied and followed Google’s <a href="https://cloud.google.com/apis/design/">API design guide</a>, which was an invaluable resource for keeping the API schema maintainable, extendable, consistent and for avoiding breaking changes.</p><p><strong>Static analysis of the schema?</strong></p><p>We’ve been using Uber’s <a href="https://github.com/uber/prototool">Prototool</a>, because its unofficial successor <a href="https://github.com/bufbuild/buf">Buf</a> was not ready to give us all the rules we were used to from Prototool. It might be worth checking out now, since Prototool is not actively maintained anymore.</p><p><strong>How’s proxy support?</strong></p><p>For a long time, there wasn’t any HTTP proxy that supported gRPC. <a href="https://blog.cloudflare.com/announcing-grpc/">In 2020, Cloudflare announced beta support</a> and it is now available as a stable <a href="https://support.cloudflare.com/hc/en-us/articles/360050483011">feature</a>. If you’re wondering, why is it such a big deal to support gRPC since Cloudflare is already capable of proxying HTTP2, read more in their <a href="https://blog.cloudflare.com/road-to-grpc/">blog</a>, the answer is very similar for web clients still needing grpc web, even though browsers generally support HTTP2. To support web clients via grpc-web protocol, <a href="https://www.envoyproxy.io/">Envoy</a> is still your best shot.</p><p><strong>How to handle caching?</strong></p><p>Server caching is still challenging. HTTP caching is complicated since all requests are POSTs and e.g. Cloudflare support is a single toggle, without any additional configuration. We have a custom application solution for general request-response caching, which we’re excited to share more about (but if you’re really interested, it’s implemented as a part of <a href="https://proto.cat/docs/wiki/caching">ProtoCat</a></p><p>Have more? Do let us know.</p><h3>Summary</h3><p>We’ve covered different layers of what the gRPC ecosystem offers which should give you a general understanding of the framework.</p><p>There is more we can share about our experience with running gRPC in production (and maintaining it for nearly three years), reach out to us or leave a comment if there is a topic you want to learn more about.</p><p><em>Originally published at </em><a href="https://www.ackee.agency/blog/welcome-to-grpc"><em>https://www.ackee.agency</em></a><em> on May 11, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed8a80bf5dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/welcome-to-grpc-please-follow-me-fed8a80bf5dc">Welcome to gRPC, Please Follow Me…</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest: Does It Test Funny to You?]]></title>
            <link>https://medium.com/ackee/jest-does-it-test-funny-to-you-d4efa1a8cfd3?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4efa1a8cfd3</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 08:59:35 GMT</pubDate>
            <atom:updated>2022-04-25T08:59:35.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bXa--9jFxN0g-vdH.png" /></figure><p>Around 2019 we replaced <a href="https://mochajs.org/">Mocha</a> with <a href="https://jestjs.io/">Jest</a> for testing Node.js applications in our back-end team to simplify our testing setup. Let us share what we learned and what are some hidden traps we fell for.</p><p>After using Mocha for testing practically on all internal and open-source projects we noticed some issues. The main defect from my perspective (being one of the main critics) was the complexity associated with the openness of the framework: <em>It is just a test runner</em>.</p><p>Apart from Mocha we needed:</p><ul><li>Istanbul for coverage reporting (<a href="https://www.npmjs.com/package/istanbul">istanbul</a>, <a href="https://www.npmjs.com/package/nyc">nyc</a> later),</li><li>Chai for assertions</li><li>and some other related extensions of these libraries to provide even more sugary testing or integrations e.g. junit reporting for our Jenkins pipeline we used at that time.</li></ul><p>Back then, Jest seemed almost too good to be true: not only we could replace the numerous dependencies with a single module jest (well, and a <a href="https://www.npmjs.com/package/jest-junit">junit formatter</a> at that time to be frank), but many things got simplified drastically — for example generating code coverage was no longer a voodoo script one had to copy from previous project, but just a matter of adding --coverage (and setting the formatter). Atop of that, everything was well documented on glamorous websites and we got used to the gimmick feature of jest: <em>the</em> <em>snapshots</em>.</p><p>In retrospect, I think I had been too harsh on Mocha and had judged too hastily in the prospect of a shiny replacement. After some (both joyful and dreadful) time spent with Jest, I think it is time to look back and call out some of its features that make our life difficult.</p><h3>Typescript aids</h3><p>After adapting TypeScript we ran tests as we did any other application code: build and run JavaScript. This bugged me a bit, because it was a tad slow (TypeScript was a bit slower and did not have some optimizations that are available now, e.g. the <em>incremental</em> builds) and stack traces and debugging required additional configuration to work properly.</p><p>We solved the problem with <a href="https://www.npmjs.com/package/ts-jest">ts-jest</a>, which lets you interpret the TypeScript files on the fly and easily solves both of the issues.</p><p>We did notice the warning in the <a href="https://github.com/kulshekhar/ts-jest#versioning">docs</a>:</p><blockquote><em>We DO NOT use SemVer for versioning.</em></blockquote><p>But it did not stop us. Take this with a pinch of salt. It is almost SemVer, but aligns the major versions with the ones of Jest. Needing the versions to be lined up with the framework caused us numerous issues:</p><ol><li>Bots do not know that versions need to be bumped together</li><li>If you have some issues after the update it can be in jest or ts-jest and debugging is a bit harder</li><li>TypeScript support is getting better, but there were issues with support for certain files (you could write suites in TypeScript, but not detached setups, configs etc.)</li><li>You can upgrade jest only when there is an appropriate version ready.</li></ol><p>Living with TS Jest and Jest is just a little painful. It would be great to have a <a href="https://stackoverflow.com/a/35661569">node module plugin</a> that is completely unrelated to Jest to solve this issue for us.</p><h3>Snapshot testing</h3><p>To be fair, snapshots are not the only way to write assertions in Jest and Jest is not the only library you can use for writing snapshot tests, but people using Jest <em>tend</em> to use snapshots more and snapshots <em>tend</em> to be used with Jest so I think the warning against overusing them is still relevant.</p><p>This is how I felt about the snapshot testing throughout the two years or so using them:</p><ol><li>Snapshots are an ultimate assertion strategy, changing how people write tests.</li><li>Writing tests using snapshots is kind of lazy: you do not need to specify the important rules and just preserve everything. It is an excellent tool for prototyping.</li><li>Maintaining snapshot tests is extremely challenging. Updates in the system produce large diffs in the snapshots that are hard to validate and review.</li><li>All external snapshots from tests are difficult to review (creations and updates alike). Use inline snapshots by default.</li><li>Do not use snapshots unless you need to, prefer short inline snapshots with carefully selected attributes.</li></ol><p>Snapshot testing might be a good tool for a specific usage. The issue however is that you know about the benefits from the start (easy to write) and feel the pain much later on down the road (maintaining a large system with large snapshot data, where it is difficult to say whether a change breaks the system or <em>changes it</em>) so people tend to overuse it.</p><p>If you start using Jest, be more conservative with adapting the snapshot testing. Everything comes with a price.</p><h3>Magical life cycle</h3><p>This is an example form the docs that showcases the test life cycle:</p><pre>beforeAll(() =&gt; console.log(&#39;1 - beforeAll&#39;));<br>afterAll(() =&gt; console.log(&#39;1 - afterAll&#39;));<br>beforeEach(() =&gt; console.log(&#39;1 - beforeEach&#39;));<br>afterEach(() =&gt; console.log(&#39;1 - afterEach&#39;));<br>test(&#39;&#39;, () =&gt; console.log(&#39;1 - test&#39;));<br>describe(&#39;Scoped / Nested block&#39;, () =&gt; {<br>  beforeAll(() =&gt; console.log(&#39;2 - beforeAll&#39;));<br>  afterAll(() =&gt; console.log(&#39;2 - afterAll&#39;));<br>  beforeEach(() =&gt; console.log(&#39;2 - beforeEach&#39;));<br>  afterEach(() =&gt; console.log(&#39;2 - afterEach&#39;));<br>  test(&#39;&#39;, () =&gt; console.log(&#39;2 - test&#39;));<br>});</pre><pre>// 1 - beforeAll<br>// 1 - beforeEach<br>// 1 - test<br>// 1 - afterEach<br>// 2 - beforeAll<br>// 1 - beforeEach<br>// 2 - beforeEach<br>// 2 - test<br>// 2 - afterEach<br>// 1 - afterEach<br>// 2 - afterAll<br>// 1 - afterAll</pre><p>If you skip some tests however, Jest <em>used to</em> behave in mysterious ways.</p><pre>beforeAll(() =&gt; console.log(&#39;1 - beforeAll&#39;));<br>afterAll(() =&gt; console.log(&#39;1 - afterAll&#39;));<br>beforeEach(() =&gt; console.log(&#39;1 - beforeEach&#39;));<br>afterEach(() =&gt; console.log(&#39;1 - afterEach&#39;));<br>test.skip(&#39;&#39;, () =&gt; console.log(&#39;1 - test&#39;));<br>describe(&#39;Scoped / Nested block&#39;, () =&gt; {<br>  beforeAll(() =&gt; console.log(&#39;2 - beforeAll&#39;));<br>  afterAll(() =&gt; console.log(&#39;2 - afterAll&#39;));<br>  beforeEach(() =&gt; console.log(&#39;2 - beforeEach&#39;));<br>  afterEach(() =&gt; console.log(&#39;2 - afterEach&#39;));<br>  test.skip(&#39;&#39;, () =&gt; console.log(&#39;2 - test&#39;));<br>});</pre><pre>// jest@24 and prior<br>// 1 - beforeAll<br>// 2 - beforeAll<br>// 2 - afterAll<br>// 1 - afterAll</pre><pre>// jest@25 onward<br>// (no output)</pre><p>Furthermore, the output are still the same <em>even if you skip the whole describe block</em>. I do not wish to blame Jest now for bugs long fixed, but this behavior taught us it is better not to trust it with setup and tear-down when it comes to modifying the suits with skip / only.</p><h3>Only works only within test suite</h3><p>Want to run a single test? Sure, for Mocha, add <a href="https://stackoverflow.com/a/12221386">.only</a>. For Jest add .only and update your test task to run only the only suite you want to test. Or check the CLI docs to find the parameters you can use with some pattern (that is hopefully regex) which matches the test names (to be honest, I am not sure what it matches). Or just read this <a href="https://stackoverflow.com/a/55279902">guide</a> which explains it thoroughly in a few pages until you reach the <em>voilà!</em> at the very end.</p><p>It is a feature of Jest that it runs every suite independently, each in a new process, so it finds the only when it launches all the suits. But more on that in the next point.</p><h3>Random by default</h3><p>Running the tests independently allows you for parallelized runs. If you use Jest to run integration tests on a single resource, that might not be what you really want (a test for listing resources from shared storage might encounter data from a different test suite). In that case you probably know about the <a href="https://jestjs.io/docs/cli#--runinband">--runInBand</a> option that allows you to run tests serially.</p><p>If your tests, however, do not perform a 100% cleanup and are at least a little sensitive to the shared resource, you might encounter random fails. Unless explicitly specified, your tests run in random order, even with the <em>run in band</em> option. You can make the order deterministic by writing a custom <a href="https://github.com/facebook/jest/issues/6194#issuecomment-582428526">TestSequencer</a>. Which of course (coming to the previous point) you cannot write in TypeScript (or at least could not few a months back).</p><h3>Global setup like a box of chocolates</h3><p>Running different tests in different processes takes another toll: global setup. You can have a module that sets up your environment (e.g. connects to the database and runs migrations). You can use a variety of options: <a href="https://jestjs.io/docs/configuration#setupfiles-array">setupFiles</a>, <a href="https://jestjs.io/docs/configuration#setupfilesafterenv-array">setupFilesAfterEnv</a>, or <a href="https://jestjs.io/docs/configuration#globalsetup-string">globalSetup</a>. Can you guess which is used for what?</p><ul><li>globalSetup is run only once (before spawning processes) at the beginning and can be used for e.g. aborting tests based on some configuration.</li><li>setupFilesAfterEnv can be used for setting up individual suites (e.g. starting server for integration tests etc.).</li><li>I have never used setupFiles and I have no idea what it does.</li></ul><p>Life is simply too short to know the setup configuration options for Jest.</p><h3>Invisible output ink</h3><p>Standard output from the tests usually gets out to your terminal, but sometimes it does not. There is a long-running <a href="https://github.com/facebook/jest/issues/2441">issue</a> on GitHub about this from 2016 that is still commented on. I have seen at least two times (<a href="https://github.com/facebook/jest/pull/6871">#6871</a>, <a href="https://github.com/facebook/jest/pull/3895">#3895</a>) in release notes for Jest that this issue is fixed or improved upon, but it is still not reliable.</p><p>I agree that logging things is not a good debugging tool, but it does not mean that it is not useful or that it is an excuse for neglecting the issue for years.</p><h3>Summary: Jest vs. Mocha</h3><p>Jest offers an all-in-one solution for testing that makes it ideal for smaller projects and libraries. It can be a good fit if you can leverage the parallel runs to cut the time without worrying about shared state components, which might be a good fit for frontend development.</p><p>If your tests operate on a shared resource and you cannot afford to run tests asynchronously, you might be better off with an alternative. If you want to use Jest with TypeScript, consider not using ts-jest to avoid issues with fragile dependencies and transpile your tests.</p><p>Would we choose it again today as a replacement for Mocha for larger projects with integration API testing? I know I would not.</p><p><em>Originally published at </em><a href="https://www.ackee.agency/blog/jest-vs-mocha"><em>https://www.ackee.agency/blog/jest-vs-mocha</em></a><em> on November 18, 2021</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4efa1a8cfd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/jest-does-it-test-funny-to-you-d4efa1a8cfd3">Jest: Does It Test Funny to You?</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript: Function composition and recurrent types]]></title>
            <link>https://medium.com/ackee/typescript-function-composition-and-recurrent-types-a9efbc8e7736?source=rss-b6348cffca53------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9efbc8e7736</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[function-composition]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Jaroslav Šmolík]]></dc:creator>
            <pubDate>Wed, 22 May 2019 08:50:46 GMT</pubDate>
            <atom:updated>2022-03-22T18:21:57.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YujICH1A6FXCr7eh.png" /></figure><p>While I was working on our toolkit library <a href="https://github.com/AckeeCZ/desmond">Desmond</a> I stumbled upon a problem when defining the TypeScript definition for a function pipe.</p><p>With help from <a href="https://stackoverflow.com/users/2887218/jcalz">Joe Calzaretta</a>, a software developer working for MIT’s IS&amp;T, I defined type definitions for a variadic function composition in TypeScript, that is in some aspects superior to the existing solutions implemented in popular libraries.</p><p>Adapting the proposed solution I managed to define the HOC function type for composition without overloads, ultimately allowing it to safely type-check function chain for any number of arguments, which is a feature lacking in type definitions of even extremely popular utility libraries such as Lodash.</p><h3>What is pipe?</h3><p>Pipe is a Higher-order variadic function, that performs a left-to-right function composition.</p><p>Here is an example of pipe definition for two arguments.</p><pre>const pipe = (f, g) =&gt; (input) =&gt; g(f(input));</pre><h3>What is Higher-order function?</h3><p>Higher-order function (HOF) is a function that either:</p><ul><li>accepts a function as an argument</li><li>returns a function</li></ul><p>As you can see, the pipe satisfies both arguments inherently.</p><h3>What is a variadic function?</h3><p>Variadic function is a function that accepts any number of arguments. In this case it practically means that pipe can take a single argument, two arguments, etc. and perform the composition.</p><p>For non-variadic functions, we specify <em>arity</em>, which is the number of arguments (unary, n-ary etc).</p><h3>Trivial pipe example</h3><p>Here is a short snippet of code that shows how pipe works and what is to be expected of it.</p><pre>const add = (a: number) =&gt; (b: number) =&gt; a + b;<br>const addConstants = pipe(add(5), add(7));<br>addConstants(0); // 0 + 5 + 7 = 12<br>addConstants(100); // 100 + 5 + 7 = 112</pre><p>This example is banal and does not seem practically useful. However, function composition allows users to write a functional, modular code. We practically use it every day in back-end development for composing middleware handlers.</p><p>At this point, you might wonder, why don’t we use an existing implementation, such as <em>Lodash’s</em> <a href="https://lodash.com/docs/4.17.11#flow">flow</a> or <em>Ramda’s</em> <a href="https://ramdajs.com/docs/#pipe">pipe</a>, both of which would work well for the provided trivial example. But Desmond’s pipe does more than that.</p><p>It handles asynchronous code via promises or async functions and provides a uniform (promise) interface.</p><h3>Desmond’s pipe specification</h3><ol><li>Create a function as left-to-right composition of arguments (arguments are functions)</li><li>First functional argument can be of any arity, while the remaining function must be unary (in JavaScript, a function can return only a single value)</li><li>Signature of the resulting (composed) function has argument(s) of the first function, and return type of the promise of the return type of the last function (even when all or some functions are synchronous)</li><li>Each function in the chain always gets resolved value of the last return. If the previous function returns an array of promises, they are resolved via Promise.all before proceeding.</li></ol><h3>Hold on, that function already exists</h3><p>The closest we got to an existing implementation is <em>Ramda’s</em> <a href="https://ramdajs.com/docs/#pipeP">pipeP</a>.</p><p>It does almost the same thing, but</p><ol><li>It fails if the argument of the first function is a promise</li><li>It does not resolve arrays via Promise.all</li><li>Typescript typings are poor (Typescript typings favour OOP and FP typings are rarely correctly implemented)</li></ol><h3>Implementation</h3><p>The implementation of pipe is fairly short and consists of no more than 8 lines of code (one of which is a comment). You can check it out on <a href="https://github.com/AckeeCZ/desmond/blob/v0.3.0/src/lib/pipe.ts#L85">GitHub</a>.</p><p>It is conscious, readable and does all we wanted from it. The problem is not the execution logic, but the type definition of this function in TypeScript.</p><p>Compare the 8 lines of code to 50 lines of type definitions using overloads, which I wrote for the initial release of pipe in <a href="https://github.com/AckeeCZ/desmond/blob/v0.3.0/src/lib/pipe.ts">Desmond </a><a href="https://github.com/AckeeCZ/desmond/blob/v0.3.0/src/lib/pipe.ts">0.3.0</a> That ratio is insane, and the typing were not even complete.</p><h3>The type problem</h3><p>What is so challenging about the type of the pipe function is the correct chaining of the functions. With the correct typing for the function, the user expects the following features.</p><h3>1. Notify when the chain is broken</h3><p>When user breaks the contract of the function chain, TypeScript should trigger an error:</p><pre>pipe(<br>    () =&gt; 21,<br>    (n: number) =&gt; n * 2,<br>    (n: string) =&gt; n.repeat(5), // Error: number is not assignable to string<br>);</pre><h3>2. Infer the argument type in chain</h3><p>The function type should be inferred as the type of the function argument in pipe, based on the previous function return type.</p><pre>pipe(<br>    () =&gt; 21,<br>    (n: number) =&gt; n * 2,<br>    n =&gt; { /* let n: number */ }, // (inferred from previous return)<br>);</pre><h3>3. Have the correct type of the result</h3><pre>const meaning = pipe(<br>    () =&gt; 21,<br>    (n: number) =&gt; n * 2,<br>    (n: number) =&gt; &#39;Answer: &#39; + n,<br>);<br>// const meaning: () =&gt; string</pre><p>Having this solution for simple function composition without the async features, more or less gives us the solution for our pipe. For simplicity let us assume, we want to achieve this for simple function composition, with the same interface and behavior as mentioned <em>Lodash</em> or <em>Ramda</em> functions.</p><h3>Lodash and Ramda types</h3><p>Do not reinvent the wheel. Lodash and Ramda have TypeScript type definitions, so I looked them up. See for yourself, here are the definitions for <a href="https://github.com/types/npm-ramda/blob/3cf3d0dc69e01b70ab3043d206782b8ef125cca1/src/pipe.d.ts">Ramda pipe</a> and <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/64104e9760065bd498a3d62d98bb05ea26500dc2/types/lodash/common/util.d.ts#L209">Lodash flow</a>.</p><p>In both cases, typings are approached by overloads, which is a standard solution to the types too complex for TypeScript type definition language.</p><p>How is overloading useful here? TypeScript can (with relative ease) express pipe function for a given number of composed functions and arity using template arguments.</p><p>See this commented snippet with definition for arity of two and two functions in the chain:</p><pre>// A1, A2 -- first function arguments<br>// R1 -- first function return<br>// R2 -- second function return<br>// (a1: A1, a2: A2) =&gt; R1 -- first function<br>// (a: R1) =&gt; R2 -- second function<br>// (a1: A1, a2: A2) =&gt; R2 -- result function<br>pipe&lt;A1, A2, R1, R2&gt;(f1: (a1: A1, a2: A2) =&gt; R1, f2: (a: R1) =&gt; R2): (a1: A1, a2: A2) =&gt; R2;</pre><p>Since this is possible, we can use overloads and define one for each possible case. That is obviously a lie, we cannot. There is infinitely many of them. But both Ramda and Lodash do it and it somewhat works, because they cover the most common uses.</p><p>But it is wrong. Here are several reasons:</p><ul><li>Type definitions are huge (sometimes even several times larger than the implementation)</li><li>Types unmaintainable and pain to read or write</li><li>Types are incomplete. Sure you might argue that nobody has a function of arity larger than… what? Five seems reasonable ceiling. But should the types be updated when someone has a function with six arguments?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*a-iFSioNUL81LxVeLaQEZg.png" /></figure><p>NameLoCLoC TypesMax functionsMax arityLodash534974Ramda94566</p><p>For a summary, here is a short preview of Lodash and Ramda discussed functions. The you can compare the lines of code of the implementation and the types. Max functions (number of pipe arguments) and arity (number of arguments for the pipe’s first arguments) show how deep do the overloads go.</p><p><em>(Lines of code are informative, both libraries use custom types for definition and helpers for implementation, this is a rough approximation)</em></p><p>The types are incomplete and reach out to the size of five times larger than the implementation in case of Ramda.</p><h3>Intuitive recurrent types</h3><p>I don’t want to write lengthly type definitions that inherently cannot generally work. I want to write conscious, precise and elegant definitions. Not ones that could be generated by a script.</p><p>Using overloads in this example in TypeScript is like not having meta-programming at all. It is same like not using template arguments in types and defining all possible options with inlined argument types. With overloads. That’s how bad it is. We just don’t see it, because we have gotten used to it.</p><p>I despised the idea to the extent I tried to write the definition without overloads. For simplicity, all functions are unary, including the first one (extending the arity without overloads not an issue, as I will discuss another time).</p><pre>type Chain&lt;In, Out = In, Tmp = any&gt; = []<br>    | [(arg: In) =&gt; Out]<br>    | [<br>        (arg: In) =&gt; Tmp,<br>        ...Chain&lt;Tmp, Out&gt;<br>    ];<br>declare function flow&lt;In, Out&gt;(...fns: Chain&lt;In, Out&gt;): Out</pre><p>Is it not beautiful? This type is a truly variadic function, it has no limits in number of arguments. It type-checks the function chain, matching outputs to inputs.</p><p>There is a single flaw to it. It does not compile since it is not a valid TypeScript type definition.</p><h3>Compilation errors</h3><ul><li>Type alias &#39;Chain&#39; circularly references itself.</li></ul><p>This is the core issue. Recursion in TypeScript types is allowed only in some cases with interfaces, using a middleman type. This shall be discussed further, but for proof, see <a href="https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540">the cheesy example</a>.</p><ul><li>A rest element type must be an array type.</li></ul><p>Another lesser issue is tuple types are not allowed to be spread at the moment. There is a <a href="https://github.com/Microsoft/TypeScript/issues/24902">proposal</a> for that support however. (While writing this article, the mentioned issue had been fixed, the error still persists probably not because Chaindoes not conform to Array, but because its definition is corrupted due to the previous error and evaluated.)</p><h3>Getting help</h3><p>I am no TypeScript guru, at the time I did not even fully understand why Chain is not an array type and why the second error even appeared in the compiler.</p><p>I tried to search for the related issues in TypeScript and discovered that almost every discussion even remotely related to word <em>recursion</em> splashes down to the argument about <a href="https://github.com/Microsoft/TypeScript/issues/3496">defining JSON structure in TypeScript</a>, which is in this case completely irrelevant.</p><p>In the end, I created a <a href="https://stackoverflow.com/questions/53173203/typescript-recursive-function-composition">question on StackOverflow</a>. To my pleasant surprise, to this day there is no reference to JSON structure type in the thread.</p><p>Joe Calzaretta gave me in his answer type definition of the flow function. Here it is (unedited):</p><pre>type Lookup&lt;T, K extends keyof any, Else=never&gt; = K extends keyof T ? T[K] : Else<br>type Tail&lt;T extends any[]&gt; = <br>  ((...t: T) =&gt; void) extends ((x: any, ...u: infer U) =&gt; void) ? U : never;<br>type Func1 = (arg: any) =&gt; any;<br>type ArgType&lt;F, Else=never&gt; = F extends (arg: infer A) =&gt; any ? A : Else;<br>type AsChain&lt;F extends [Func1, ...Func1[]], G extends Func1[]= Tail&lt;F&gt;&gt; =<br>  { [K in keyof F]: (arg: ArgType&lt;F[K]&gt;) =&gt; ArgType&lt;Lookup&lt;G, K, any&gt;, any&gt; };<br>type LastIndexOf&lt;T extends any[]&gt; =<br>  ((...x: T) =&gt; void) extends ((y: any, ...z: infer U) =&gt; void)<br>  ? U[&#39;length&#39;] : never</pre><pre>declare function flow&lt;F extends [(arg: any) =&gt; any, ...Array&lt;(arg: any) =&gt; any&gt;]&gt;(<br>  ...f: F &amp; AsChain&lt;F&gt;<br>): (arg: ArgType&lt;F[0]&gt;) =&gt; ReturnType&lt;F[LastIndexOf&lt;F&gt;]&gt;;</pre><p>It has it’s drawbacks. It is relatively complex and has a parade of tough meta types that you need to fight through. The definition is all but conscious or elegant. It looks ugly, but it works!</p><p>Let us see how it stands to our expectations.</p><h3>How it holds up</h3><h4>1. Notify when chain is broken</h4><pre>flow(<br>  (n: number) =&gt; n * 2, // Type &#39;string&#39; is not assignable to type &#39;boolean&#39;.<br>  (n: number) =&gt; &#39;Answer: &#39; + n,<br>  (res: boolean) =&gt; res + &#39;!&#39;,<br>);</pre><p>The validation works, but is at the wrong line. This is actually a bug in TypeScript error messages. I started poking around it and Joe created an issue <a href="https://github.com/Microsoft/TypeScript/issues/28505">#28505</a> in TypeScript itself and it is now set on TypeScript 3.3 milestone.</p><h4>2. Infer argument type in chain</h4><pre>flow(<br>    (n: number) =&gt; n * 2,<br>    n =&gt; { /* let n: any */ }, // (NOT inferred from previous return)<br>);</pre><p>This is unfortunately a drawback of this solution. It is caused by the <em>imperative validation</em> type definition suggested by Joe, rather than my proposed <em>recursively constructive</em> solution (which is at this time invalid Typescript code).</p><h4>3. Have correct type of the result</h4><p>Result type inference works as expected:</p><pre>const foo = flow(<br>    (n: number) =&gt; n * 2,<br>    (n: number) =&gt; &#39;Answer: &#39; + n,<br>    (res) =&gt; res + &#39;!&#39;,<br>);<br>// const foo: (arg: number) =&gt; string</pre><h3>Why are recurrent types forbidden?</h3><p>An excellent question. As it appears from the <a href="https://github.com/Microsoft/TypeScript/issues/27102"><em>Design Meeting Notes, 9/14/2018</em></a> (section <em>Recursive Types</em>), recursive types are not likely to be supported in the near future. The main argument against it, is an uncontrollable computationally intensive reference resolution.</p><h3>Summary</h3><p>With help from Joe Calzaretta, I managed to implement type definition for pipe that handles n-ary first functions and any number of arguments. At this point, we can proudly add Desmond to the existing table, having very brief type definition, and unseen argument dynamics, even though suffering the type inference in the function chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*arcTmS5rFGscWtSN_x8CqA.png" /></figure><p>You can see the implementation for yourself at <a href="https://github.com/AckeeCZ/desmond/blob/master/src/lib/pipe.ts">GitHub</a>.</p><p>Next time I might show you how to handle arity and explain the Joe’s solution step-by-step, because it is fascinating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9efbc8e7736" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ackee/typescript-function-composition-and-recurrent-types-a9efbc8e7736">Typescript: Function composition and recurrent types</a> was originally published in <a href="https://medium.com/ackee">Ackee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>