<?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 Kjartan Rekdal Müller on Medium]]></title>
        <description><![CDATA[Stories by Kjartan Rekdal Müller on Medium]]></description>
        <link>https://medium.com/@kjartanmuller?source=rss-25140386f2e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UYMCOrMWDBkmSQqPyV5TEw.jpeg</url>
            <title>Stories by Kjartan Rekdal Müller on Medium</title>
            <link>https://medium.com/@kjartanmuller?source=rss-25140386f2e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:55:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kjartanmuller/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[HTMX served from static as a SPA?]]></title>
            <link>https://itnext.io/htmx-served-from-static-as-a-spa-5477a28d0a7f?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5477a28d0a7f</guid>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 13:48:55 GMT</pubDate>
            <atom:updated>2025-06-04T17:41:56.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXcsrcgaOu7Pr4VPkQ0wbw.png" /></figure><p>I have nothing against using js-frameworks, and have used several over the years, but I have weak spot for initiatives like HTMX that try to work close to the metal — meaning web as platform. Also, I think the last trend of mixing SSR into the frameworks, and concequently as a part of the dev toolbox, is healthy.</p><p>So why this clickbait title? Well, since first reading about HTMX. I got this itch to scratch about how this could be used with service workers. I was also triggered by this <a href="https://simonwillison.net/2025/Apr/28/give-it-away-for-free/">blog post</a> by Simon Willis, emphasizing the importance of serving from static:</p><blockquote>If you want to create completely <strong>free software</strong> for other people to use, the absolute best delivery mechanism right now is static HTML and JavaScript served from a free web host with an established reputation. (Simon Willis)</blockquote><p>So what I have done is to create a POC of how even HTMX can be served from static, installed as a standalone app, even running its own database locally. And while the title may sound preposterous, it is all about love for web as platform.</p><p>The POC is based on the contact app used as an example in the HTMX book <a href="https://hypermedia.systems/">Hypermedia Systems</a> (recommended). Source code for the original is here: <a href="https://github.com/bigskysoftware/contact-app">bigskysoftware/contact-app</a>. My own version is here: <a href="https://github.com/kjartanm/htmx-sw">kjartanm/htmx-sw</a>. It is a POC, so it is missing the usual checks and redundancies that make a proper robust application. A live demo is running here: <a href="https://htmx-sw.krmuller.workers.dev/">My Contacts</a>.</p><p>So, how can we serve HTMX from static?</p><h4>Service Workers to the rescue</h4><p>The main idea is that when serving HTMX from static, a service worker (SW) can act as a replacement for a server, providing the necessary SSR-capabilities. While the usual usecase for a SW is to provide caching and offline possibilities, it is possible to use the core mechanism of intercepting network requests to hook up a router, and to treat that router mostly as you would an API-router on a server. Here I use itty-router (<a href="https://itty.dev/itty-router/">itty-router — itty.dev</a>), which is very small, but still powerful enough for my POC here. The basics of adding the router to the SW, is very simple:</p><pre>//in a service worker file<br><br>import { AutoRouter } from &#39;./itty-router-5.0.18/index.js&#39;<br><br>const router = AutoRouter()<br>router<br>   .all( ... )<br>   .get( ... )<br>//etc<br><br>self.addEventListener(&#39;fetch&#39;, async (event) =&gt; {<br>    event.respondWith((async () =&gt; {<br>        return router.fetch(event.request)<br>    })())<br>})</pre><p>The route-handler can act in different ways. If the response is cached, it can return the cached response, if it needs to get the resource from the network, it just acts as a proxy, if it is something local, it can generate a response, or it can be a mix of these variants. For example, for static assets, it can use a cache first strategy:</p><pre>router<br>    .get(&#39;/assets/*&#39;, cacheFirst)<br>    .get(&#39;/npm/*&#39;, cacheFirst)<br><br><br>###<br>const putInCache = async (request, response) =&gt; {<br>  const cache = await caches.open(cacheName);<br>  await cache.put(request, response);<br>}<br><br>export const cacheFirst = async (_request, context, event) =&gt; {<br>  const request = _request.clone()<br>  const cachedResponse = await caches.match(event.request);<br>  if (cachedResponse) return cachedResponse;<br><br>  const response = await event.preloadResponse;<br>  if (response) return response;<br><br>  try {<br>    const responseFromNetwork = await fetch(request);<br>    event.waitUntil(putInCache(request, responseFromNetwork.clone()));<br>    return responseFromNetwork;<br>  } catch (error) {<br>    return new Response(&quot;Network error happened&quot;, {<br>      status: 500,<br>      headers: { &quot;Content-Type&quot;: &quot;text/plain&quot; },<br>    })<br>  }<br>}</pre><p>Resources in /assets/* are resources coming from the same origin as the SW, so they are pre-cached by the SW when installed. The resources from /npm/* are actually from CDN, so they are fetched from network first time, and then cached for later.</p><h4>SQLite, WebAssembly (WASM) and Origin Private File System (OPFS)</h4><p>But the main routes in the app, deals with generated content. This content is managed in a simple database for contacts, and the routes creates a sort of CRUD-based API for managing these contacts from the UI, but where the responses are rendered HTML for HTMX instead of the usual JSON that one would expect.</p><p>Having a database running locally is made possible by using SQLite compiled to WASM. There are several options if you want to use WASM-versions of SQLite. I went with <a href="https://sql.js.org/">https://sql.js.org/</a>, since it had the right level of abstractions for my purpose here.</p><p>The database is persisted with the help of <a href="https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system">Origin Private File System</a> (OPFS). OPFS is another one of those supercool APIs that is mostly widely available in browsers, but unfortunately with some differences in implementation. Initially I used the following for initiating a db from file, and for writing back to OPFS:</p><pre>import {initSqlJs} from &#39;./sql-wasm.js&#39;<br><br>export const getDBFromOPFS = async (fileName) =&gt; {<br>    const SQL = await initSqlJs({<br>        locateFile: file =&gt; `/assets/db/${file}`<br>    })<br>    const opfsHandle = await navigator.storage.getDirectory()<br>    const fileHandle = await opfsHandle.getFileHandle(fileName, { create: true })<br>    const file = await fileHandle.getFile()<br>    const arrayBuffer = await file.arrayBuffer()<br>    return new SQL.Database(new Uint8Array(arrayBuffer))<br>}<br><br>export const saveDBToOPFS = async (db, fileName) =&gt; {<br>    let success = true<br>    try {<br>        const opfsHandle = await navigator.storage.getDirectory()<br>        const fileHandle = await opfsHandle.getFileHandle(fileName, { create: true })<br>        const writable = await fileHandle.createWritable()<br>        const data = db.export()<br>        await writable.write(data)<br>        await writable.close()<br>    } catch (err) {<br>        success = false<br>    }<br>    return success<br>}</pre><p>This worked as a charm on Edge and Chrome on windows, but not in Safari or on iOS in general. Going through the documentation, I found that Safari doesn’t support .createWriteable , and while it is possible to use alternatives for writing, that doesn’t work in a service worker, only in web workers. So I had to move the write part to a web worker, using messaging from the service worker to provide the data. It is not as elegant, but it works:</p><pre>onmessage = async (event) =&gt; {<br>    if (event.data.type === &#39;update&#39;) {<br>        try {<br>            const { data, fileName } = event.data<br>            const opfsHandle = await navigator.storage.getDirectory()<br>            const fileHandle = await opfsHandle.getFileHandle(fileName, { create: true })<br>            const accessHandle = await fileHandle.createSyncAccessHandle();<br>            const writeSize = accessHandle.write(data, { &quot;at&quot;: 0 });<br>            accessHandle.flush();<br>            accessHandle.close();<br>            postMessage({<br>                type: &#39;updateCompleted&#39;,<br>                message: &#39;Database saved successfully. Size: &#39; + writeSize,<br>            })<br>        } catch (err) {<br>            postMessage({<br>                type: &#39;error&#39;,<br>                message: &#39;Error while saving database: &#39; + err.message,<br>            })<br>        }<br>    }else{<br>        postMessage({<br>            type: &#39;info&#39;,<br>            message: &#39;Unhandled message type: &#39; + event.data.type,<br>        })<br>    }<br>}</pre><p>I made a class for interacting with the db, and this class is then used by the routes. To go through how this works with HTMX, I’ll use viewing the details of a contact as example. In the list of contacts, you’ll find links rendered by following snippet:</p><pre>&lt;a hx-boost=&quot;true&quot; hx-target=&quot;main&quot; href=&quot;/${contact.id}&quot;&gt;${contact.name}&lt;/a&gt;</pre><p>What this link says, is that when clicked, the request should be handled as AJAX by HTMX (hx-boost), and that the response should be rendered in the &lt;main&gt;&lt;/main&gt;-element on the HTML-page (hx-target). The route responding to the href-attribute is following:</p><pre>.get(&#39;/:id&#39;, async ({ params, headers }, { db, render, html, }, event) =&gt; {<br>    const contact = await db.getContact(params.id)<br>    if (!contact || contact.length === 0) {<br>        return new Response(render(String, layout(html`&lt;p&gt;Contact not found&lt;/p&gt;`)), { status: 404, headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } })<br>    } else if (headers.get(&#39;Hx-request&#39;)) {<br>        return new Response(render(String, contactView(contact[0])), { status: 200, headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } })<br>    } else {<br>        return new Response(render(String, layout(contactView(contact[0]))), { status: 200, headers: { &#39;Content-Type&#39;: &#39;text/html&#39; } })<br>    }<br>})</pre><p>What the route does, is to check if the request is sent by HTMX, for example by clicking the above link (Hx-request in the header). If so, it returns a response rendered with only the contactView-template. This response is then put inside the main-element by HTMX without refreshing the whole page. If not requested by HTMX, for example when refreshing a page with contact-id in the url, it serves the whole page by embedding the contactView-template within the layout-template. I use <a href="https://github.com/WebReflection/uhtml-ssr">uhtml-ssr</a> for templating here. It is based on template literals and adds very little extra js to the total.</p><p>HTMX has a lot of functionality like these attributes and headers that helps to make a smooth experience, with the default browser functionality as a fallback.</p><p>So that is the basic elements of how to serve HTMX from static. Full POC/example can be found in <a href="https://github.com/kjartanm/htmx-sw">kjartanm/htmx-sw</a>. In addition to what is mentioned here, it can also be installed as PWA, and uses DaisyUI and Tailwind for components and styling. Even adjusting dark/light-theme according to preferences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5477a28d0a7f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/htmx-served-from-static-as-a-spa-5477a28d0a7f">HTMX served from static as a SPA?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attribute Based Access Control with Open Policy Agent and WebAssembly]]></title>
            <link>https://itnext.io/attribute-based-access-control-with-open-policy-agent-and-webassembly-a050064c42e4?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a050064c42e4</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[abac]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 14:36:55 GMT</pubDate>
            <atom:updated>2024-07-08T07:52:56.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*lk1a_wFtmof4eIKKyFmCyw.png" /></figure><p><em>Thoughtworks published earlier this year their annual Technology Radar. Among the tools listed for trial, you will find OPA (Open Policy Agent). Here I’ll describe a way to experiment with this technology in an easy manner.</em></p><p><a href="https://www.openpolicyagent.org/">OPA</a> is described as a “<a href="https://www.thoughtworks.com/radar/tools/summary/open-policy-agent-opa">uniform framework and language for declaring, enforcing and controlling policies</a>”. One usecase is to use it to handle ABAC (Attribute Based Access Control). I will not go into details regarding ABAC vs RBAC (Role Based Access Control). AWS has a <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/saas-multitenant-api-access-authorization/access-control-types.html">nice section about ABAC and RBAC</a> and you probably should read in that regard. But let me just say that OWASP has <a href="https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html#prefer-attribute-and-relationship-based-access-control-over-rbac">a recommendation</a> that you should prefer ABAC over RBAC.</p><p>I have made PoC of how to deploy and use an Opa policy that is compiled into Wasm, and then deployed as part of a service on Cloudflare Workers. <a href="https://github.com/kjartanm/opa-poc">The PoC is available on Github</a>. This setup should make it easy to experiment with Opa.</p><h4>How it works</h4><p>OPA has a very expressive language, called REGO, that you can use to write a policy. This policy is combined with some long term data when running the policy engine. The data are a set of some sort of relatively stable attributes that is used by the policy when evaluating inputs.</p><p>In my toy-example the scenario is an endpoint acting as a gateway for an API for a team-based todos application, using OPA for access control. In that scenario <em>input </em>is a set of attributes based on the authenticated request, <em>data </em>are some department and team-structure in a small company, and the <em>policy </em>says something about what sort of requests can be allowed with that data as context.</p><p>OPA comes in different flavours. You can download, build and run the app, you can use a docker version, you can use a managed service, and you can even compile the REGO based policy into Wasm and run it in suitable environments. And it is the last option, compililing it into Wasm, which I am using here.</p><p>Whatever way you want to run it, the hard part about using OPA is writing policies in REGO. I guess some will find similiarites with other languages, but for most, the syntax will feel very unfamiliar. But the expressiveness of the language for writing policies, makes it worth it, in my opinion. There is <a href="https://play.openpolicyagent.org/">playground</a> you can use for testing and learning the language.</p><p>Here is my toy example and a short walk through:</p><pre>package example<br>import rego.v1<br><br>default allow := false<br><br>is_view_action := input.method == &quot;GET&quot;<br>is_view_or_edit_action := input.method in [&quot;POST&quot;, &quot;GET&quot;, &quot;UPDATE&quot;, &quot;DELETE&quot;]<br><br># the authenticated user<br>user := input.payload.sub<br><br># the employee whos todos you want to see &#39;/todos/[employeeid]&#39;<br>employee := employeeId if {<br>    input.path = [&quot;todos&quot;, employeeId]<br>}<br><br># if the path is not &#39;/todos/[employeeid]&#39; the employee is set to &#39;none&#39;<br>employee := employeeId if {<br>    input.path[0] != &quot;todos&quot;<br>    employeeId := &quot;none&quot;<br>}<br><br># aggretates an array with direct reports in your department if manager<br>dep_responsibilities contains direct_report if {<br>    manages := data.managers[user]<br>    some direct_report in data.departments[manages]<br>}<br><br># araggretates an array with team members that report to you from all projects if project manager<br>pm_responsibilities contains team_member if {<br>    some projects in data.pm[user]<br>    some team_member in data.projects[projects]<br>}<br><br># you can both view and edit your own todos<br>allow if {<br>    is_view_or_edit_action<br>    user == employee<br>}<br><br># you can view todos for your direct reports<br>allow if {<br>    is_view_action<br>    employee in dep_responsibilities<br>}<br><br># you can view all todos for team member in the projects you manage<br>allow if {<br>    is_view_action<br>    employee in pm_responsibilities<br>}<br><br># you can both view and edit todos for team members in context of the projects you manage<br>allow if {<br>    is_view_or_edit_action<br>    input.path = [&quot;projects&quot;, projectid, &quot;todos&quot;, teamEmployee]<br>    projects := data.pm[user]<br>    projectid in projects<br>    team_responsibilities := data.projects[projectid]<br>    teamEmployee in team_responsibilities<br>}<br><br># use as entrypoint if you want some more data with your evaluation<br>partial := {<br>    &quot;allowed&quot;: allow, <br>    &quot;dep-responsibilities&quot;: dep_responsibilities,<br>    &quot;pm-responsibilities&quot;: pm_responsibilities<br>}</pre><ul><li><strong>default allow := false</strong> means default is no access.</li><li><strong>this_view_action</strong>, <strong>is_view_or_edit_action</strong>, <strong>employee</strong>, <strong>dep_responsinbilities</strong> and <strong>pm_responsibilities</strong> sets up some variables that are used during evaluation.</li><li><strong>allow </strong>statements express in what sort of circumstances access and actions can be allowed. First one says you can do everything with your own todos, second that your boss can see your todos, third that your project manager can see your todos, last that your project manager can edit your todos in context of the project. If <em>any part</em> of an allow statement evaluates to false, the statement in total evaluates to false. If <em>any allow statement</em> evaluates to true, allow is set as true and access allowed. This means logical AND within statement, and logical OR between similar statements.</li><li><strong>partial </strong>can be used as entrypoint if you want fuller response from the evaluation.</li></ul><p>The example data structure:</p><pre>{<br>    &quot;managers&quot;: {<br>        &quot;bob&quot;: &quot;development&quot;,<br>        &quot;carol&quot;: &quot;it&quot;<br>    },<br>    &quot;pm&quot;: {<br>        &quot;peter&quot;: [&quot;proj1&quot;, &quot;proj2&quot;],<br>        &quot;quentin&quot;: [&quot;proj3&quot;]<br>    },<br>    &quot;projects&quot;: {<br>        &quot;proj1&quot;: [&quot;betty&quot;, &quot;chris&quot;],<br>        &quot;proj2&quot;: [&quot;alice&quot;, &quot;fionna&quot;],<br>        &quot;proj3&quot;: [&quot;dave&quot;, &quot;grant&quot;]<br>    },<br>    &quot;departments&quot;: {<br>        &quot;development&quot;: [&quot;alice&quot;, &quot;betty&quot;, &quot;dave&quot;, &quot;john&quot;],<br>        &quot;it&quot;: [&quot;chris&quot;, &quot;donna&quot;],<br>        &quot;sales&quot;: [&quot;eric&quot;, &quot;fionna&quot;],<br>        &quot;pr&quot;: [&quot;grant&quot;, &quot;holly&quot;],<br>        &quot;pm&quot;: [&quot;peter&quot;, &quot;quentin&quot;]<br>    }<br>}</pre><p>So when running this with an example input like this:</p><pre>{<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;payload&quot;: {<br>        &quot;sub&quot;: &quot;peter&quot;,<br>        &quot;iat&quot;: 1516239022,<br>        &quot;department&quot;: &quot;pm&quot;,<br>        &quot;tenant&quot;: &quot;ACME&quot;<br>    },<br>    &quot;path&quot;: [&quot;todos&quot;, &quot;chris&quot;]<br>}</pre><p>Will give a response like this:</p><pre>[<br>    {<br>        &quot;result&quot;: true<br>    }<br>]</pre><h4>How to compile and deploy</h4><p>The ability to compile REGO policies into Wasm is part of the Opa application. I find it easiest to use the docker version and a script for running it for that purpose. Here is the script i use with this proof of concept:</p><pre>touch &quot;$(pwd)/src/opa/bundle.tar.gz&quot;<br>chmod a+rw &quot;$(pwd)/src/opa/bundle.tar.gz&quot;<br>docker run -v &quot;$(pwd)/src/opa:/src&quot; openpolicyagent/opa build -t wasm -e example/allow ./src/todo.rego -o ./src/bundle.tar.gz<br>tar xfC &quot;$(pwd)/src/opa/bundle.tar.gz&quot; &quot;$(pwd)/src/opa/&quot; &quot;/policy.wasm&quot;</pre><p>The build command has Wasm as target and allow as entrypoint and creates a bundle. The Wasm is then extracted from the bundle and available for the rest of the code. When deploying the code, this step can be automated, for example with a Github action like this:</p><pre>name: GitHub Opa Action<br>run-name: ${{ github.actor }} is deploying OPA Wasm 🚀<br>on: [push]<br>jobs:<br>  Explore-GitHub-Actions:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Check out repository code<br>        uses: actions/checkout@v3<br>      - name: Install dependencies<br>        run: npm ci<br>      - name: Run script<br>        run: scripts/opa.sh<br>      - name: Deploy service<br>        run: npm run deploy<br>        env: <br>          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}<br>          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}</pre><p>This action checks out the code, runs the Opa script (remember to set execute permission), and then runs the deploy script in the package.json with the necessary variables set on the environment.</p><h4>How to use the Wasm</h4><p>In my PoC I deploy the Wasm on Cloudflare Workers. Initially this is a stateless serverless environment, making it less useful to load the engine with long term data. But it is possible to use a so called Durable Object on Cloudflare to enable some sort of statefulnes. There is some drawbacks with this, of course. Using Durable Objects links the service to a certain location, and it will be taken down during inactivity meaning risk of some startup latency on irregular intervals.</p><p>In my PoC-scenario, the application is assumed to be a multi-tenant service, and I link both the Durable Objects and data structures to a single tenent. This could be a reasonable way to handle the different trade offs if the users of the tenant is somewhat co-located and there is enough activity to keep the Durable Object running. The data comes from the Key-Value store that Cloudflare Workers offer. For experimenting, data can be edited directly in your Cloudflare Dashboard and uploaded to the KV-store.</p><p>The Durable Object is defined as following:</p><pre>import policyWasm from &#39;./opa/policy.wasm&#39;<br>import { loadPolicy } from &#39;@open-policy-agent/opa-wasm&#39;<br><br>const SECONDS = 1000<br><br>export class OPAAuthorizer {<br>  constructor(state, env) {<br>    this.state = state<br>    this.env = env<br>    this.updatedAt = 0<br>  }<br><br>  async fetch(request) {<br>    let input<br>    try {<br>      input = await request.json()<br>    } catch (error) {<br>      return new Response(&#39;Bad Request.&#39;, { status: 400 })<br>    }<br><br>    // If not already initiated, load the Wasm using the js-loader from Opa<br>    if (!this.policy) {<br>      this.policy = await loadPolicy(policyWasm).catch((error) =&gt; {<br>        return new Response(&#39;Failed to load policy.&#39;, { status: 500 })<br>      })<br>    }<br><br>    // If not already initiated, check which tenant should be used for <br>    // fetching data from the KV-store. Get the data, and load it into<br>    // the policy engine.<br>    if (!this.tenant) {<br>      const url = new URL(request.url)<br>      const tenant = url.pathname.substring(1).toLowerCase()<br>      const data = await this.env.TENANT_DATA.get(tenant)<br>      if (data === null) {<br>        return new Response(&#39;Not Found.&#39;, { status: 404 })<br>      } else {<br>        this.policy.setData(JSON.parse(data))<br>        this.updatedAt = Date.now()<br>        this.tenant = tenant<br>      }<br>    }<br><br>    // Set up an alarm to update data if changes.<br>    const currentAlarm = await this.state.storage.getAlarm()<br>    if (currentAlarm === null) {<br>      this.state.storage.setAlarm(Date.now() + 180 * SECONDS)<br>    }<br><br>    // Evaluate the input and return the result<br>    const resultSet = this.policy.evaluate(input)<br><br>    return new Response(JSON.stringify(resultSet), {<br>      headers: {<br>        &#39;content-type&#39;: &#39;application/json;charset=UTF-8&#39;,<br>        &#39;x-updatedat&#39;: this.updatedAt,<br>      },<br>    })<br>  }<br><br>  async alarm() {<br>    const data = await this.env.TENANT_DATA.get(this.tenant)<br>    if (data) {<br>      this.policy.setData(JSON.parse(data))<br>      this.updatedAt = Date.now()<br>    }<br>  }<br>}</pre><p>The Durable Object is then initated by worker:</p><pre>export { OPAAuthorizer } from &#39;./authorizer&#39;<br><br>const fetch = async (request, env) =&gt; {<br>  let url = new URL(request.url)<br><br>  //Get the tenant from the path<br>  let tenant = url.pathname.substring(1)<br>  if (!tenant) {<br>    return new Response(&#39;Bad Request.&#39;, { status: 400 })<br>  } else if (request.method !== &#39;POST&#39;) {<br>    return new Response(&#39;Method not allowed.&#39;, { status: 405 })<br>  }<br><br>  // Get the Durable Object linked to the tenant<br>  let id = env.AUTHORIZER.idFromName(tenant)<br>  let obj = env.AUTHORIZER.get(id)<br>  let resp = await obj.fetch(request)<br>  return resp<br>}<br><br>export default {<br>  fetch,<br>}</pre><p>The deployed worker can then act as a <em>Policy Decision Point</em> for the part of the service acting like a <em>Policy Enforcement Point</em>, like a gateway. See the main illustration for a sort of architectural description.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a050064c42e4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/attribute-based-access-control-with-open-policy-agent-and-webassembly-a050064c42e4">Attribute Based Access Control with Open Policy Agent and WebAssembly</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easier Service Worker caching with Routing]]></title>
            <link>https://itnext.io/easier-service-worker-caching-with-routing-323d347d95d3?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/323d347d95d3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 22:39:09 GMT</pubDate>
            <atom:updated>2022-02-26T09:19:28.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOuhqmCo4X-RE4a-7MyJEA.jpeg" /><figcaption><a href="https://pxhere.com/en/photo/187030?utm_content=shareClip&amp;utm_medium=referral&amp;utm_source=pxhere">https://pxhere.com/en/photo/187030?utm_content=shareClip&amp;utm_medium=referral&amp;utm_source=pxhere</a></figcaption></figure><p>A service worker is a really powerful tool in the browser toolbox, but it can be hard to wrap your head around it, and not least to model and organize the different flows in a maintainable way. Using a routing based pattern, similar to what you find in the Node Express framework can help you with that. And that is what I have experimented with here. Similar things have been done before. A library like Workbox, for example, implements routing as part of the API. But here I will explore a <em>routing first alternative</em> to create a more flexible and lightweight option.</p><p>For that I’m using <em>itty router</em> (<a href="https://github.com/kwhitley/itty-router">https://github.com/kwhitley/itty-router</a>). <em>itty router</em> is a very small, lightweight, but still powerful routing library that I came across experimenting with Cloudflare Workers. Cloudflare Workers is a FaaS platform that’s based on the Service Worker API, so <em>itty router</em> can be used within the browser without any extra effort.</p><h3>Short intro to itty routers</h3><p>With <em>itty router</em>, a single route can defined like this:</p><pre>router.get(&#39;/hello&#39;, request =&gt; {<br>  return new Response(&#39;Hello World!&#39;)<br>})</pre><p>There are specially two aspects of <em>itty router</em> that makes it so useful within a service worker. One, it uses a middleware pattern so you can chain handlers. If the first one doesn’t return a respons, the request is moved to the next one:</p><pre>router.get(&#39;/hello&#39;, handler1, handler2)</pre><p>The other important thing, is that while a request is the only expected argument for the handlers, it is possible to register the main router handler with additional arguments that will be passed down the chain:</p><pre>router.get(&#39;/hello&#39;, (request, user) =&gt; {<br>  return new Response(`Hello ${ user.name }!`)<br>})</pre><pre>addEventListener(&#39;fetch&#39;, event =&gt;<br>  event.respondWith(router.handle(event.request, user))<br>)</pre><h3>Basic setup</h3><p>So, with that in mind, we can see how that can help us implement the different patterns/strategies associated with service workers, like CacheFirst or NetworkFirst. But first the basic setup. The service worker can be loaded and registered from the HTML like this:</p><pre>&lt;script type=&quot;module&quot;&gt;<br>    const reg = await navigator.serviceWorker.register(&#39;/sw.js&#39;, {<br>        type: &#39;module&#39;,<br>    });<br>&lt;/script&gt;</pre><p>With this PoC I use ES Modules, and that has to be reflected in both the script tag and within the registration of the service worker. The root for the service worker, is pretty basic:</p><pre>import { cacheName, coreAssets } from &#39;./config.js&#39;;<br>import router from &#39;./router&#39;;</pre><pre>self.addEventListener(&#39;install&#39;, function (event) {<br>    // Cache core assets<br>    event.waitUntil(caches.open(cacheName).then(function (cache) {<br>        for (let asset of coreAssets) {<br>            let req = new Request(asset)<br>            cache.add(req);<br>        }<br>        return cache;<br>    }));<br>});</pre><pre>self.addEventListener(&#39;fetch&#39;, async event =&gt; {<br>    event.respondWith(router.handle(event.request, {onLine: navigator.onLine}, event))<br>})</pre><p>Some config for pre-caching, and onLine status set on the context object. The main work being done by the imported router, which could look something like this:</p><pre>import { Router } from &#39;itty-router&#39;;<br>import { handler1, handler2 } from &#39;./handlers.js&#39;;</pre><pre>const router = Router()</pre><pre>//Add routes<br>router.get(&#39;/assets&#39;, handler1 )<br>router.get(&#39;*&#39;, handler2)<br>...</pre><pre>export default router;</pre><h3>Basic SW strategies</h3><p>So, CacheFirst and NetworkFirst, then. Lets first define a handler for retrieving a response from cache:</p><pre>const ifCacheRespond = async (request, context, event) =&gt; {<br>    const response = await caches.match(request);<br>    if (response) {<br>        return response<br>    }<br>}</pre><p>Similar a handler for network response. It checks online status before firing off a fetch:</p><pre>const ifNetworkRespond = async (request, context, event) =&gt; {<br>    if(context.onLine){<br>        let response = await fetch(request);<br>        if (response &amp;&amp; response.ok) {<br>            return response;<br>        }<br>    }<br>}</pre><p>A CacheFirst strategy can thus be expressed like this:</p><pre>router.get(&#39;/assets/*&#39;, ifCacheRespond, ifNetworkRespond, handleError)</pre><p>If ifCacheRespond finds a response in the cache, it returns this response. If not, it passes the request on to ifNetworkRespond. handleError is there to pick up total failures in some way or other. Alternatively you can use a default route at the end to handle those cases, since the router will pass the request to the next route if the route in question doesn’t return any response.</p><p>So how would we then express a NetworkFirst strategy? Yes, of course, we can just swap the sequence 😁:</p><pre>router.get(&#39;/assets/*&#39;, ifNetworkRespond, ifCacheRespond, handleError)</pre><p>For a bit more complex strategies, we need to add to the flow. But they can still be expressed in a similar manner. For example with CacheAsYouGo, you need to add the response to the cache before you return it. A route to enable this strategy can be defined like the following:</p><pre>router.get(&#39;/articles/*&#39;, ifCacheRespond, getNetworkResponse, addToCache, ifNetworkRespond, handleError)</pre><p>The first one is as before. If you have the response in the cache, serve it. If not, the flow moves to the next handler:</p><pre>const getNetwork = async (request, context, event) =&gt; {<br>    if (context.onLine) {<br>        const response = context.networkResponse || await fetch(request);<br>        if (response &amp;&amp; response.ok) {<br>            console.log(&quot;response.ok&quot;, response)<br>            context.networkResponse = response;<br>        }<br>    }<br>}</pre><p>This handler doesn’t return the network response, but adds it to the context to be available for handlers further down the chain, like addToCache :</p><pre>const addToCache = async (request, context, event) =&gt; {<br>    const response = context.networkResponse;<br>    if (response &amp;&amp; response.ok) {<br>        let responseClone = response.clone();<br>        caches.open(cacheName).then(async (cache) =&gt; {<br>            cache.put(request, responseClone);<br>        });<br>    }<br>}</pre><p>And we need to change ifNetworkRespond to use the response on the context object if available:</p><pre>const ifNetworkRespond = async (request, context, event) =&gt; {<br>    if (context.onLine) {<br>        const response = context.networkResponse || await fetch(request);<br>        if (response) {<br>            context.networkResponse = response;<br>        }<br>        if (response &amp;&amp; response.ok) {<br>            return response;<br>        }<br>    }<br>}</pre><p>To enable a strategy like StaleWhileRevalidate, we need expand this a little bit. With StaleWhileRevalidate you want to use the cache, but update the cache in the background without waiting for it, so that a next hit will use an updated resource:</p><pre>router.get(&#39;/&#39;, revalidateCache, ifCache, ifNetworkRespond, handleError)</pre><p>Here you want to start revalidating, but not wait for it if you have a cache. So revalidateCache creates a promise for it instead, and moves on:</p><pre>const revalidateCache = async (request, context, event) =&gt; {<br>    if (context.onLine) {<br>        const cache = await caches.open(cacheName);<br>        const networkResponsePromise = fetch(request);<br>        context.networkResponsePromise = networkResponsePromise;<br>        event.waitUntil(async function () {<br>            const networkResponse = await networkResponsePromise;<br>            await cache.put(request, networkResponse.clone());<br>        }());<br>    }<br>}</pre><p>And ifNetworkRespond needs to handle the promise as well, so it doesn’t start a new fetch in case there is no cached response available, but instead will use the same fetch that revalidates the cache:</p><pre>const ifNetworkRespond = async (request, context, event) =&gt; {<br>    if (context.onLine) {<br>        let response;<br>        if (context.networkResponsePromise) {<br>            response = await context.networkResponsePromise<br>        } else {<br>            response = context.networkResponse || await fetch(request);<br>        }<br>        if (response) {<br>            context.networkResponse = response;<br>        }<br>        if (response &amp;&amp; response.ok) {<br>            return response;<br>        }<br>    }<br>}</pre><h3>Header filtering</h3><p>Another typical way to use caching with service workers, is not to use route, but header-fields. For example cache everything with Content-Type: text/html. This is possible here as well. You can add an array in the initial context object with cachable content-types and check this before caching:</p><pre>self.addEventListener(&#39;fetch&#39;, async event =&gt; {<br>    event.respondWith(router.handle(event.request, {onLine: navigator.onLine, cachableContent: [&#39;text/html&#39;]}, event))<br>})</pre><p>Then you can use a catch all route to cache for example all HTML as you go:</p><pre>router.get(&#39;/*&#39;, ifCacheRespond, getNetworkResponse, addToCache, ifNetworkRespond, handleError)</pre><p>For more fine granular handling, combining header and route, the filter can instead be set with a handle first in the flow:</p><pre>const cacheHTMLOnly = async (request, context, event) =&gt; {<br>    context.cachableContent = [&#39;text/html&#39;];<br>}</pre><pre>router.get(&#39;/assets/*&#39;, cacheHTMLOnly, ifCacheRespond, getNetworkResponse, addToCache, ifNetworkRespond, handleError)</pre><h3>More advanced</h3><p>This is pretty bareboned, and a full implementation will of course need to add more stuff, like handling cache expiry headers etc. Not least you need to manage cache versioning and deletion, so you don’t end up in a bad state when changes are needed, and you suddenly can’t update resources on the clients.</p><p>Also, libraries like Workbox enables more advanced bookeeping functionality, like limiting number of requests that will be cached, saving post-requests that fail due to network failures, adding its own expiry handling etc. For that you’ll need something like IndexedDB as part of the flow. I won’t go into details here, but will sketch it with the following scenario where you want to be able to store new articles offline if network is down:</p><pre>router.post(&#39;/article/*&#39;, ifNetworkRespond, saveRequestForLater, handleError)</pre><p>If ifNetworkRespond doesn’t return, saveRequestForLater will pick up the request and save it into IndexedDB. Here is a very simplified version. You might need to save more of the request, like headers, params etc. This will be rather dependent on the app and feature in question:</p><pre>const saveRequestForLater = async (request, context, event) =&gt; {<br>    if(!context.onLine){<br>        event.waitUntil(async function () {<br>            const payload = await request.clone().json();<br>            const dbrequest = indexedDB.open(&quot;articles&quot;);<br>            dbrequest.onsuccess = async (event) =&gt; {<br>                const db = event.target.result;<br>                const tx = db.transaction(&#39;createarticle&#39;, &#39;readwrite&#39;);<br>                const store = tx.objectStore(&#39;createarticle&#39;);<br>                store.add(payload)<br>            } <br>        }());       <br>    }<br>}</pre><p>The crucial thing here is, of course, to have some mechanism to act when the app goes online again, and then replays the requests. But that will probably also be based on the requirements of the app and the specific feature.</p><h3>Cache expiration and sidecar requests</h3><p>The cache handling might need to take into account the cache headers of the response, but what if you wan’t to add separate expiry handling into the service worker itself? The challenge is that you can’t modify the response by setting custom headers before putting it into the cache, since it is read-only. One alternative is to use IndexedDB for additional metadata, another one is to create a <em>sidecar requests</em> for caching additional metadata:</p><pre>const addToCache = async (request, context) =&gt; {<br>    const response = context.networkResponse;<br>    if (response &amp;&amp; response.ok) {<br>        let responseClone = response.clone();<br>        caches.open(cacheName).then(async (cache) =&gt; {<br>            cache.put(request, responseClone);<br>            const sidecarReq = new Request(request.url + &#39;-sidecar&#39;, {<br>                method: &quot;GET&quot;,<br>            });<br>            const sidecarResp = new Response(null, {<br>                status: 200,<br>                headers: {<br>                    &#39;x-sw-expires&#39;: Date.now() + context.cacheMaxAgeMS,<br>                },<br>            });<br>            cache.put(sidecarReq, sidecarResp);<br>        });<br>    }<br>}</pre><p>And then check the headers in the sidecar when checking the cache.</p><p><strong><em>NB!</em></strong><em> But make sure that such sidecar-routes won’t be inadvertently cached by other handlers, or used for storing authentication or something sensitive since it obviously can be tampered with.</em></p><h3>Summary</h3><p>So using a router like <em>itty router</em> can certainly help when writing service workers. It lets you work closer to the platform than using a library like Workbox, and can be very flexible and customizable. But still it lets you organize the flows in a way that is close to as readable as more highlevel tools. And still being very lightweight, it adds very little overhead to your bundle compared to what it can help you save of downloaded bytes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=323d347d95d3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/easier-service-worker-caching-with-routing-323d347d95d3">Easier Service Worker caching with Routing</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrating Serverless from Serverless]]></title>
            <link>https://medium.com/geekculture/orchestrating-serverless-from-serverless-bcdb751ddd6c?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcdb751ddd6c</guid>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[xstate]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 13:04:03 GMT</pubDate>
            <atom:updated>2021-09-21T14:32:43.159Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using XState and Durable Objects with Cloudflare Workers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsRYfaU7uh9fHVcJ7NkFEQ.png" /><figcaption>Diagram of the PoC</figcaption></figure><p><em>Serverless is an exciting field these days. There is a lot of competition from both big, medium and small players, and this makes it an interesting option in all kind of apps and architectures. But managing a lot of smaller functions in a coherent flow comes with some challenges. Here I present a PoC I did on how to implement the </em>Orchestration<em> pattern with a serverless function to manage the flow of other serverless functions. I’m using </em><a href="https://xstate.js.org/"><em>XState</em></a><em> to manage the flow and </em><a href="https://developers.cloudflare.com/workers/learning/using-durable-objects"><em>Cloudflare Durable Objects</em></a><em> to persist state between invocations. RabbitMQ is used as message broker.</em></p><p><em>Orchestration</em> is often mentioned together with <em>Choreography</em> as one of the main architectural patterns for managing flow of microservices. Where Choreography is the designed flow of services picking up on other services gestures, Orchestration is the careful guiding of the flow between different services, creating a whole. Both are mentioned with <a href="https://microservices.io/patterns/data/saga.html"><em>Saga pattern</em></a>, as a way to keep transactional integrity between services in a microservice architecture. I won’t go into details here, but assume some familiarity with the topic. If not, there is a lot out there to read. Myself, I like Burning Monk’s rule of thumb for when to choose Choreography or Orchestration (<a href="https://theburningmonk.com/2020/08/choreography-vs-orchestration-in-the-land-of-serverless/">https://theburningmonk.com/2020/08/choreography-vs-orchestration-in-the-land-of-serverless/</a>), and Kislay Verma’s writeup of orchestration and workflow pattern (<a href="https://kislayverma.com/software-architecture/architecture-pattern-orchestration-via-workflows/">https://kislayverma.com/software-architecture/architecture-pattern-orchestration-via-workflows/</a>).</p><p>Orchestration can, of course, also be done using AWS Step functions, Azure Durable functions, or with 3rd party managed services like Camunda or Temporal.io. So there are options to a homegrown variant as I’m describing here, but where is the fun in that? Besides, those options can be very costly, or lock you into the major cloud platforms. And, not least, one clear result of doing this PoC, is that I suspect that using XState in this context, may not always be that much different from using one of the above alternatives (see for example <a href="https://aws.amazon.com/blogs/compute/building-a-serverless-distributed-application-using-a-saga-orchestration-pattern/">https://aws.amazon.com/blogs/compute/building-a-serverless-distributed-application-using-a-saga-orchestration-pattern/</a>).</p><h3>Caveat</h3><p>This is a Proof of Concept so I haven’t bothered with data validation, error handling etc that is needed for a robust implementation. Neither is the responses proper API-responses, but just the raw data.</p><h3>Use case and setup</h3><p>The hypothetical use case is the fruit based pizza shop <em>Tropical Pizzas</em> made famous in an earlier prototype of how to do easy micro-frontends 😉(<a href="https://itnext.io/prototyping-micro-frontends-d03397c5f770">https://itnext.io/prototyping-micro-frontends-d03397c5f770</a>). Those micro-frontends was a huge success, so now the backend also needs to be modernized to keep up the increasing demands of the business. And that, of course, means serverless, message broking and all the hot stuff 😁</p><p>So you can order a pizza with pineapple, bananas, everything juicy and nice, and get it delivered to the safety of your home. The basic PoC architecture is something like the diagram above: An orchestrating service (<em>Order</em>) managing the ‘shopping cart’ and the related services (<em>Kitchen</em>, <em>Delivery</em>) that’s part of the flow of getting a great pizza experience. Also, some basic logging for observability. The client in the PoC is just using Postman or similar, <em>Order log</em>, <em>Kitchen</em> and <em>Delivery</em> are stubs just confirm and move the flow of things. So I will focus on <em>Order</em> and <em>Message Broker</em>.</p><p>The <em>Order</em> orchestrator consists of:</p><ul><li>A <em>serverless function</em> (Cloudflare Worker) that translates a request from the <em>Client</em> or the <em>Message Broker</em> into an event that may trigger a transition in the statemachine.</li><li>A <em>statemachine</em> that acts on the event and may trigger actions and messages based on transitions and state changes.</li><li>And a <em>Durable Object</em> that is used to persist state and workflowdata in between invocations</li></ul><p>You create an pizza order by posting the first pizza to a basic endpoint (I use <a href="https://www.npmjs.com/package/itty-router">itty router</a>):</p><pre>router.post(&#39;/&#39;, auth, async (request, env) =&gt; {<br>    const eventRequest = new Request(&#39;ADD_PIZZA&#39;, {<br>        body: request.body,<br>        method: request.method,<br>    });<br>    const orderId = env.ORDER.newUniqueId();<br>    const order = env.ORDER.get(orderId);<br>    const response = await order.fetch(eventRequest);<br>    return response;<br>});</pre><p>Afterwards pizzas can be added to the order by referencing the created order-id:</p><pre>router.post(&#39;/:id&#39;, auth, checkValidOrderId, async (request, env) =&gt; {<br>    const orderId = env.ORDER.idFromString(request.params.id);<br>    const order = env.ORDER.get(orderId);<br>    const eventRequest = new Request(&#39;ADD_PIZZA&#39;, {<br>        body: request.body,<br>        method: &#39;POST&#39;,<br>    });<br>    const response = await order.fetch(eventRequest);<br>    return response;<br>});</pre><p><strong>env.ORDER</strong> is a binding to a Durable Object namespace that is configured to use an uploaded Javascript Class. From that I get a stub conforming to that class. So the route checks the requests, translates it into an event-request suitable for the statemachine, and forwards that to the Durable Object instance that also holds the statemachine for the order. See <a href="https://developers.cloudflare.com/workers/runtime-apis/durable-objects">https://developers.cloudflare.com/workers/runtime-apis/durable-objects</a>.</p><p>XState has a concept of <em>interpreters</em> that interpret and manages statemachines in form of a service that handles events, transitions, actions, etc. In the PoC, the interpreted statemachine is the <strong>orderService </strong>below, based on a custom interpreter I made that was more suitable in a serverless scenario than the standard one that comes with the library. So when the Durable Object gets the <strong>ADD_PIZZA</strong> event, it goes through something like this:</p><pre>//Process request and get the event type<br>const type = new URL(request.url).pathname.substr(1);</pre><pre>//Get data from event/request<br>const data = await request.json();</pre><pre>//Process the transition and run associated actions based on the event type and -data<br>const newState = await orderService.send({ type, data });</pre><pre>//Update statemachine context with some workflow data<br>const newContext = { ...newState.context, nextEvents: newState.nextEvents, currentState: newState.value };</pre><pre>//Store it in the storage of the Durable Object<br>await storage.put(newContext);</pre><pre>//Create response based on the updated context<br>const strContext = JSON.stringify(newContext)</pre><pre>return new Response(strContext, {<br>    status: 201,<br>    headers: {<br>        &quot;content-type&quot;: &quot;application/json;charset=UTF-8&quot;<br>    }<br>});</pre><p>With statemachines it is useful to distinguish between discret states and continuous state. For example: With a traffic light, red, yellow, green will be the discrete states of the traffic light, while how many times the light switches during a day, could be part of the continuous state of the traffic light. In XState the continuous state is handled as the <em>context</em> of the statemachine, which always will be available for actions etc. So it is this context that is persisted in the Durable Object and holds the data for the pizza-order in question.</p><p>So the magic happens within the <strong>orderService</strong> that receives an event and returns a state with updated context according to the statemachine. The statemachine in the PoC can be visualized with the following statechart that is directly generated from the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJ5OEehSAvlfrNEXoEqlig.png" /><figcaption>Statechart with the service flow visualized from the xstate code.</figcaption></figure><p>The statechart has a state for <strong>orderPizza</strong> with different transitions, like <strong>ADD_PIZZA</strong>:</p><pre>states: {<br>    orderPizza: {<br>        entry: [&#39;updateStatus&#39;],<br>        meta: {<br>            message: &#39;Oh, just ordering some pizza...&#39;,<br>        },<br>        on: {<br>            ADD_PIZZA: {<br>                target: &#39;orderPizza&#39;,<br>                actions: [&#39;addPizzaToItems&#39;, &#39;log&#39;],<br>            },<br>            REMOVE_PIZZA: {<br>                target: &#39;orderPizza&#39;,<br>                actions: [&#39;removePizzaFromItems&#39;, &#39;log&#39;],<br>            },<br>            CONFIRM_PIZZA: {<br>                target: &#39;bakePizza&#39;,<br>                actions: [&#39;log&#39;],<br>            },<br>        },<br>    },</pre><p>Actions can be invoked on entry (<strong>updateStatus</strong>) or as part of the transition (<strong>addPizzaToItems</strong>, <strong>log</strong>). The target of the <strong>ADD_PIZZA</strong> transition is the same state. Even if one doesn’t change state, I find it useful to handle changes as transitions instead of direct CRUD-like manipulations, since it lets me model and encapsulate the changes that belongs together and is relevant for the different states. <strong>addPizzaToItems</strong> will for example only be called when the state is <strong>orderPizza</strong>.</p><p>So the <strong>ADD_PIZZA</strong> event triggers the <strong>addPizzaToItems</strong> action:</p><pre>addPizzaToItems: assign({<br>    items: (context, event) =&gt; context.items.concat(event.data.pizza),<br>}),</pre><p>The assign-method is an XState action-creator that lets you manipulate the context. Here I just add the pizza to the items-array of the order.</p><p>When the customer is statisfied with her selection of pizzas, she will confirm that and trigger a <strong>CONFIRM_PIZZA</strong> event, and that again willl trigger a transition to the <strong>bakePizza</strong> state:</p><pre>bakePizza: {<br>    initial: &#39;sendingOrderToKitchen&#39;,<br>    states: {<br>        sendingOrderToKitchen: {<br>            entry: [&#39;updateStatus&#39;],<br>            meta: {<br>                message: &#39;Sending the order for the pizza...&#39;,<br>            },<br>            invoke: {<br>                id: &#39;sendOrderToKitchen&#39;,<br>                src: &#39;orderPizzaFromKitchen&#39;,<br>                onDone: {<br>                    target: &#39;waitingForPizzaToBeBaked&#39;,<br>                    actions: [&#39;setSendOrderStatus&#39;, &#39;log&#39;]<br>                },<br>                onError: {<br>                    target: &#39;errorInKitchen&#39;,<br>                    actions: [&#39;setErrorStatus&#39;, &#39;log&#39;],<br>                },<br>            }<br>        },<br>        waitingForPizzaToBeBaked: {<br>            entry: [&#39;updateStatus&#39;],<br>            meta: {<br>                message: &#39;Waiting for the pizza to be baked...&#39;,<br>            },<br>        },<br>        errorInKitchen: {<br>            entry: [&#39;updateStatus&#39;],<br>            meta: {<br>                message: &#39;Ooops! Something got burned...&#39;,<br>            },<br>        },<br>    },<br>    on: {<br>        PIZZA_READY: {<br>            target: &#39;deliverPizza&#39;,<br>            actions: [&#39;log&#39;],<br>        },<br>    },<br>},<br></pre><p>This state is more complex with three nested substates:</p><p><em>sendingOrderToKitchen</em>: The default one for sending the order to the kitchen by invoking what XState defines as a <a href="https://xstate.js.org/docs/guides/communication.html#the-invoke-property"><em>invocable service</em></a>. If the invoked <strong>sendOrderToKitchen</strong> is successfull, then the statemachine transitions to</p><p><em>waitingForPizzaToBeBaked</em> : Where it just waits for the <strong>PIZZA_READY</strong> event. But if <strong>sendOrderToKitchen </strong>is not successfull, the statemachine transitions to</p><p><em>errorInKitchen</em>: Which is an error state that can be starting point for error handling — which is not implemented as part of this PoC.</p><h3>Message/event brokering</h3><p><strong>sendOrderToKitchen</strong> and the subsequent <strong>PIZZA_READY</strong> event is tied to the message brokering part of the PoC. Sometimes you will see the distinction between Orchestration and Choreography hinged on that the first depends on synchroneous calls, while the other depends on events/messaging. But more precisely the first will usually be based on a request/respons pattern (<strong>MAKE_PIZZA</strong>, <strong>PIZZA_READY</strong>) that can be implemented either synchroneously, using for example a REST-API ( I realize that a REST call strictly speaking is asynchroneous, but in this setting it would block the flow until it gets a response and act synchroneously), or asynchroneously as here, using message brokering. Benefit of doing this asynchronously is that it opens up for long running workflows and workflows with manual steps. But, of course, this can be mixed if that helps.</p><p>The message brokering in the PoC is based on RabbitMC (CloudAMPQ). As it is, the PoC is dependent on sending messages using the REST-API for RabbitMQ, and in the same way dependent on webhooks for receiving messages from RabbitMQ. In the PoC, the code for the method linked to the <strong>sendOrderToKitchen</strong>-service is defined like this:</p><pre>const orderPizzaFromKitchen = async (context, event) =&gt; {<br>    const mqEvent = createMQEvent(mqTypes.MAKE_PIZZA, context.orderId, context.items, true);<br>    return await postEvent(mqEvent, env)<br>}</pre><p>The <strong>createMQEvent</strong> helper function creates a properly formated message based on data from the statemachine context (I have based that on <a href="https://cloudevents.io/">https://cloudevents.io/</a>). The <strong>MAKE_PIZZA</strong> type ensures it gets to the proper queue after being posted to the exchange-endpoint for my RabbitMQ instance on CloudAMPQ. A webhook for that queue will then delegate it to a suitable service (<em>Kitchen</em> in the PoC-diagram). If this goes OK, then the statemachine transitions to <strong>waitingForPizzaToBeBaked</strong>.</p><p>In the PoC, the <em>Kitchen</em> service is just a very simple serverless that lets me store the event in a Durable Object. It also provides an endpoint that lets me check if I have some orders in process, and then emits a <strong>PIZZA_READY</strong> event for the next order in line. I then have another webhook on my RabbitMQ instance for the <strong>PIZZA_READY</strong> queue that hits the event-endpoint on the <em>Order</em> orchestrator:</p><pre>router.post(&#39;/event&#39;, mqCheck, async (request, env) =&gt; {<br>    const message = await request.json();<br>    const orderid = env.ORDER.idFromString(message.subject);<br>    const order = env.ORDER.get(orderid);<br>    const data = JSON.stringify(message.data);</pre><pre>    const eventRequest = new Request(`${message.type}`, {<br>        body: data,<br>        method: &#39;POST&#39;,<br>    })<br>    const response = await order.fetch(eventRequest);<br>    return response;<br>});</pre><p>This endpoints translates the event from RabbitMQ into something that can be interpreted by the statemachine on the Durable Object. With a <strong>PIZZA_READY</strong> event it will now transition into the <strong>deliverPizza</strong> state that is set up in the same way as <strong>bakePizza, </strong>and<strong> </strong>which will trigger a similar flow. It sends a request for <strong>DELIVER_PIZZA</strong>, and when it later receives <strong>PIZZA_DELIVERED</strong>, it transitions to done and the pizza order is completed.</p><h3>Connecting with the client using a websocket</h3><p>At any time of the workflow, a client can poll the order status from the <em>Order</em> orchestrator. In the PoC it just serializes the current context:</p><pre>if (type === &#39;GET_ORDER&#39;) {<br>    return new Response(JSON.stringify(currentContext), {<br>        status: 201,<br>        headers: {<br>            &quot;Content-Type&quot;: &quot;application/json;charset=UTF-8&quot;,<br>        }<br>    });<br>}</pre><p>But since both Cloudflare Workers and Postman now supports websockets, I thought I try to add and test that as well. This means letting the Durable Object handle a special event that registers a socket on the Object and returns a socket client:</p><pre>if (type.indexOf(&#39;websocket&#39;) !== -1) {</pre><pre>//Request is for websocket<br>    const [client, server] = Object.values(new WebSocketPair())<br>    server.accept()<br>    this.sockets.push(server);<br>    return new Response(null, {<br>        status: 101,<br>        webSocket: client<br>    })<br>}</pre><p>So before returning a regular response, the Durable Object can then broadcast the same data to websocket clients:</p><pre>//Create response based on the updated context<br>const strContext = JSON.stringify(newContext)</pre><pre>//Broadcast state changes on registered sockets<br>this.sockets = this.sockets.filter(socket =&gt; {<br>    try {<br>        socket.send(strContext);<br>        return true;<br>    } catch (err) {<br>        // Whoops, this connection is dead. Remove it from the list.<br>        return false;<br>    }<br>});</pre><pre>return new Response(strContext, {<br>    status: 201,<br>    headers: {<br>        &quot;content-type&quot;: &quot;application/json;charset=UTF-8&quot;<br>    }<br>});</pre><p>This means that when the Message Broker hits the event-endpoint and trigger a transition/state change, this change will immediately be broadcasted to listening clients — which is very cool!</p><h3>Concluding remarks</h3><p>Using XState to orchestrate on serverless has mostly been a positive experience. It is not optimized for that, but still has a lot of relevant features and the setup was pretty straight forward. It has a flexible way to balance config and code, and you can easily get the statechart visualized. I had to make a custom interpreter to make it easier to use await/asynch with the actions and services, so I hope that can be part of future iterations of XState. But that was not a real problem neither, with the more ‘low level’ API of XState available.</p><p>I didn’t demonstrate a Saga pattern here, but using XState to handle a Saga should not be difficult. At least not more difficult than using the alternatives. A statechart can be become very complex fast, but this is by nature and not necessarily due to implementation details.</p><p>Having to be dependent on REST-API and Webhooks for message brokering may exclude some use cases based on performance. It might be possible to set up something using websockets instead, so that could be a future experiment. But having a ‘native’ way to integrate serverless with messaging and queues is/will be a huge selling point for the platforms that can offer that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcdb751ddd6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/orchestrating-serverless-from-serverless-bcdb751ddd6c">Orchestrating Serverless from Serverless</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Suduko Solving Serverless Endpoint Using WebAssembly and OR-Tools]]></title>
            <link>https://medium.com/swlh/a-suduko-solving-serverless-endpoint-using-webassembly-and-or-tools-df9f7bb10044?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/df9f7bb10044</guid>
            <category><![CDATA[google-or-tools]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 07:40:21 GMT</pubDate>
            <atom:updated>2020-09-10T07:43:16.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jp05R-PAUKt6PofnBYqIcw.png" /></figure><p>In this article I will go through the process of</p><ul><li>Building an existing C++ library as WebAssembly</li><li>Creating a WebAssembly application that links to this library</li><li>Deploying the WebAssembly application as part of a serverless endpoint</li></ul><p>The example I use is a Sudoku solver using <a href="https://developers.google.com/optimization">Google OR-Tools</a> for the solving part. There is an online demo of the result here: <a href="https://sudoku-solver.krmuller.workers.dev/">https://sudoku-solver.krmuller.workers.dev/</a>. To be clear: Creating a Sudoku solver is not really the end goal here. Puzzles like Sudoku is kind of a “Hello World” in this context. It exemplify the use of powerful C++-based libraries being leveraged within a serveless setting. The GitHub-repo for the Sudoko solver can be found at <a href="https://github.com/kjartanm/sudoku-solver">https://github.com/kjartanm/sudoku-solver</a>.</p><p>First a bit of background. Using WebAssembly can have different motivations: Speed is obviously one, consistent speed across environments another — since WebAssembly may not always be faster. But access to tools, applications, libraries and functionality that else would be hard to use is another important motivation. Also, WebAssembly has different usecases: on browser, on serverless, or even in gateways. Here I focus on <em>access to otherwise hard to implement functionality </em>in combination with <em>serverless</em>. That is a natural combination. When compiling stuff that was not at all meant for a browser, you risk getting filesizes that is huge — even compared to todays React-based js-bundles. Pushing that as part of your js-app could create unacceptable download times. Enabling that same functionality on serverless could then make sense.</p><h4>Building OR-Tools as WebAssembly</h4><p>I became aware of Google OR-Tools while researching technology for dealing with task management. OR-Tools is an extensive library for handling problems that falls within the discipline that is called “<a href="https://en.wikipedia.org/wiki/Operations_research">Operations Research</a>”:</p><blockquote><strong>Operations research</strong> (<strong>OR</strong>) is a discipline that deals with the application of advanced analytical methods to help make better decisions (…) operations research arrives at optimal or near-optimal solutions to complex decision-making problems. (Wikipedia)</blockquote><p>Typical OR-problems is scheduling, routing, work flows, critical paths etc. Problems with a lot of variables, hard and soft constraints, and potentially a range of possible solutions that needs to be prioritized.</p><p>The problems can be dealt with in a myriad of ways, using different techniques, methods and technologies. OR-Tools supports several of these by a mixture of own components and third party libraries. In addition OR-Tools include wrappers for Java, Python and C#. All in all it is a complex setup with a lot of dependencies.</p><p>I was looking for something I could use on the web. Since I also was looking into WebAssembly at the time, I thought I could see if it was possible to compile OR-Tools into Wasm. Being a novice of WebAssembly, having only rudimentary knowledge of C++, and being borderline clueless about OR, that sounded like a good idea :) Fortunately it turned out well!</p><p>But the start was bumpy. The usual way to compile existing libraries — as I gathered from the examples — would be to use Emscripten and its ‘make’-commands: emmake, emconfigure. The make process for OR-Tools has two steps, building the third-party dependencies first. Using emmake for the dependencies didn’t work well at all, and the main make process for OR-Tools is a very all-or-nothing for creating libraries, binaries, wrappers for Java and Python, examples, tests, etc. This is great for those who want to jump into it, but is hard to adapt for something else — at least for me with limited experience creating make-files.</p><p>The breakthrough was after reading this article about cross compiling (<a href="http://marcelbraghetto.github.io/a-simple-triangle/2019/03/10/part-06/">http://marcelbraghetto.github.io/a-simple-triangle/2019/03/10/part-06/</a>), with a setup for using Emscripten.cmake. OR-Tools has an experimental cmake support, so I could adapt the Emscripten.cmake setup from the article for my own purpose. The first run(s) failed, but even so gave better feedback and showed lot more promise than using emmake directly. So I iterated on that, and in the end, I didn’t really have to change that much. Some small changes within the OR-Tools process, mostly turning things off that I didn’t really need, and some changes with two of the dependencies.</p><p>The OR-Tools cmake-process adapt the dependencies for its own purposes doing a patch after fetching them. So to do the needed changes, I used standalone versions of the dependencies in question, iterated on them until I got a Wasm-build, then created patches with the differences. The patches were added back into the OR-Tools repo for its cmake-process. The resulting build took a lot of time, but it actually worked! I compiled some of the examples using Emscriptens emcc, linking the output of the OR-Tools build, and they behaved as the should.</p><p>The changes I did was of the quick and dirty kind, so for now building OR-Tools as Wasm is just part of this fork (<a href="https://github.com/kjartanm/wasm-or-tools">https://github.com/kjartanm/wasm-or-tools</a>). But with that little changes, it should be totally possible to adapt the OR-Tools cmake process to add Wasm as an option in a proper way. But that is for someone more experienced with cmake than myself at the moment.</p><p><em>Update: The repo have been cleaned up a bit, making it less hacky.</em></p><h4>Creating an WebAssembly application using OR-Tools</h4><p>OR-Tools comes with a lot examples illustrating different methods and techniques. This Sudoku solver is based on a Java example in the contributor section of the examples. But ported to C++ and adapted for integration with JavaScript. The solver uses something called <a href="https://en.wikipedia.org/wiki/Constraint_programming">Constraint Programming</a>, where “ users declaratively state the <a href="https://en.wikipedia.org/wiki/Constraint_(mathematics)">constraints</a> on the feasible solutions for a set of decision variables”. In the Sudoku solver this is done in just a few steps. First the solver sets up the variables:</p><pre>std::vector&lt;std::vector&lt;IntVar *&gt;&gt; grid = {<br>    {}, {}, {}, {}, {}, {}, {}, {}, {}};<br>std::vector&lt;IntVar *&gt; grid_flat;</pre><pre>for (int i = 0; i &lt; n; i++)<br>{<br>    for (int j = 0; j &lt; n; j++)<br>    {<br>        std::ostringstream varname;<br>        varname &lt;&lt; &quot;grid[ &quot; &lt;&lt; i &lt;&lt; &quot;,&quot; &lt;&lt; j &lt;&lt; &quot;]&quot;;<br>        IntVar *nr = solver.MakeIntVar(1, 9, varname.str());<br>        grid[i].push_back(nr);<br>        grid_flat.push_back(nr);<br>    }<br>}</pre><p>This is the well known 81 variables with numbers from 1–9 arranged in a grid (the solver use both a flat and a 2d version of the grid for convenience ).</p><p>Then we add the constraints:</p><pre>for (int i = 0; i &lt; n; i++)<br>{<br>    std::vector&lt;IntVar *&gt; row;<br>    for (int j = 0; j &lt; n; j++)<br>    {<br>        if (sudoku_flat[i * n + j] &gt; 0)<br>        {<br>            solver.AddConstraint(solver.MakeEquality(grid[i][j], sudoku_flat[i * n + j]));<br>        }<br>        row.push_back(grid[i][j]);<br>    }<br>    solver.AddConstraint(solver.MakeAllDifferent(row));<br>}</pre><p>Here we add constraints for the rows. The first AddConstraint says that if we already have a value from the original problem, the variable should be equal to this value. The other says all variables in a row should be different. Constraints for columns and the 3x3 cells is declared in the same way.</p><p>After defining variables and setting the constraints, we initiate a solver and execute a search for solutions:</p><pre>DecisionBuilder *db = solver.MakePhase(<br>    grid_flat,    <br>    solver.INT_VAR_SIMPLE, <br>    solver.INT_VALUE_SIMPLE<br>);<br>solver.NewSearch(db);<br>if (solver.NextSolution())<br>{<br>    for (int i = 0; i &lt; n; i++)<br>    {<br>        for (int j = 0; j &lt; n; j++)<br>        {<br>            sudoku_flat[i * n + j] = (int)grid[i][j]-&gt;Value();<br>        }<br>    }<br>}<br>solver.EndSearch();</pre><p>In this case we write the solution back into the orginal array which is already referenced by the JavaScript integration.</p><p>The application is compiled using the following script:</p><pre>docker run --rm -v $(pwd):/src emscripten/emsdk \<br>   emcc \<br>   -O3 \<br>   --bind \<br>   --no-entry \<br>   -s EXTRA_EXPORTED_RUNTIME_METHODS=&#39;[&quot;getValue&quot;]&#39; \<br>   -s ALLOW_MEMORY_GROWTH=1 \<br>   -s DYNAMIC_EXECUTION=0 \<br>   -s TEXTDECODER=0 \<br>   -s MODULARIZE=1 \<br>   -s ENVIRONMENT=&#39;web&#39; \<br>   -s EXPORT_NAME=&#39;emscripten&#39; \<br>   --pre-js &#39;./pre.js&#39; \<br>   -lm \<br>   -s ERROR_ON_UNDEFINED_SYMBOLS=0 \<br>   -I deps/include \<br>   -L deps/lib \<br>   -lglog \<br>   # Rest of libs removed from the example, ca 90 in total<br>   -o ./build/module.js \<br>   ./src/sudoku.cc</pre><p>I will not go into details here. Most of these settings comes from the Cloudflare Emscripten-template. See here <a href="https://emscripten.org/docs/tools_reference/emcc.html#emccdoc">https://emscripten.org/docs/tools_reference/emcc.html#emccdoc</a> and here <a href="https://github.com/emscripten-core/emscripten/blob/master/src/settings.js">https://github.com/emscripten-core/emscripten/blob/master/src/settings.js</a> for added details. What I have changed/added is emscripten/emsdk as docker image instead of the deprecated trzeci/emscripten that most examples usually references. I also added —-bind since I’m using Emscripten’s <a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html">Embind</a> for integrating WebAssembly with JavaScript. —-no-entry says that the module doesn’t have any main() that can be called, and -I deps/include and -L deps/lib is where to find the dependencies. I haven’t included every or-tool library here, since there is around 90 of them. But the repo has the full script.</p><h3>Integrating with JavaScript on serverless endpoint</h3><p>The setup for the serverless endpoint is as following:</p><ul><li>First it receives the Sudoko problem as a flat array in JSON as a POST request</li><li>It sets up a Wasm-instance with the Sudoku solver</li><li>It loads the problem-array into instance’s memory</li><li>Then it calls instance.solve with the pointer for the array</li><li>Finally it reads back the solution from the instance’s memory into an array that it returns as JSON to the client.</li></ul><p>I wanted to use Cloudflare Workers for this example. They seems to emphasize the possibilities with WebAssmbly, and I wanted to test the experience. That has mostly been positive, even if they need to update their template for emscripten. But it should be very easy to adapt this example to other serverless platforms as well (or add it to a SPA). The main work is done in a single method that is called by the function handling the request:</p><pre>let instance = null;<br>const solve = async sudokuArray =&gt; {<br>    if(!instance) {<br>        instance = await emscripten_module;<br>    }<br>    const I32_SIZE = 4;<br>    const sudokuPtr = instance._malloc(sudokuArray.length * I32_SIZE);<br>    instance.HEAP32.set(sudokuArray, sudokuPtr / I32_SIZE);<br>    instance.solve(sudokuPtr);</pre><pre>    for (let v = 0; v &lt; sudokuArray.length * I32_SIZE; v += I32_SIZE) {<br>        sudokuArray[v/I32_SIZE] = instance.getValue(sudokuPtr + v, &#39;i32&#39;)<br>    } <br>    instance._free(sudokuPtr);  <br>    return new Response(JSON.stringify(sudokuArray), { &#39;status&#39;: 200, &#39;content-type&#39;: &#39;application/json&#39; });<br>}</pre><p>When passing arrays to a Wasm-function you will have to load it into the memory for the Wasm-instance and pass the pointer in the function call. In the same way you can’t return an array, but must pass a pointer. Since the Wasm-solver writes the result back to the same memory space, we can just use the same pointer here.</p><p>Emscripten has a lot of helpful functionality for dealing with stuff like this. The most important thing is to remember that the memory is one single ArrayBuffer, and it is easy to overwrite stuff by accident. For example, instance.HEAP32 and instance.HEAPF64 is just two views of the same array buffer, so it is important to keep track of nr of bytes with the different types when addressing and allocating memory, and keep within the allocated space. See <a href="https://becominghuman.ai/passing-and-returning-webassembly-array-parameters-a0f572c65d97">https://becominghuman.ai/passing-and-returning-webassembly-array-parameters-a0f572c65d97</a> for a more thorough discussion about passing/receiving arrays with Wasm.</p><p>For the integration to work this way, two methods needs to be added to the Emscripten instance: getValue is added by the EXTRA_EXPORTED_RUNTIME_METHODS setting in the build script (see above). solve is added by using Embind to bind the C++ function to its JavaScript counter part:</p><pre>int solve(int sudoko_ptr)<br>{<br>    int *sudoku_flat = (int *)sudoko_ptr;<br>    operations_research::solve(sudoku_flat);<br>    return EXIT_SUCCESS;<br>}</pre><pre>EMSCRIPTEN_BINDINGS(module)<br>{<br>    function(&quot;solve&quot;, &amp;solve);<br>}</pre><p>Since we can’t pass the pointer directly as a pointer in Embind at the moment, I pass it as int and cast it as pointer before processing it further. When the call to Wasm returns, the JavaScript-part can read back the solution array from memory.</p><p>One concern with using OR-Tools on serverless is that processing time can grow real fast with increased complexity of the problems. Cloudflare has a 10 ms CPU time capping on a request on their free plan, and 50 ms on their bundled plan. 50 ms is more than enough to solve tough Sudoko problems, but not for more advanced OR-problems. But they are now testing a new <a href="https://blog.cloudflare.com/introducing-workers-unbound/">Unbound plan</a> in a beta-program that are without this capping, and hopefully the pricing will be acceptable also for complex OR-Tools-applications. On other platforms, this will count against general timeout settings — like 10 seconds on Vercel.</p><h4>Concluding remarks</h4><p>The possibility of leveraging complex functionality in serverless through WebAssembly and libraries like OR-Tools represent a huge opportunity, I think. It is early days yet, but I see promise in this area with companies like Cloudflare, and for example Fastly who are putting Wasm directly on endpoints without the need of being instantiated by JavaScript (<a href="https://www.fastly.com/blog/announcing-lucet-fastly-native-webassembly-compiler-runtime">https://www.fastly.com/blog/announcing-lucet-fastly-native-webassembly-compiler-runtime)</a>. Experiments like this Sudoku solver have been very encouraging so far, and this is absolutely something I look forward to explore further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df9f7bb10044" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-suduko-solving-serverless-endpoint-using-webassembly-and-or-tools-df9f7bb10044">A Suduko Solving Serverless Endpoint Using WebAssembly and OR-Tools</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature flags — an explainer and interactive demo using React and Mavo]]></title>
            <link>https://itnext.io/feature-flags-an-explainer-and-interactive-demo-using-react-and-mavo-5f84eed3d111?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f84eed3d111</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 08:07:37 GMT</pubDate>
            <atom:updated>2020-04-24T06:26:47.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>Feature flags — an explainer and interactive demo using React and Mavo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHoN4VeJjdoQo_041gVpZw.png" /><figcaption>Screenshot from the demo-dashboard</figcaption></figure><p><em>Here I discuss the use of feature flags and some related design patterns. Further I describe a demo implementation, with a prototype app using flags (React) and a feature flag dashboard (Mavo) for administering flags. I also show how error handling/-reporting and analytics can be implemented together with feature flagging, using something I call a </em>Feature Boundary<em>.</em></p><p>Feature flags is <a href="https://martinfowler.com/articles/feature-toggles.html">described by Martin Fowler</a> as a “set of patterns which can help a team to deliver new functionality to users rapidly but safely”. The idea is to hide new features or updated features behind feature flags that can be turned on or off dependent on situational context. A feature flag is integrated into the software, and works by temporarily overriding the primarily designed control flow, using the the flags as switches.</p><p>It is a very useful tool when moving along the continiuous something-axis. It lets you:</p><ol><li>deploy frequently behind flags without disturbing end-users with halfbaked stuff (separating deployments from releases),</li><li>have a firstline defence if some problem turn up after release/deployment (sort of killswitch/circuit breaker, turning off the flag either automatically or manually — but more about that later when I discuss the <em>Feature Boundary</em>),</li><li>experiment with new features (for example by using it for A/B-testing, or by partially releasing a new feature for a select test group that will give useful feedback).</li></ol><p>The flexibility and usefulnes of feature flagging comes from implementing them as part of your software. But that is obviously also the major argument against, since it adds complexity and risk of unstability to your applications and services. So it needs to be handled with a lot of care. You will typically need some sort of abstraction that let you add, maintain and remove flags within your software with ease and predictability. In React that, of course, means creating some suitable components that handles the flags in a declarative way. This is done in the demo, and I will show how.</p><ul><li>Demo of app with feature flags: <a href="https://easy-peasy-features.now.sh/">https://easy-peasy-features.now.sh/</a></li><li>Demo of dashboard for feature flags: <a href="https://easy-peasy-features.now.sh/features">https://easy-peasy-features.now.sh/features</a></li><li>Github repo: <a href="https://github.com/kjartanm/easy-peasy-features">https://github.com/kjartanm/easy-peasy-features</a></li></ul><p>There is also some overlap between feature flags and pipeline-based strategies for partial rollouts etc, but I think this really is a belt and suspenders thing, where software-based and pipeline-based patterns rather should be seen as complementary strategies that enables you to deploy and release with as little risk as possible.</p><h3>What is a flag?</h3><p>The basic feature flag-functionality is something like:</p><p>if check(&#39;flag-x&#39;) then enable someFunctionality</p><p>The check will usually be a check if the flag is enabled, combined with a match of properties on your user object against some preset properties on the flag to see if the user is within the scope of the flag. In the demo a user object looks something like:</p><pre>{<br>    &quot;userid&quot;: &quot;user3&quot;,<br>    &quot;name&quot;: &quot;Cilla Customer, DK&quot;,<br>    &quot;country&quot;: &quot;dk&quot;,<br>    &quot;role&quot;: &quot;customer&quot;<br>}</pre><p>And a flag looks something like this:</p><pre>{<br>    &quot;label&quot;: &quot;Add customer profile-page&quot;,<br>    &quot;flag&quot;: &quot;profile-page-v1&quot;,<br>    &quot;description&quot;: &quot;A customer profile-page to improve metrics by ...&quot;,<br>    &quot;threshold&quot;: 100,<br>    &quot;self-select&quot;: false,<br>    &quot;enabled&quot;: true,<br>    &quot;deprecated&quot;: false,<br>    &quot;expires&quot;: &quot;2020-12-01&quot;,<br>    &quot;selectors&quot;: {<br>        &quot;country&quot;: [<br>            &quot;all&quot;<br>        ],<br>        &quot;role&quot;: [<br>            &quot;customer&quot;<br>        ],<br>        &quot;userid&quot;: [<br>            &quot;all&quot;<br>        ]<br>    }<br>}</pre><p>Here the flag will be <em>on</em> since it is enabled and it is an accepted role. The other selectors are here more like wildcards, but you could narrow the scope of the flag to limit it to a certain country or to a limited set of userids. The granularity of the flag depends on the granularity of your user object. If you have full address, you could limit the feature down to a specific zip code, or if you have the userid of your boss, you could finally give him the shiny boss-button he wants without bothering everyone else! 😉</p><h4>Randomized subsets</h4><p>In addition to property selectors, the flag has a treshold property that can be used for selecting a randomized subset of the original selector-scope, like 20% of the Norwegian customers. In the demo I just use a randomized number that is stored in localStorage, but if the userId can be treated as a number, there is the possibility of using the modulo operator to get the number from there instead (userid % 100). This technique is used by Unleash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csJteRVRZQPRdixe4ugKNw.png" /><figcaption>From the Flag-dashboard demo.</figcaption></figure><h4>Flag storage and editing</h4><p>Where it gets more complicated is the question of how and where you edit and store your flags. The simplest way is to just bundle the flags as JSON into your app and take it from there. On the other end, you have managed services like Launch Darkly, Configcat, Unleash (Unleash also comes in an open source version) and others. The nice thing with the managed services is that they usually come with a dashboard UI that lets you create and manage flags in a user friendly way. But they can be expensive!</p><p>This demo/prototype started as a wish to explore some middle ground, where you can have a nice dashboard, but still have it integrated into your project somehow. Thats why I’m using <a href="https://mavo.io/">Mavo</a>. Mavo is a great tool for creating editable frontends, and it comes with the possibility for using different storage mechanisms. On of these is GitHub, and that means you can use Mavo to create nice UI’s for JSON-files in your repository. In the demo I use Mavo to create a dashboard for the flags. The resulting JSON can then be bundled into the build, or deployed as a simple, standalone API, or even be part of a more advanced API. Since flags can be a potential privacy leak, it may be necessary to move the flag checking into a protected API, instead of serving the whole flag-JSON from an endpoint.</p><p>Here is the markup for editing a feature, creating the ui above, and the JSON-example before that again. With Mavo, you define editable properties using the property-attribute plus some namespaced helper attributes. This is then serialized into JSON when saved (other formats possible). Here is an example of the markup. The wired-prefix comes from <a href="https://wiredjs.com/"><em>wiredjs</em></a>, a set of ui-components to create a sketchy feel and look:</p><pre>&lt;wired-card class=&quot;card--main&quot;&gt;<br>    &lt;div class=&quot;card feature-details&quot;&gt;<br>        &lt;div class=&quot;feature-summary&quot;&gt;<br>            &lt;div&gt;Show/edit [flag]&lt;/div&gt;<br>            &lt;h3&gt;Flag&lt;/h3&gt;<br>            &lt;div property=&quot;flag&quot; class=&quot;card-property-editor&quot;&gt;&lt;/div&gt;<br>            &lt;h3&gt;Label&lt;/h3&gt;<br>            &lt;div property=&quot;label&quot; class=&quot;card-property-editor&quot;&gt;&lt;/div&gt;<br>            &lt;h3&gt;Description&lt;/h3&gt;<br>            &lt;div property=&quot;description&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;feature-editor&quot;&gt;<br>            &lt;div&gt;<br>                &lt;label&gt;Self select:&lt;/label&gt;<br>                &lt;wired-toggle onchange=&quot;this.setAttribute(&#39;aria-checked&#39;, this.checked)&quot; mv-mode=&quot;edit&quot;<br>                    property=&quot;self-select&quot; class=&quot;mv-editor&quot; mv-attribute=&quot;aria-checked&quot;&gt;&lt;/wired-toggle&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>                &lt;label&gt;Deprecated:&lt;/label&gt;<br>                &lt;wired-toggle onchange=&quot;this.setAttribute(&#39;aria-checked&#39;, this.checked)&quot; mv-mode=&quot;edit&quot;<br>                    property=&quot;deprecated&quot; class=&quot;mv-editor&quot; mv-attribute=&quot;aria-checked&quot;&gt;&lt;/wired-toggle&gt;<br>            &lt;/div&gt;<br>            &lt;div&gt;<br>                &lt;label&gt;AB-threshold:&lt;/label&gt;<br>                &lt;wired-slider class=&quot;feature-threshold&quot; onclick=&quot;this.wiredRender(true)&quot;<br>                    onchange=&quot;this.render();this.setAttribute(&#39;aria-valuenow&#39;, this.value)&quot;<br>                    knobradius=&quot;12&quot; mv-attribute=&quot;aria-valuenow&quot; property=&quot;threshold&quot;<br>                    aria-valuenow=&quot;100&quot;&gt;&lt;/wired-slider&gt;<br>            &lt;/div&gt;<br>            &lt;h3&gt;Selectors&lt;/h3&gt;<br>            &lt;ul property=&quot;selectors&quot;&gt;<br>                &lt;li&gt;<br>                    &lt;label class=&quot;card-label&quot;&gt;Countries:&lt;/label&gt;&lt;br&gt;<br>                    &lt;span class=&quot;selector&quot; property=&quot;country&quot; mv-multiple mv-edit=&quot;#countries&quot;&gt;&lt;/span&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;label class=&quot;card-label&quot;&gt;Roles:&lt;/label&gt;&lt;br&gt;<br>                    &lt;span class=&quot;selector&quot; property=&quot;role&quot; mv-multiple mv-edit=&quot;#roles&quot;&gt;&lt;/span&gt;<br>                &lt;/li&gt;<br>                &lt;li&gt;<br>                    &lt;label class=&quot;card-label&quot;&gt;Users:&lt;/label&gt;&lt;br&gt;<br>                    &lt;span class=&quot;selector&quot; property=&quot;userid&quot; mv-multiple&gt;&lt;/span&gt;<br>                &lt;/li&gt;<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/wired-card&gt;</pre><blockquote><strong>NB!</strong> In the demo I use localStorage as storage mechanism, not GitHub, since it lets me create a sort of sandbox where you can test both the dashboard and an demo-app in the privacy of your browser. When you modify a flag in the dashboard, the app updates immediately (if it is open in another tab), since it is listening to localStorage-updates. This is handled by the flag context, so changing this will not affect the rest of the components.</blockquote><h3>Flag Guards, Flag Switches, and Self Selects</h3><p>In the demo/prototype I have implemented three flag-related design patterns:</p><ul><li>Flag Guard</li><li>Flag Switch</li><li>Flag Self-Select</li></ul><p><em>Flag Guards</em> are simple constructs that just hides functionality. In the demo-implementation a Flag Guard can be expressed in React in the following way:</p><pre>&lt;FlagGuard flag=&quot;support-chat-v1&quot;&gt;<br>    &lt;ChatButton /&gt;<br>&lt;/FlagGuard&gt;</pre><p>In this case, the Flag Guard hides the ChatButton if the user is not within the scope of the <strong>support-chat-v1 </strong>flag. The implementation of the guard for the demo is very basic:</p><pre>export const FlagGuard = ({ flag, children }) =&gt; {<br>    const { checkFlag, user, timeStamp } = useContext(FlagContext);<br>    const [hasError, setHasError] = useState(false);<br>    const checkedFlag = useMemo(() =&gt; checkFlag(flag, user, timeStamp), [flag, user, timeStamp, checkFlag]);<br>    if (checkedFlag &amp;&amp; checkedFlag.value &amp;&amp; !hasError) {<br>        return &lt;FeatureBoundary setHasError={setHasError} flag={flag}&gt;{children}&lt;/FeatureBoundary&gt;;<br>    } else {<br>        return &lt;NoAccess flag={flag} status={checkedFlag.status}/&gt;<br>    }<br>}</pre><p>Generic Flag-functionality is made available from a <em>FlagContext</em>. If the user is within the scope, it renders the children inside a <em>FeatureBoundary</em>, if not it just renders some hidden comment.</p><p><em>Flag Switches</em> are if-else-constructs that can be used when replacing existing features, or with A/B-experiments, or in other use cases where you need to show something else if the user is not within the scope of the flag. In the demo-implementation it looks something like this:</p><pre>&lt;FlagSwitch flag=&quot;profile-page-v1&quot;&gt;<br>    &lt;FlagSwitch.On&gt;<br>        &lt;Link to=&quot;/profile&quot;&gt;&lt;UserIcon /&gt;&lt;b&gt;Profile&lt;/b&gt;&lt;/Link&gt;<br>    &lt;/FlagSwitch.On&gt;<br>    &lt;FlagSwitch.Off&gt;<br>        &lt;UserIcon /&gt;<br>    &lt;/FlagSwitch.Off&gt;<br>&lt;/FlagSwitch&gt;</pre><p>In this case, the flags creates a link to the profile page if the user is within the scope of the <strong>profile-page-v1</strong> flag. It can then be complemented with a similar Flag Switch in the React Router setup:</p><pre>&lt;FlagSwitch.On&gt;<br>    &lt;Switch&gt;<br>        &lt;Route path=&quot;/&quot; exact &gt;<br>            &lt;PseudoPage pageTitle=&quot;Landing&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/about&quot; &gt;<br>            &lt;PseudoPage pageTitle=&quot;About&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/shop&quot; &gt;<br>            &lt;PseudoPage pageTitle=&quot;Shopping&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/profile&quot; &gt;<br>            &lt;PseudoPage pageTitle=&quot;Profile&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route&gt;<br>            &lt;PseudoPage pageTitle=&quot;404!!&quot; /&gt;<br>        &lt;/Route&gt;<br>    &lt;/Switch&gt;<br>&lt;/FlagSwitch.On&gt;<br>&lt;FlagSwitch.Off&gt;<br>    &lt;Switch&gt;<br>        &lt;Route path=&quot;/&quot; exact &gt;<br>            &lt;PseudoPage pageTitle=&quot;Landing&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/about&quot; &gt;<br>            &lt;PseudoPage pageTitle=&quot;About&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;/shop&quot; &gt;<br>            &lt;PseudoPage pageTitle=&quot;Shopping&quot; /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route&gt;<br>            &lt;PseudoPage pageTitle=&quot;404!!&quot; /&gt;<br>        &lt;/Route&gt;<br>    &lt;/Switch&gt;<br>&lt;/FlagSwitch.Off&gt;</pre><p>The effect is that if you toggle between a user that is within (initially Cilla Customer) and one outside (initially all the others) the profile scope, you will see that the page on ‘/profile’ toggles between Profile-page and a 404-page.</p><p>The demo-implementation is based on the compound component-pattern, the Context-API-version (<a href="https://kentcdodds.com/blog/compound-components-with-react-hooks">https://kentcdodds.com/blog/compound-components-with-react-hooks</a>). Besides that it is very similar to the FlagGuard-implementation:</p><pre>const FlagSwitchContext = createContext();</pre><pre>const FlagSwitch = ({ flag, children }) =&gt; {<br>    const [hasError, setHasError] = useState(false);<br>    const { checkFlag, user, timeStamp } = useContext(FlagContext);<br>    const checkedFlag = useMemo(() =&gt; checkFlag(flag, user, timeStamp), [flag, user, timeStamp, checkFlag]);<br>    return (&lt;FlagSwitchContext.Provider value={{ flag, status: checkedFlag.status, on: checkedFlag.value, hasError, setHasError }}&gt;{children}&lt;/FlagSwitchContext.Provider&gt;);<br>}</pre><pre>function On({ children }) {<br>    const { on, flag, status, hasError, setHasError } = useContext(FlagSwitchContext);<br>    return (on &amp;&amp; !hasError) ? &lt;FeatureBoundary flag={flag} setHasError={setHasError} switchState=&quot;On&quot;&gt;{children}&lt;/FeatureBoundary&gt; : &lt;NoAccess flag={flag} status={status} switchState=&quot;On&quot; /&gt;;<br>}</pre><pre>function Off({ children }) {<br>    const { on, flag, status, hasError, setHasError } = useContext(FlagSwitchContext)<br>    return (on &amp;&amp; !hasError) ? &lt;NoAccess flag={flag} status={status} switchState=&quot;Off&quot; /&gt; : &lt;FeatureBoundary setHasError={setHasError} flag={flag} switchState=&quot;Off&quot;&gt;{children}&lt;/FeatureBoundary&gt;;<br>}</pre><pre>FlagSwitch.On = On;<br>FlagSwitch.Off = Off;</pre><pre>export { FlagSwitch };</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*lhXt5mgLPYVJqL0RaP51vw.png" /></figure><p><em>Flag Self-select</em> is the usecase where you can self-select to test a new feature. I haven’t seen this in context of feature flags elsewhere. This is usually a pipeline-based, and not flag-based, strategy. But I think it also should be part of the feature flag-toolbox, since it is perfectly possible to use this pattern when experimenting with modules and parts of the application — not only when you are rewriting the whole shebang.</p><p>Self-selection gives a biased sample of users, but sometimes that is actually very useful. The self-selected group will probably be mainly <a href="https://en.wikipedia.org/wiki/Early_adopter">innovators/early adopters</a> — and/or users that is dissatisfied with current feature(s). If this group gives negative feedback, you probably just should kill the feature — at least in its current implementation, and go back to the drawing board.</p><p>It works by displaying the toggle if the user is within the scope of the flag and the flag is marked as self-select:</p><pre>&lt;FlagToggle flag=&quot;shiny-frontend-v1&quot; label=&quot;Try my shiny new look and feel!&quot; /&gt;</pre><p>Implemented like this:</p><pre>export const FlagToggle = ({ flag, label }) =&gt; {<br>    const { checkFlag, userSettings, setUserSettings, user, timeStamp } = useContext(FlagContext);<br>    const checkedFlag = useMemo(() =&gt; checkFlag(flag, user, timeStamp), [flag, user, timeStamp, checkFlag]);<br>    const [isSelected] = useState(userSettings[flag] &amp;&amp; userSettings[flag].isSelected)<br>    const handleChange = useCallback(() =&gt; {<br>        const isSelected = !(userSettings[flag] &amp;&amp; userSettings[flag].isSelected)<br>        const currentFlagSetting = userSettings[flag] ? userSettings[flag] : {};<br>        const newFlagSetting = { ...currentFlagSetting, isSelected };<br>        setUserSettings({ ...userSettings, [flag]: newFlagSetting });<br>    }, [flag, userSettings, setUserSettings])</pre><pre>if (checkedFlag.isSelfSelect) {<br>        return (<br>            &lt;div className=&quot;toggle-container&quot;&gt;<br>                &lt;input className=&quot;toggle-check&quot; id=&quot;toggle&quot; type=&quot;checkbox&quot; onChange={handleChange} checked={isSelected}&gt;&lt;/input&gt;<br>                &lt;label className=&quot;toggle-label&quot; htmlFor=&quot;toggle&quot;&gt;{label}&lt;/label&gt;<br>            &lt;/div&gt;<br>        );<br>    } else {<br>        return (<br>            &lt;NoAccess flag={flag} status={checkedFlag.status}&gt;&lt;/NoAccess&gt;<br>        )<br>    }<br>}</pre><p>Even if the user is within the scope of the flag, the flag check in a Flag Guard or Flag Switch doesn’t return true before the user also self-selects for the flag:</p><pre>ReactDOM.render(<br>    &lt;FlagProvider&gt;<br>        &lt;BrowserRouter&gt;<br>            &lt;FlagSwitch flag=&quot;shiny-frontend-v1&quot;&gt;<br>                &lt;FlagSwitch.On&gt;<br>                    &lt;App version=&quot;shiny&quot;/&gt;<br>                &lt;/FlagSwitch.On&gt;<br>                &lt;FlagSwitch.Off&gt;<br>                    &lt;App version=&quot;tired&quot;/&gt;<br>                &lt;/FlagSwitch.Off&gt;<br>            &lt;/FlagSwitch&gt;<br>        &lt;/BrowserRouter&gt;<br>    &lt;/FlagProvider&gt;, <br>    document.getElementById(&#39;root&#39;));</pre><p>In the demo the effect is to simulate two versions of the app. You can test this by selecting users that is within the shiny-frontend-scope (initially Ada Admin and Cilla Customer). First the toggle shows, then you can self-enable <strong>shiny-frontend-v1</strong> by toggling the self-select. The self-select toggle can also be used for getting feedback from users that turns it off again, but this is not implemented in the demo/prototype.</p><h3>Accumulated scoping</h3><p>In the demo/prototype, the flag-check:</p><ol><li>first checks if the flag is enabled,</li><li>then matches properties against the user object,</li><li>then checks the treshold value against a randomized user property,</li><li>and last it checks if the flag is marked as self-select and if so selected.</li></ol><p>This gives an accumulated effect, enabling scenarios where you can open the feature for those who self-select among a random x% of a certain group within your system. This means you can do both very small and very big experiments, and not least different type of experiments, with as little risk as possible. Adding a <em>Feature Boundary</em> will further mitigate the risk and help with experiments.</p><h3>Feature Boundary: error handling, -reporting and analytics with flags</h3><p>If there is a bug in the new feature, lets say the sort of error that crashes the script execution, how should that be handled? Well, React has something called an <a href="https://reactjs.org/docs/error-boundaries.html">error boundary</a>. An error boundary is a React component (it requires a class component) that implements certain lifecycle method(s). It creates a sort of declarative try/catch that you can use to enclose a React module and stop errors in that module from crashing the execution of the whole application. In the demo I implement it as a <em>Feature Boundary</em> that I use to wrap the children of a validated flag.</p><pre>export class FeatureBoundary extends React.Component {</pre><pre>    constructor(props) {<br>        super(props);<br>        this.state = { hasError: false };<br>    }</pre><pre>    static getDerivedStateFromError(error) {<br>        return { hasError: true };<br>    }</pre><pre>    componentDidCatch(error, errorInfo) {<br>        if (this.props.setHasError) {<br>            this.props.setHasError.call(null, true);<br>        }</pre><pre>        console.log(`This is error reporting for &#39;${this.props.flag}&#39;: ${error}`);<br>    }</pre><pre>    doAnalytics = (msg) =&gt; {<br>        console.log(`This is analytics for &#39;${this.props.flag}&#39;: ${msg}`);<br>    }</pre><pre>    render() {<br>        if (this.state.hasError) {<br>            return (&lt;NoAccess flag={this.props.flag} status=&quot;error-caught-by-boundary&quot; /&gt;);<br>        }<br>        return (&lt;AnalyticsContext.Provider value={{ doAnalytics: this.doAnalytics }}&gt;{this.props.children}&lt;/AnalyticsContext.Provider&gt;);<br>    }<br>}</pre><p>And to repeat, here is how it is used in the FlagGuard. If the flag is on, the children are rendered within the Feature Boundary:</p><pre>export const FlagGuard = ({ flag, children }) =&gt; {<br>    const { checkFlag, user, timeStamp } = useContext(FlagContext);<br>    const [hasError, setHasError] = useState(false);<br>    const checkedFlag = useMemo(() =&gt; checkFlag(flag, user, timeStamp), [flag, user, timeStamp, checkFlag]);<br>    if (checkedFlag &amp;&amp; checkedFlag.value &amp;&amp; !hasError) {<br>        return &lt;FeatureBoundary setHasError={setHasError} flag={flag}&gt;{children}&lt;/FeatureBoundary&gt;;<br>    } else {<br>        return &lt;NoAccess flag={flag} status={checkedFlag.status}/&gt;<br>    }<br>}</pre><p>The Feature Boundary serves three purposes:</p><ol><li>It acts as a sort of <a href="https://martinfowler.com/bliki/CircuitBreaker.html">circuit breaker</a>. If there is a triggering error somewhere in the feature, it just closes it. <em>The impact on the end-user will therefore be the same as if the flag is disabled</em>.</li><li>But you can still report the error to a service, like sentry.io, attaching the flag-id to the report/context. So if the notifications flare up after a deployment, you will immediately see if this is because of the new feature or not — hopefully before any end-user will notice anything at all, sparing your support system 😬. You can then disable feature (after getting enough useful data from the reports) while you fix it. And then redeploy the fix in a roll-forward fashion, carefully enabling the flag again.</li><li>The Feature Boundary can also serve as an anchor point for analytics. In the demo, it sets up an <em>analytics provider</em> with necessary flag information that the sub components in the feature module can use to send relevant data. That should be useful in an A/B-scenario, or with similar experiments:</li></ol><pre>export const ShinyButton = () =&gt; {<br>    const { doAnalytics } = useContext(AnalyticsContext);<br>    const pressMyButton = () =&gt; {<br>        doAnalytics(&quot;add 1 for &#39;press my shiny button&#39;&quot;)<br>    }<br>    return (&lt;button className=&quot;btn--shiny-very&quot; onClick={pressMyButton}&gt;PRESS MY SHINY BUTTON&lt;/button&gt;);<br>}</pre><h3>Other concerns</h3><p>There are some loose ends in the demo/prototype. One issue with feature flags is that they are time-limited. Sure, Fowler mentions something about ‘permission toggle’, using flags (or toggles as he calls them) to implement a a more longliving permission system. And I can very well understand why. Moving the permission system into its own layer in this way, certainly has some benefits. And using React to move permissions into declarative components gives a very nice separation of concerns. But I still think that it should not be the same system as you use for experimenting, partial roll-outs etc. There is a clear overlap in functionality, design patterns, properties, but there is also some significant differences. So while there is some overlap, I will hold permission toggles outside of the scope of feature flagging.</p><p>So flags is not longlived, in my opinion. They expire, and they need to be refactored out of the code. This is why I added ‘expire date’ and ‘deprecated’ as properties on the flag. The idea behind ‘expire date’ is that the flags can be automatically turned off at a certain time, without someone being there to turn it off. There should probably also be a complementary ‘start date’. Together they mean you can use Flag Guards to add time-limited features to your app. Features that can be scheduled independently of release dates/cycles. That is a nice thing in times like these, with corona virus and everything.</p><p>The deprecated-property in a flag could be a way to signal that it is time to remove the flag from code. Combined with environment variable, you could have it throw an error in developement, and report a warning in production. That gives you a way to phase out a flag actively. First you may let it expire, then you deprecate it, then you delete it. With proper logging/reporting, that should give ample time and opportunity for removing the flag from code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f84eed3d111" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/feature-flags-an-explainer-and-interactive-demo-using-react-and-mavo-5f84eed3d111">Feature flags — an explainer and interactive demo using React and Mavo</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixing React modules into a legacy application]]></title>
            <link>https://itnext.io/mixing-react-modules-into-a-legacy-application-ddc0c5660ecd?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc0c5660ecd</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[backbonejs]]></category>
            <category><![CDATA[legacy-code]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Sat, 25 Jan 2020 08:06:52 GMT</pubDate>
            <atom:updated>2020-01-27T07:42:20.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwwXxRHbPtQm2gOBu2-d2w.png" /><figcaption>Screenshot from the Backbone with React-modules PoC</figcaption></figure><p>With a huge monolithic frontend application that is getting on in years, you will come to a point where the cost of maintenance and incremental changes is considerable, radical changes seems impossible, and recruiting for an outdated technology is a major hassle. It is time for a rewrite!</p><p>There are different strategies for starting on that daunting process. But there might be some situations where the better option is a modular rewrite that mixes new into the old. This strategy will never be optimal, since you will be adding significant overhead by using two frameworks. But just let&#39;s say the total tradeoff can still come in favour of this strategy, and move on to the technical practicalities. Here I will describe a Proof of Concept of how it can be done. It mixes React in Backbone, since that was our use case, but the principles should be relevant for other frameworks as well.</p><h3>The PoC</h3><p>The PoC is based on the the Backbone ToDo app (<a href="https://backbonejs.org/docs/todos.html">https://backbonejs.org/docs/todos.html</a>), vamped up with some Material design.</p><p>To this I have added two React modules. One that is an alternative to the Backbone List-view (it is still there, hidden by a checkbox, to show that they are synched), and one that adds features to the editing of the todo. They both uses Material UI (<a href="https://material-ui.com/">https://material-ui.com/</a>) so that the styles can be aligned with the Backbone app. These two modules are compiled and deployed independently of each other, but they still share mui-theme and Redux-store.</p><p>Demo: <a href="https://custom-react-elements.now.sh/">https://custom-react-elements.now.sh/</a></p><p>GitHub: <a href="https://github.com/kjartanm/custom-react-elements">https://github.com/kjartanm/custom-react-elements</a></p><p>Here are some concerns that the PoC addresses:</p><ul><li>It should not add unnecessary complexity to the legacy application.</li><li>It should not add unnecessary overhead to the legacy application.</li><li>It should be possible to share state between different React modules.</li><li>It should be possible to easily communicate state between React modules and legacy application.</li></ul><p>These concerns are addressed through the following steps:</p><h4>Step 1: Deploy and integrate React modules as custom-elements</h4><p>There are different ways to mix React into a legacy framework. The PoC use a technique where the React module is compiled into a custom element. A ‘hello world’ example of this technique would look something like this:</p><pre>const HelloWorldComponent = () =&gt; {<br>    return (<br>        &lt;h1&gt;Hello world!&lt;/h1&gt;<br>    )<br>}</pre><pre>class HelloWorldElement extends HTMLElement {<br>    connectedCallback() {<br>        ReactDOM.render(HelloWorldComponent(), this);<br>    }<br>}<br>customElements.define(&#39;hello-world&#39;, HelloWorldElement);</pre><pre>//Then you can just use the custom element to render and add the React component to the DOM</pre><pre>&lt;div class=&quot;legacyapp-container&quot;&gt;<br>    &lt;hello-world&gt;&lt;/hello-world&gt;<br>&lt;/div&gt;</pre><p>The benefit of this technique is that you can add the React-modules with minimal impact on the codebase of the legacy app. Instead, you do it indirectly through the legacy frameworks template handling. You can then focus on removing code from the legacy app, replacing full logic components with dumb components just for presenting the templates with the custom elements.</p><h4>Step 2: Share resources between React modules</h4><p>You would not like to bundle React and Redux etc. for every component. Fortunately its quite easy to set up those kinds of dependencies as shared, external dependencies while compiling the modules. The PoC loads React &amp; Co from CDN, and the rollup config (but this can probably be done as easy with webpack) tells the script where to find them:</p><pre>//from rollup.config.js<br> <br>const globals = {<br>    react: &#39;React&#39;,<br>    redux: &#39;Redux&#39;,<br>    &#39;react-dom&#39;: &#39;ReactDOM&#39;,<br>    &#39;react-theme&#39;: &#39;reactTheme&#39;,<br>    &#39;react-store&#39;: &#39;reactStore&#39;,<br>}</pre><pre>const externals = [&#39;react&#39;, &#39;redux&#39;, &#39;react-dom&#39;, &#39;react-theme&#39;, &#39;react-store&#39;]</pre><pre>export default [<br>    {<br>        input: &#39;src/Module1Wrapper.js&#39;,<br>        output: {<br>            file: &#39;public/module1.js&#39;,<br>            format: &#39;iife&#39;,<br>            globals,<br>            name: &#39;Module1&#39;<br>        },<br>        externals,<br>        plugins<br>    },<br>    ...<br>]</pre><p>Local dependencies can be handled in the same way. The shared theme is exported as an iife (immediately invoked function expression) that sets the export as a named global that can be used as a shared dependency:</p><pre>//from rollup.config.js</pre><pre>{<br>    input: &#39;src/theme.js&#39;,<br>    output: {<br>        file: &#39;public/theme.js&#39;,<br>        format: &#39;iife&#39;,<br>        globals,<br>        name: &#39;reactTheme&#39;<br>     },<br>     external,<br>     plugins<br> }</pre><p>If a resource should be shared or not, is not always traight forward. In the PoC I could have loaded the Material UI-library through a CDN and treated it the same way as with React, Redux. But the overhead of loading the whole library outweighs the benefit. Instead, if I really needed to optimize, I could create a local bundle of just the needed components, and served those in the same way as the theme.</p><h4>Step 3: Share state between React modules</h4><p>You can share a redux store between modules the same way as the theme:</p><pre>//from rollup.config.js</pre><pre>{<br>    input: &#39;src/store.js&#39;,<br>    output: {<br>        file: &#39;public/store.js&#39;,<br>        format: &#39;iife&#39;,<br>        globals,<br>        name: &#39;reactStore&#39;<br>    },<br>    external,<br>    plugins<br>},</pre><p>The React modules will then both ‘import’ the global store, making it available for the module together with the theme:</p><pre>const App = () =&gt; {<br>    return (<br>        &lt;Provider store={reactStore}&gt;<br>            &lt;ThemeProvider theme={reactTheme}&gt;<br>                &lt;SimpleEdit&gt;&lt;/SimpleEdit&gt;<br>            &lt;/ThemeProvider&gt;<br>        &lt;/Provider&gt;<br>    )<br>}</pre><p>Since the shared resource is a created and ready store, the state will be shared between the modules.</p><h4>Step 4: Communicate state between React modules and legacy app</h4><p>The nice thing with the shared Redux store is that it also can be used to communicate state between legacy app and React modules. Here we need to add something to the legacy app, but with some care that can be done centrally, and not dispersed throughout the app. In the PoC, for example, I have set up a listener on the Todos-collection in the main script for dispatching todos to the modules:</p><pre>Todos.on(&quot;change destroy&quot;, ()=&gt;{<br>    window.reactStore.dispatch({ type: &#39;SET_TODOS&#39;, payload: Todos.toJSON() })<br>})</pre><p>And this goes the other way as well:</p><pre>window.reactStore.subscribe(() =&gt; {<br>    const state = window.reactStore.getState();<br>    const items = (state.items?state.items:[]);<br>    Todos.set(items);<br>    Todos.each(todo=&gt;todo.save())<br>})</pre><p>This last one is rather dumb. You will soon need some abstraction that lets collections and models listen to just a slice of the state, and not the whole state since that could create a lot of noise.</p><p>There is also some danger of endless looping, since model and state are listening to each other, but as long as the incoming state can be checked off as equivalent with existing, it will stop. If not, you will need some bookkeeping to make sure. But all that is out of the PoC scope, and something for another day.</p><h3>Conclusion</h3><p>The PoC works, but there is, of course, a difference between creating a PoC and using this strategy in a full-blown legacy application. There will be hick ups, problems with synhcing, and a significant addition to the overhead — even if it can be contained. If this is time well spent, is an open question, and the only answer is that it depends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc0c5660ecd" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/mixing-react-modules-into-a-legacy-application-ddc0c5660ecd">Mixing React modules into a legacy application</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototyping Micro Frontends]]></title>
            <link>https://itnext.io/prototyping-micro-frontends-d03397c5f770?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03397c5f770</guid>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 17:28:51 GMT</pubDate>
            <atom:updated>2022-01-16T06:50:25.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy Micro-Frontends</h3><blockquote>A prototype with React, Vue, Svelte and Web Components</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZocr5YkGeQR7UK3FHRgqg.png" /></figure><p><em>When first reading about micro-frontends some years ago, I thought it was a fun concept, but not very practical. Even if the idea was nice, the suggested implementations seemed klunky. But maybe there could be ways to make it work? This prototype explores some ideas to do this in a feasible manner:</em></p><ul><li>Prototype app: <a href="https://microfrontends.kjartanm.vercel.app/">https://microfrontends.kjartanm.vercel.app/</a></li><li>Repo: <a href="https://github.com/kjartanm/microfrontends">https://github.com/kjartanm/microfrontends</a></li></ul><h4>Caveats</h4><ul><li>This is a prototype, so no nifty abstractions or optimizations.</li><li>It uses dynamic import of modules, and that doesn’t work in Edge, yet — but is under implementation. It should mostly work elsewhere.</li><li>I haven’t tried to make this mobile friendly, either, since that is not part of the experiment. But there is no reason that this shouldn’t be made to work very well on small screens.</li><li>The app is just a silly excuse for creating different routes and views, so there has been very little effort in creating a good user flow.</li></ul><h3>Background</h3><p>I won’t say much about micro-frontends here, and I will assume some familarity with the concept. <a href="https://martinfowler.com/articles/micro-frontends.html">Micro Frontends</a> at martinfowler.com is a nice intro. For me the main thing about micro-frontends is that they are related to micro-services, and:</p><blockquote>[Microservice] is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies. <a href="https://martinfowler.com/articles/microservices.html">https://martinfowler.com/articles/microservices.html</a></blockquote><p>Micro-frontends is a strategy for doing the same on the frontend. Decoupled modules that are arranged around business capabilities or domains. The pros and cons for micro-frontends overlap those for micro-services. But micro-frontends have an additional hard constraint due to the fact at they are consumer facing, and as such, moving to micro-frontends should not impact UX in a negative way.</p><p>A lot has been said about the idea of mixing different framworks in the frontend, but that is not a goal in it self for using micro-frontends. Using different technologies is a possibility due to the constraints of hard decoupling of modules within a system, modules that communicates through lightweight protocols independent of whatever application technologies that are choosen. The point is that even if the services are made with the same technology, you should not short-cut the constraints of decoupling and communication between modules. But, of course, there are other reasons for not mixing to many technologies.</p><h3>Method</h3><p>The prototype is organized as a set of frontend-modules that are launched and rendered through a home-app that acts as gateway/bootstrap app. Currently the prototype loads modules made with <a href="https://svelte.dev/">Svelte</a>, <a href="https://reactjs.org/">React</a>, <a href="https://vuejs.org/">Vue</a> and a module made with a very small set of web components libraries (<a href="https://github.com/WebReflection/lighterhtml">lighterhtml</a>, <a href="https://github.com/matthewp/haunted">Haunted</a>). The UI is made with the help of <a href="https://wiredjs.com/">wiredjs</a>. The different frameworks are marked with different color backgrounds in the prototype to highlight the different frameworks. There is a color legend in the footer.</p><p>This home-app is very lightweight, based on simple skeleton html, some vanilla js, and a small router library (<a href="https://vaadin.github.io/vaadin-router/vaadin-router/">https://vaadin.github.io/vaadin-router/vaadin-router/</a>). The home-app is also responsible for serving global styles and assets.</p><p>Each frontend-module follows the same pattern, independent of the framework in question:</p><ul><li>The module is bundled as an ES module using Rollup. Here from the Vue-module:</li></ul><pre>export default {<br>    input: &#39;src/index.js&#39;,<br>    output: {<br>        file: &#39;public/order.app.js&#39;,<br>        format: &#39;esm&#39;<br>    },<br>    plugins: [<br>        stopDynamicImport (),<br>        replace({<br>            &quot;process.env.NODE_ENV&quot;: &quot;&#39;production&#39;&quot;<br>        }),<br>        resolve({<br>            alias: {<br>                &#39;vue$&#39;: &#39;vue/dist/vue.esm.js&#39;,<br>                &#39;vuex$&#39;: &#39;vuex/dist/vuex.esm.js&#39;<br>            },<br>            extensions: [&#39;*&#39;, &#39;.js&#39;, &#39;.vue&#39;, &#39;.json&#39;]<br>        }),<br>        vue(),<br>        commonjs(),<br>        terser(),<br>    ]<br>}</pre><ul><li>It exports a common renderer function that acts as a simplified interface to the different frameworks DOM-renderer/bootstrapping functions. For the React-module, it looks like this:</li></ul><pre>export const ReactApp = (el) =&gt; ReactDOM.render(App(), el);</pre><ul><li>For the Svelte-module, it looks like this:</li></ul><pre>export const SvelteApp = (el) =&gt; new App({ target: el });</pre><ul><li>The Vue module:</li></ul><pre>export const VueApp = (el) =&gt; {<br>    const App = new Vue({<br>        template: &#39;&lt;OrderPizza/&gt;&#39;,<br>        components: { OrderPizza },<br>        store<br>    })<br>    App.$mount(el);<br>}</pre><ul><li>The modules are imported into the home app as part of a custom element definition, either by dynamic or static import. Doing it dynamically lets the module be lazy loaded when the custom element is added to the DOM. It is possible to add some intersectionobserver-handling to make the lazy loading even smarter. Here is the React-module loaded dynamially:</li></ul><pre>class PizzaMenu extends HTMLElement {<br>   connectedCallback() {<br>       const root = document.createElement(&#39;section&#39;);<br>       root.classList.add(&#39;react-module&#39;);<br>       this.appendChild(root);<br>       import(&#39;./modules/pizzamenu&#39;)<br>            .then((module) =&gt; {<br>                module.ReactApp(root);<br>            });<br>    }<br>}<br>customElements.define(&#39;x-pizzamenu&#39;, PizzaMenu);</pre><ul><li>The Header-module (part of Svelte-frontend) is loaded statically:</li></ul><pre>import { SvelteHeader } from &#39;./modules/header&#39;;<br>class HeaderModule extends HTMLElement {<br>    connectedCallback() {<br>        const root = document.createElement(&#39;div&#39;);<br>        root.classList.add(&#39;svelte-module&#39;);<br>        this.appendChild(root);<br>        SvelteHeader(root);<br>    }<br>}<br>customElements.define(&#39;x-header&#39;, HeaderModule);</pre><ul><li>The custom element loads and renders the module on screen when it is added to the DOM.</li><li>In the prototype the custom elements loading the modules, except from the header, is added to the DOM by the router. Some of the routes are protected:</li></ul><pre>const mainOutlet = document.querySelector(&#39;main&#39;);<br>const router = new Router(mainOutlet);<br>let hascustomerid = null;<br>const paths = {<br>    &#39;/pizzamenu&#39;: &#39;x-pizzamenu&#39;,<br>    &#39;/orderpizza&#39;: &#39;x-orderpizza&#39;,<br>    &#39;/profile&#39;: &#39;x-profile&#39;,<br>}</pre><pre>const guardPath = (context, commands) =&gt; {<br>    if (hascustomerid !== null) {<br>        return commands.component(paths[context.path]);<br>    }else{<br>        return commands.redirect(&#39;/&#39;)<br>    }<br>};</pre><pre>router.setRoutes([<br>    { path: &#39;/&#39;, component: &#39;x-login&#39; },<br>    { path: &#39;/pizzamenu&#39;, action: guardPath },<br>    { path: &#39;/orderpizza&#39;, action: guardPath },<br>    { path: &#39;/profile&#39;, action: guardPath }<br>]);</pre><pre>onKernelKey(&#39;change:customerid&#39;, customerid =&gt; {<br>    if (customerid != null) {<br>        hascustomerid = customerid;<br>        Router.go(&#39;/pizzamenu&#39;);<br>    }<br>});</pre><ul><li>The modules communicate and share some state using a <em>Kernel</em> (a concept borrowed from Domain Driven Design), which also is a module that can be loaded dynamically.</li></ul><blockquote>“[A shared kernel] Designate some subset of the domain model that the two teams agree to share. Of course this includes, along with this subset of the model, the subset of code or of the database design associated with that part of the model. This explicitly shared stuff has special status, and shouldn’t be changed without consultation with the other team.” (Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software, <a href="https://books.google.no/books?id=hHBf4YxMnWMC&amp;pg=PA354&amp;lpg=PA354&amp;dq=Designate+some+subset+of+the+domain+model+that+the+two+teams+agree+to+share.&amp;source=bl&amp;ots=4AWKMTnD-i&amp;sig=ACfU3U3o1KL_xZovlxLdmjbWukrr9ke3bQ&amp;hl=no&amp;sa=X&amp;ved=2ahUKEwiXmozBmrjlAhVhwIsKHTfQD0wQ6AEwAXoECAkQAQ#v=onepage&amp;q=Designate%20some%20subset%20of%20the%20domain%20model%20that%20the%20two%20teams%20agree%20to%20share.&amp;f=false">p. 354</a>)</blockquote><ul><li>The Kernel is loaded by the different modules, and hooked into the framework specific statemanagement. In the React-module this is done in a useEffect-hook as part of a context provider:</li></ul><pre>useEffect(() =&gt; {<br>    import(&#39;./kernel&#39;)<br>        .then((module) =&gt; {<br>            module.onKernelKey(&#39;change:customerid&#39;, _customerid =&gt; {<br>                setCustomerid(_customerid);<br>            });<br>            const _customerid = module.getSharedKernel(&#39;customerid&#39;);<br>            if (_customerid != null) {<br>                setCustomerid(_customerid);<br>            }<br>            module.onKernelKey(&#39;change:cart&#39;, _cart =&gt; {<br>                    setCart(_cart);<br>            });<br>            const _cart = module.getSharedKernel(&#39;cart&#39;);<br>            if (_cart != null) {<br>                setCart(module.getSharedKernel(&#39;cart&#39;));<br>            }<br>        });<br>}, []);</pre><h3>Micro-frontends and monorepo</h3><p>The whole prototype-application is arranged as a monorepo, with sub-repos for home-app and each frontend-module.The prototype is deployed using Zeit Now, which handles both build pipelines and routes. Here is the config:</p><pre>{<br>    &quot;name&quot;: &quot;Easy Micro-frontends&quot;,<br>    &quot;version&quot;: 2,<br>    &quot;builds&quot;: [<br>        {<br>            &quot;src&quot;: &quot;packages/home/index.html&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static">@now/static</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/home/static/**/*.*&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static">@now/static</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/pizzamenu/package.json&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static-build">@now/static-build</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/kernel/package.json&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static-build">@now/static-build</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/login/package.json&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static-build">@now/static-build</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/order/package.json&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static-build">@now/static-build</a>&quot;<br>        },<br>        {<br>            &quot;src&quot;: &quot;packages/customer/package.json&quot;,<br>            &quot;use&quot;: &quot;<a href="http://twitter.com/now/static-build">@now/static-build</a>&quot;<br>        }<br>    ],<br>    &quot;routes&quot;: [<br>        { &quot;src&quot;: &quot;/modules/pizzamenu&quot;, &quot;dest&quot;: &quot;/packages/pizzamenu/pizzamenu.app.js&quot; },<br>        { &quot;src&quot;: &quot;/modules/kernel&quot;, &quot;dest&quot;: &quot;/packages/kernel/kernel.js&quot; },<br>        { &quot;src&quot;: &quot;/modules/login&quot;, &quot;dest&quot;: &quot;/packages/login/login.app.js&quot; },<br>        { &quot;src&quot;: &quot;/modules/order&quot;, &quot;dest&quot;: &quot;/packages/order/order.app.js&quot; },<br>        { &quot;src&quot;: &quot;/modules/profile&quot;, &quot;dest&quot;: &quot;/packages/customer/profile.app.js&quot; },<br>        { &quot;src&quot;: &quot;/modules/header&quot;, &quot;dest&quot;: &quot;/packages/customer/header.app.js&quot; },<br>        { &quot;src&quot;: &quot;/static/(.*)&quot;, &quot;dest&quot;: &quot;/packages/home/static/$1&quot;, &quot;headers&quot;: { &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;, &quot;cache-control&quot;: &quot;s-maxage=60000&quot;} },<br>        { &quot;src&quot;: &quot;/pizzamenu&quot;, &quot;dest&quot;: &quot;/packages/home/index.html&quot; },<br>        { &quot;src&quot;: &quot;/orderpizza&quot;, &quot;dest&quot;: &quot;/packages/home/index.html&quot; },<br>        { &quot;src&quot;: &quot;/profile&quot;, &quot;dest&quot;: &quot;/packages/home/index.html&quot; },<br>        { &quot;src&quot;: &quot;/&quot;, &quot;dest&quot;: &quot;/packages/home/index.html&quot; }<br>    ]<br>}</pre><h3>Result</h3><p>The resulting prototype is a simple web app, where different routes are rendered using different framework-modules, deployed from individual sub-repos. It shows how the kernel let different modules share a minimal state: Login sets customerid, which other modules use to interact with fake backends. The shoppingcart is also shared, so that changes to it are reflected in the different frontend-modules.</p><p>Of course the modules are very lightweight in a prototype like this, but still, it loads and works better than expected. A webpagetest gives mostly <strong>A</strong> on 4G (<a href="https://www.webpagetest.org/result/191030_4N_d0dc1ecdd62ef03a71233ea777164a8d/">https://www.webpagetest.org/result/191030_4N_d0dc1ecdd62ef03a71233ea777164a8d/</a>), and total JS-load is around 136Kb gzipped, wiredjs included.</p><p>The prototype demonstrates what I think could become a balanced strategy of modularization, implementation and organization. And it shows a possibly acceptable balance between team autonomity and the constraint of not negatively impacting the user experience. That means the prototype assumes some shared concerns between the micro-frontends, which may seem contrary to more pure implementations of micro-frontends. Those shared concerns are:</p><h4>Shared ui-components</h4><p>Wiredjs is really cool, but is also an example of a (mostly) framework agnostic ui-component library, as it is based on web components. Which means that it can be used by the different frameworks independent of each other.</p><p>Micro-frontends needs to be aligned on ux and design. If fragmented, it would create a confusing user experience. At least there should be a styleguide, documenting design, styles, ux-patterns etc. But maintaining different implementations of components, would be costly, and even microscopic differences in component behaviour — undetectable for automated tests — can hurt the experience. Also it adds significantly to the combined js load.</p><p>Using a framework agnostic ui-component library would help, and this is an area where I think custom elements/web components can make sense. Separating the visual layer from framework specific components for business logic makes sense pattern wise, and reduces technological lock in.</p><p>But there is still a need to enforce a common use of design patterns and other macro ux-concerns across micro-frontends. That should be quite enough.</p><h4>Other shared assets</h4><p>The prototype serves some shared assets as part of the home-app. That, I think, also makes sense. Not neccessarily all assets, since it can very well make sense to maintain module specific assets within that micro-frontend repo. But serving the same assets from different sources reduces the benefit of caching, and will at some point end up with fragmentation and QA issues.</p><h4>Monorepo</h4><p>Monorepo really makes sense for micro-frontends, I think. Maintaining different pipelines increases the complexity without giving much back. Also, it would help for setting up e2e tests and other stuff that it would be counter productive to maintain different setups and versions of. Both shared assets, tests and ui-components could be maintained within the monorepo as sub repos, reducing integration overhead.</p><h3>Should we do this?</h3><p>I think this prototype show a reasonable trade-off between UX (user experience), DX (developer experience) and TX (team experience). The shared concerns or dependencies is more or less in the place of what else would be individual dependencies. So it doesn’t hurt TX that much. But not having these trade-offs would hurt UX hard, and probably also DX.</p><p>But there is still a question of bundlesizes. Even if the overhead of having both React and Vue was less than expected in the prototype, I expect that a real life version would have bundles with triple the sizes in the prototype. And if you are adding more than one React and/or Vue-module, you could get the possible burden of duplicate run time code. This is as it should be according to some, since sharing run time code — which is totally possible — will introduce coupling between micro-frontends. I think duplicate run time code is unacceptable, and this may be one reason for using monorepo so to let the deployment pipeline synch dependencies in different packages.</p><p>But when you start doing at lot of these things, the benefit of micro-frontends dwindles. On the other hand, by using more minimal frameworks, this would certainly be less of a problem. So I think the main result of these experiments is that the prototype demonstrates that with micro-frontends, there could possibly be alternatives to using the dominating frameworks, also for enterprise applications.</p><p>Without the overhead of larger runtime evironments, the overhead of loading and executing independent modules based on Svelte, Preact, or similar lightweight libraries/frameworks, would not be that different from doing that within a framework like React or Vue. Maybe even with less total overhead. In that case, the pros could outweigh the cons of using micro-frontends.</p><h4>Domain teams?</h4><p>And since the business capabilities would be the same for both micro-services and micro-frontends, or at least aligned, the combination of micro-frontends and micro-services opens up for domain based/oriented teams that take full responsibility for a business domain, from back to front.</p><blockquote>Expired: Project Teams</blockquote><blockquote>Tired: Product Teams</blockquote><blockquote>Wired: Domain Teams?</blockquote><p>So micro-frontends, in combination with very lightweight frameworks, some glue tooling, monorepos, shared ui-library, and an efficient CI pipeline, could be absolutely something worthwhile exploring further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03397c5f770" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/prototyping-micro-frontends-d03397c5f770">Prototyping Micro Frontends</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MODBooks: Modular and Modifiable Ebooks]]></title>
            <link>https://medium.com/@kjartanmuller/modbooks-modular-and-modifiable-ebooks-379c4d07e2fd?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/379c4d07e2fd</guid>
            <category><![CDATA[book-app]]></category>
            <category><![CDATA[multimodality]]></category>
            <category><![CDATA[ebook]]></category>
            <category><![CDATA[genre]]></category>
            <category><![CDATA[enhanced-ebooks]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Mon, 02 Sep 2019 15:27:00 GMT</pubDate>
            <atom:updated>2020-01-20T08:09:00.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>MODBooks: MultiMODal, MODular and MODifiable Ebooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cj-yMs9GeKWIcCY8qGNu1g.png" /><figcaption>Screenshot from prototype</figcaption></figure><p>This is about a concept I developed as part of my PhD in digital genre- &amp; platform design and development — which I finished a couple of years ago. The idea came a bit too late in the project for me to do anything substantial with it, but it is something I later have wanted to do explore further. So here I will present the concept, called MODBook, and an updated version of the prototype I created for my PhD.</p><ul><li>A prototype of a guidebook as a MODBook is demoed at <a href="https://modbook.muller.no/">https://modbook.muller.no</a></li><li>The editor for that MODBook is demoed at <a href="https://modbook.muller.no/editor">https://modbook.muller.no/editor</a> (it uses Github as login if you want to see it in action)</li></ul><p>The prototype is based on the guide book-genre, since digitial guiding was the main use case in my PhD. It is also partly based on me being an active observer in the <a href="https://kulturognaturreise.wordpress.com/2012/02/21/akerselva-digitalt/">Akerselva Digitalt-project</a>, a museum R&amp;D project for experimenting with digital guides for an historically important industry area in Oslo. It can be used in the browser as a web-book/-app or installed as a PWA (Progressive Web Application).</p><h3>The problem</h3><p>The background for this prototype is how to deal with multimodality in ebooks in a both a reader friendly and production friendly way. The current ebook technology (epub, mobi, and their Kindle and iBooks cousins) works pretty well with text dominated genres, but as soon as you add illustrations that are not purely decorative, tables, notes/references, asides etc. — not to mention sound, video and interactive elements, it starts to break down.</p><h3>Disclaimer</h3><blockquote>Not every ‘bookish’ genre should be digitalized in a ‘bookish‘ way, of course. But a lot of genres still benefit from design patterns associated with books, and the <a href="https://medium.com/@hughmcguire/what-books-can-learn-from-the-web-what-the-web-can-learn-from-books-64670171908f">boundedness that Hugh McGuire calls the essence of books</a>.</blockquote><h3>Reflowable text vs fixed layout</h3><p>Ebooks mostly uses reflowable text. That means the text presentation adapts to the screen/window size of the reader system along with font family, font size, margin settings etc. If any of these changes, the reader system recalculates the layout into a sequence of screens that we perceive as pages. That works great for fiction genres and non-fiction genres that are mostly narrative and text dominated (biographies etc).</p><p>It doesn’t work well at all if the genre uses different text elements (tables, aside boxes, etc) and/or leans heavily on illustrations, maps, and other non-text modalities — and specially when all this needs to be presented together in context. With reflowable ebooks, all these elements are embedded into the text, and will be shuffled around in the reflow. This breaks up the context, and creates a need for navigating back and forth in the text in order to keep everything together.</p><p>Fixed layout is an alternative to reflowable ebooks. Fixed layout means designing the ebook as a sequence of composed pages/spreads that target an ideal reading system with regard to screen size(s), screen ratio etc. These pages/spreads don’t adapt to the reader system besides scaling up/down. Typically that will mean you are creating iPad specific ebooks.</p><p>Creating digital-first fixed layout is costly and complicated, so usually this is done based on a print-first workflow and a PDF-version. So fixed layout is mostly digital textbooks converted from PDF on proprietary platforms/solutions with iPad as target. But even if the result may look good in a superficial way on an iPad, fixed layout doesn’t really work that well either. There are lot of pinching and zooming, and most studies shows that students prefer print editions.</p><p>So web-based non-ebook alternatives starts looking good, but that doesn’t always solve the issues. Moving reflowable text with embedded content from horizontal scroll (bookish navigation) to vertical scroll with embedded content (webbish navigation) does not really solve that much. It is still hard to keep things in context.</p><p>So, instead, MODBooks takes a different approach where the different semiotic types are not embedded in the text, but linked from the text and presented in adjacent views. As you navigate the text, the different views are kept in synch. If you have a figure link present in the page you are reading, the figure-view will be updated with the appropriate link. The spread is not the composition of individual elements, but a compostion of views, or windows, that keep the different semiotic types together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tr8GkUTn-iTEX-ZKsG2KGg.png" /><figcaption>How views/windows can be presented in a guidebook on different devices.</figcaption></figure><h3>How it works</h3><ul><li>You can navigate the text in the text-view/window​ as you would a normal reflowable ebook.</li><li>Other view are updated with relevant content if related link in the texts comes into the text-view.​ If &lt;a rel=”TOC” href=”/loc/10/toc”&gt;&lt;h1&gt;This Popint of Interest&lt;/h1&gt;&lt;/a&gt; comes into view, the TOC-view (Table of Content) highlight that link. These links can be also be of the type &lt;link/&gt; and hidden from the ui (typically section links).</li><li>The first link for a specific relation are actuated automatically, others (if there are more than one illustration linked from a view, for example) will have to be activated by clicking or tapping on the link.</li><li>Navigation and links goes both ways. If you activate link/item or similar in a TOC-view, or Map-view, or Timeline-view or similar, the text in the text-view will navigate to the location of the relevant link.</li><li>Views has full access to document-structure and navigational state, so a TOC-view will know that is between to headings, and highlight the correct one when you for example start navigating backwards.</li></ul><h3>Reader system and widgets</h3><p>The reader system for MODBooks is envisoned as a configurable set of views/windows. These views/windows are implemented as sort of widgets.</p><ul><li>A widget can be used to display a semtiotic element: body text, illustration, map, audio​, etc.</li><li>The widget-windows can be arranged/presented in different ways​, like cascade, stack (+tabbar), popup, slide-in, button+menu etc.</li><li>A widget can also have functional properties, for navigation etc., like a TOC or a progressbar.</li><li>Functional widgets can link to locations, that means a map-widget, or timeline-widget can be used to navigate in the text as well as a traditional TOC.</li></ul><p>The arrangement of the widget windows can be done in a responsive way according to available screensize. So on a desktop screen it will work more like a conventional spread — except that you navigate inside the widgets and not by replacing the whole spread in one. On a mobile, it will behave more like a reflowable text, but where you can switch between modalities without losing context so easily.</p><h3>Format</h3><p>The idea is simple. Structured content with links, but not links meant for embedding/inlining content in the main text flow. As an example:</p><pre>&lt;a rel=&quot;illustration&quot; href=my-illustration.jpg&gt;fig. 1&lt;/a&gt;</pre><p>rather than</p><pre>&lt;img src=my-illustration.jpg/&gt;</pre><p>(See the deprecated spec <a href="https://www.w3.org/TR/xlink11/#link-behaviors">https://www.w3.org/TR/xlink11/#link-behaviors</a> for the inspiration here.)</p><p>That means a content item (mostly text) will link to the other semiotic elements that should be associated with the item. If the item is a recipe in a cookbook, the links could go to ingredients, instructions, illustrations etc.</p><h3>Genre profiles</h3><p>Content items and associated links could be typed. In a cookbook, the item is a recipe, in a guidebook it could be POI (point of interest). Chapter could be used if there is nothing else suitable. The links should be typed with relations. In the prototyped guidebook, a map-links use ‘location’ as relation.</p><p>A combined set of types defines a genre-profile. But remember this is soft typing. It is suggestive, and should not be used for validation or something like that. Genres are fuzzy categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V1EvJ8BO5tz1liGj4jBxg.png" /><figcaption>Example profile</figcaption></figure><h3>Text locations and navigation</h3><p>Text locations are used to identify part of the texts that can be used for navigating. These are generated automatically, based on css-selector syntax and injected into the HTML:</p><pre>META: text-location= p, h1, h2, =&gt; &lt;p data-text-location=”123&quot; …</pre><p>The example says that paragraphs and headings should be used for text-locations and navigation. That also means that is possible to navigate using normal url routing:</p><pre>/loc/45</pre><p>will open the MODBook on the 45th paragraph or heading — if that were the selector. This means implementing navigation, bookmarking etc in different ways is pretty straightforward.</p><h3>Web-book, Web-app, PWA?</h3><p>MODBook is about moving ebooks onto the web platform. Usually ebooks have been either using its own special platform (EPUB/Mobi/Kindle etc) for text dominated genres, or on some sort of customized native app-platform if we are talking about more complex genres in need of fixed layout and what has been called enhanced ebooks. Enhanced ebooks comes either as singular apps or in some sort of proprietary format used with a native player app. Singular apps is typically used for things like childrens picture books, and proprietary formats/player typically used with e-textbooks with fixed layout.</p><p>MODBooks can cover all these bases in a way. Basically it uses web as platform, so — at least in theory — all you need is a browser. But the combination of player-widgets and content, means that it can act as an singular app, web app that is. And since the prototype conform to the PWA-specification, it can even be installed and used in the same way as a native app.</p><p>On the other hand, if you have a certain stable profile and widget setup for a series of content, it is not a problem to use the format/player separation as a strategy.</p><p>Ether way, having PWA as option makes sense for a lot of genres that may function as reference. Or if they for other reasons are accessed over a longer period of time, like textbooks.</p><h3>The prototype</h3><p>Technically, the prototype has been through many, many iterations, both backend and frontend. Currently, the backend and MODBook-editor is based on Mavo, which is my favorite prototyping tool at the moment. In this case, I use Mavo with Github as storage, which gives versioning and collaboration out of the box. Creating a new MODBook is just creating and initiating a new repo. No need for a special CMS.</p><p>In the linked demo it just uses local storage in the HTML, so you don’t have to get access to the repo just to see the prototype editor in action.</p><p>The prototype aesthetics in the editor is a result of WiredJS. The current MODBook-player is based on the Sapper/Svelte-framework, which is a brilliant alternative to React and the likes. The whole shebang is deployed using Zeit Now (since it is just the free tier, there may be some coldstart issues).</p><ul><li>MODBook Player (<a href="https://modbook.muller.no/">https://modbook.muller.no/</a>)</li><li>MODBook Editor (<a href="https://modbook.muller.no/">https://modbook.muller.no/</a>editor)</li><li>MAVO (<a href="https://mavo.io/">https://mavo.io/</a>)</li><li>WiredJS (<a href="https://wiredjs.com/">https://wiredjs.com/</a>)</li><li>Sapper (<a href="https://sapper.svelte.dev/">https://sapper.svelte.dev/</a>)</li><li>Zeit Now (<a href="https://zeit.co/">https://zeit.co</a>)</li></ul><h3>Future work</h3><p>I would love to try out the concept on other genres, but to do that I need to get in touch with people who have some suitable content they would like to experiment with. Unfortunately, I have too little time to both do the tech and content.</p><p>I have a lot of experience with edtech and working in publishing, so textbookish stuff is an area I can do a lot with. But I would like to test it with other genres as well.</p><p>Let me know if you find this interesting and would like to know more about it!</p><h3>Links</h3><p>A couple of academic papers related to this:</p><ul><li><a href="https://www.academia.edu/1325759/Genre_in_the_Design_Space">Genre in the Design Space</a></li><li><a href="https://www.academia.edu/3780645/Innovation_and_the_Genre-Platform_Model">Innovation and the Genre-Platform Model</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379c4d07e2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theming with CSS Custom Properties (variables) and calc()]]></title>
            <link>https://itnext.io/theming-with-css-custom-properties-variables-and-calc-a89b37ad0013?source=rss-25140386f2e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a89b37ad0013</guid>
            <category><![CDATA[theming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[styling]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[custom-properties]]></category>
            <dc:creator><![CDATA[Kjartan Rekdal Müller]]></dc:creator>
            <pubDate>Mon, 13 May 2019 19:14:54 GMT</pubDate>
            <atom:updated>2019-05-14T13:52:47.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Theming of styling has a lot of usecases. Component systems, customization, white labeling, dark mode/light mode, differentiation within an application (routes, topics, sub apps), accessibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRFeomkpe9Om4wQ6Esa-EQ.png" /></figure><p>A good theming system need to handle <em>DRY</em> (don’t repeat yourself), <em>SOC</em> (separation of concerns), <em>loose coupling</em> between parts of system (if I change something here, do I need to change something there?), and what I here will call <em>co-variation</em> (property-value-pairs that need to change together, like button background and button border color). If not these concerns are handled well, that will reflect on an increase in quality issues over time.</p><p>I will not discuss SOC here. A premise for this text is that CSS is the better way for SOC with regard to styling. What I will discuss is DRY, and coupling, but mostly co-variation. The last thing is the juicy part where I show how co-variation can be handled by vanilla CSS using custom properties and calc().</p><h3>Step 1, Naive theming with cascade</h3><p>First, let consider the naive version of theming:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fembed%2Fpreview%2FMxzGvp%3Fheight%3D600%26slug-hash%3DMxzGvp%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fpen%2FMxzGvp%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F3032165.MxzGvp.small.4f397e18-b68a-4031-a664-90e703d84a98.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e70f7f5cede1c0947de2f90bbfe0199/href">https://medium.com/media/4e70f7f5cede1c0947de2f90bbfe0199/href</a></iframe><p>Themes are created using cascade. But this is problematic for two reasons. If you need to update the color, you will have to change it everywhere the theme color is used within the CSS. This is not just a case of ‘find and replace’ when the CSS grows. What if the sameness is a coincidence? (Yes, that happens.) Or if RGB and HSL is used in a mix?</p><p>The other thing is that if a theme is added, you probably need to update the CSS for the individual components as well, and this introduces hard coupling within the system.</p><h3>Step 2, Naive theming with custom properties</h3><p>So to start with, you could use custom properties to ensure that the same value is used where it should be, and that it could be changed from somewhere central:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fembed%2Fpreview%2FMxzGLE%3Fheight%3D600%26slug-hash%3DMxzGLE%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fpen%2FMxzGLE%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F3032165.MxzGLE.small.9a7e7c9f-cf56-4258-90a5-78d996c7234c.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f5a76fb42af6ac6d6e6023f4562adb6/href">https://medium.com/media/8f5a76fb42af6ac6d6e6023f4562adb6/href</a></iframe><p>Here you at least make sure that you safely can update colors and DRY. But you still need to handle the coupling. To do that, you could avoid using properties that are named after their values, and for example use a named color scheme as part of your system. A color scheme could be something like <em>primary</em> and <em>secondary</em> color, or <em>theme</em> color and <em>brand</em> color, or something. That is up to you.</p><h3>Step 3, Not so naive theming with custom properties</h3><p>So instead of referencing a custom property for a specific color, the components reference a named custom property from the color scheme, and this again can be changed from somewhere central without bothering the component. And adding themes will be a breeze:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fembed%2Fpreview%2FLaXrGo%3Fheight%3D600%26slug-hash%3DLaXrGo%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fpen%2FLaXrGo%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F3032165.LaXrGo.small.66e7c376-2a96-4f8a-8f21-3a8d8d3c804c.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/397a2ebf6102c93338f2f2cf49af633f/href">https://medium.com/media/397a2ebf6102c93338f2f2cf49af633f/href</a></iframe><p>Here the component references the propert --themecolor, and the value of that property is kind of set and scoped by the theme-class. The added benefit is readability, since you now communicate the intent or role of the property. You can still use custom properties for named values in addition. And that would probably be good practice, since it reduces the risk of accidentally breaking the theming while adding and changing stuff. You just assign the named value-property to the schemed-property:</p><pre>--themecolor: var(--purple);</pre><h3>Step 4, Co-variation with calc()</h3><p>All well so far, but what about co-variation? The thing is that custom properties can be used together with calc(). A usecase could be a top and side margin that need to be in a certain ratio:</p><pre>--marginSides: 30px;<br>--marginTopBottom: calc(var(--marginSides) * .7)</pre><p>If you change --marginSides, the marginTopBottom will follow. So by using calc(), you can have co-variation in your system without pre-processors like LESS and SASS.</p><p>And this also goes for colors. My favorite LESS color function is darken(), and, well, could we do something like that in plain CSS? Yes, of course, and the secret to that is using HSL instead of RGB. HSL is great because it separate the color into properties that are easier to manipulate than RGB, and each of those colors can be represented by custom properties:</p><pre>--hue: 255;<br>--saturation: 100%;<br>--lumnosity: 87%;<br>--themecolor: hsla(var(--hue), var(--saturation), var(--lumnosity),1);</pre><p>And this could be used for theming and co-variation between color values, like a slighly darker border for some background color:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fembed%2Fpreview%2FqGEeOL%3Fheight%3D600%26slug-hash%3DqGEeOL%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fpen%2FqGEeOL%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F3032165.qGEeOL.small.7801522b-e85d-4f63-827c-bd1a148385ed.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/703b57e7ddd80bd53f96034b0454a403/href">https://medium.com/media/703b57e7ddd80bd53f96034b0454a403/href</a></iframe><p>Darkening of a color can be done by changing saturation and lumnosity using calc(), and in that way co-variation of shades can be handled by the system. You need 50 shades? No problem!</p><p>And, as you can see in this Pen, a nice touch is that you also can use custom properties for shorthand properties, which greatly reduces the risk of accidentally introducing variability within the system:</p><pre>--themeBorder: var(--borderSize) solid var(--darkThemecolor);</pre><pre>border: var(--themeBorder);</pre><p>You can still overwrite specific properties within the components if you need:</p><pre>.cracyButton {<br>    border: var(--themeBorder);<br>    border-left: 15px dotted var(--cracyColor);<br>}</pre><h3>Step 5, Make sure that rules are calculated as they should</h3><blockquote>Custom properties are scoped to the element(s) they are declared on, and participate in the cascade: the value of such a custom property is that from the declaration decided by the cascading algorithm. <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/--*">https://developer.mozilla.org/en-US/docs/Web/CSS/--*</a></blockquote><p>The trick to using custom properties and calc() with theming, is that a CSS rule is not automatically updated if a property is changed, so if a property used in calc() is changed, you have to make sure that the rule is recalculated.</p><p>So something like this won’t work, since changing the property down in the DOM-tree does not automatically affect the .themed-rule higher up:</p><pre>//Does not work</pre><pre>.themed {<br>    --hue: var(--basichue);<br>    --themecolor: hsla(calc(var(--hue), ...);<br>}</pre><pre>.procolTheme {<br>    --hue: var(--aWhiterShadeOfPale);<br>}</pre><pre>.hendrixTheme {<br>    --hue: var(--purpleHaze);<br>}</pre><pre>&lt;main class=&quot;themed&quot;&gt;<br>    &lt;section class=&quot;procolTheme&quot;&gt;...&lt;/section&gt;<br>    &lt;section class=&quot;hendrixTheme&quot;&gt;...&lt;/section&gt;<br>&lt;/main&gt;</pre><p>Changing the order, or having them on the same node, as in the Pen, will help.</p><p>In addition there are possible strategies for forcing a recalculation of the calculating rule. The basic principle is to do something that updates the property within the scope. You could add a rule later in the flow that partly updates the rule. If the usecase is theme per route, you can have a shared CSS with basic theming, and a per route CSS that overwrites the rule with just the needed properties. Or the overwriting CSS can be in the components if routing is handled by the framework, or if you just need to handle different themes within the application for another reason. It is also possible to add the overwriting rule by JavaScript.</p><p>If the usecase is dark-/lightmode and the browsers at that point all supports the media query prefers-color-scheme , you can trigger recalculation within the media query:</p><pre>@media (prefers-color-scheme: dark) {<br>    .themed {<br>        --hue: var(--backInBlack);<br>    }<br>}</pre><p><em>And as a sidenote here: Custom properties and media queries are great for handling responsive design in a theming system, since you can really minimize the needed code within the queries!</em></p><h3>Step 6, Over the top</h3><p>The last one is more experimental than practical, but shows that you can implement a colorwheel-based colorscheme as co-variation. But your designers will probably not thank you for it, since it misses the finetuning that make their day.</p><p>The scheme used in this Pen, is known as <em>complementary split</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*nIJN_gQwAUes6p7h.png" /><figcaption>Complimentary split: <a href="http://www.paletton.com/wiki/index.php?title=Split_complementary_color_scheme">http://www.paletton.com/wiki/index.php?title=Split_complementary_color_scheme</a></figcaption></figure><p>Since hue can be seen as an angle in the color wheel (0–360 degrees), it is easy to derive the other colors in the scheme in the same way that you can manipulate saturation and lumnosity:</p><pre>--primaryHue: var(--hueBasic);<br>--secondaryHue: calc(var(--primaryHue) + 150);<br>--complementaryHue: calc(var(--primaryHue) + 210);</pre><p>And don’t worry if you get values &gt; 360, it just starts another round.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fembed%2Fpreview%2FbyNXEw%3Fheight%3D600%26slug-hash%3DbyNXEw%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fkjartanmuller%2Fpen%2FbyNXEw%3Feditors%3D1100&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F3032165.byNXEw.small.d4ffde6c-5949-4fdc-8a57-10abc3946109.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b892e128fecbfbe99a6335c5c3a5e35f/href">https://medium.com/media/b892e128fecbfbe99a6335c5c3a5e35f/href</a></iframe><h3>Summary</h3><p>So to sum it up. CSS custom properties and calc() can help you dealing with <em>sameness</em>, <em>coupling</em> and <em>co-variation</em> within a theming system.</p><p>Sameness, since custom properties can define values that need to be the same throughout the system. Coupling, since custom properties can be defined by their role, not only as shorthand for their value. Co-variation can be handled by a combination of custom properties and calc() to bind values together, since calc() can use custom properties as parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a89b37ad0013" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/theming-with-css-custom-properties-variables-and-calc-a89b37ad0013">Theming with CSS Custom Properties (variables) and calc()</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>