<?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"><channel><title><![CDATA[Daniel Imfeld's blog - Writing]]></title><description><![CDATA[Daniel Imfeld's Writing and Notes]]></description><link>https://imfeld.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 19:51:45 GMT</lastBuildDate><atom:link href="https://imfeld.dev/rss/writing.xml" rel="self" type="application/rss+xml"/><copyright><![CDATA[Daniel Imfeld 2021]]></copyright><language><![CDATA[English]]></language><managingEditor><![CDATA[Daniel Imfeld]]></managingEditor><category><![CDATA[technology]]></category><category><![CDATA[programming]]></category><item><title><![CDATA[How Svelte 5 Runes will Fix Long-Standing Svelte Bugs]]></title><description><![CDATA[<p>Svelte 5&apos;s rune system has brought a lot of excitement, but also some consternation. While overall it&apos;s a big improvement, certain patterns seem like they&apos;ll be less ergonomic, and Svelte may feel less &quot;magical&quot; than it used to.</p>
    <p>As it&apos;s still in progress, hopefully some of these concerns will be alleviated as runes are refined and best practices are established. But the biggest improvement IMO will be that some long-standing, hard-to-fix bugs in Svelte will be gone.</p>
    <h2>Large Svelte Apps</h2>
        <p>Many people may not experience these bugs, as they only show up with more complex code. So first, a bit about my experience. The Carevoyance SvelteKit app contains over 600 individual Svelte components and a bunch of supporting Javascript code. The app originated in 2014 and was initially written in AngularJS (aka Angular 1). Svelte came onto my radar just after Svelte 3 was released, and after some prototyping, it was clear that the move to Svelte would be a huge improvement. The ability to easily integrate Svelte into the existing Angular app, and to somewhat easily render Angular templates from Svelte, also made the migration much easier.</p>
        <p>Of course, nothing is perfect, and we did hit a few wrinkles that even now aren&apos;t fixed in Svelte 4. But they will be in 5! Let&apos;s take a look.</p>

    <h2>Loss of Reactivity with Multiple Nested Slots</h2>
        <p>There are a few Github issues about this one already, and unfortunately it looks very tricky to fix. In Svelte 3.12, the state tracking system was updated to use a &quot;dirty&quot; bitset, where each number in the bitset corresponded to a particular variable which some reactive code or template reference depends on. This brought a much needed performance increase, but also leads to complexity when using slots.</p>
        <p>When using slots, Svelte passes a portion of its dirty bitset from the parent component into the child, so that the child will know when to rerender the slot. This usually works well, but sometimes when using nested components with multiple layers of slots, something gets lost. Changes aren&apos;t reflected immediately, sometimes being a tick behind or lost completely.</p>
        <p>These REPLs demonstrates the problem in Svelte 3 and 4:</p>
        <p><a href="https://svelte.dev/repl/39bafbb43d2a44af874156720f6e1cad?version=3.50.1">REPL 1</a></p>
        <p><a href="https://svelte.dev/repl/82ea195768214f75b408409b12e26e01?version=4.2.0">REPL 2</a></p>
        <p>(I didn&apos;t write these; they came from the authors of various Github issues).</p>
        <p>Svelte 5&apos;s rune system completely changes how this works. The code generated by the compiler plays much less of a role in dependency tracking now. Instead each rune tracks everything that depends on it and this works across modules. This also means that slots are vastly simplified, with no more need to pass a subset of the dirty bitset between components.</p>
        <p>Below I&apos;ve ported the above REPLs to Svelte 5. Notice that everything works!</p>
        <p><a href="https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAE6WUW2_TMBTHv8oh4qGbRrys3cZCWwQPICSEEONt2UManzRmqW3Z7mWq-t2x4yRLtNKtQsrNzrn4nP_P3gY5K1EH8d024OkCgzj4JGVwFphH6QZ6haVBO9ZiqTI3M9aZYtJME54YcuqeifldMA32SkEKZUDkUBgjdUyI9w8prohCWZLhzSzNZ7PRkF6ko1Gav78eRZdX1xfn-RVGWUo_rlBpJvhkGF6eh5ELD7AuWFbAOtWwVswY5GAEUFwIro1KDbbZ5swUy1mYiUWd-I-uPwjTeomaXN9EwzDhcEpcaLao1vtZbL4qsZSQK7GAJAhJMxN67yToWN8alNGTaTXs2bm7RAPa_tEwgbfa2EUO7nyvtlmB2QPSGPK01Lg7O376_uRDwsfkSQg-LqJKkG8ccGN7AroUBgbcPtZCPTA-P3EeldW4Ka7yGPtyZozTuFrwZFu9dkCcLekat2l-iF6a5ykOBLUsLQRlOUMaxEYtbU0tejbZa9F7ku62SKlY97TzUx1R-s1qLXwHKFtZrR5LnCSBTCm1pcQQ4SIJpl6EcVUm8dbEmk-dyGPSj_NCYVUXD1fns7wQ56cSc4VaH9-oXov2kf3KZrriARzh25rxnaNcKiH1wKHZ2wDfMTfuN0XFVkgH1WRoTx2DqhrAZApv3EdYs34SlsjnpnhOuUf2F6aZsbFALI1mFGPYtpl2zkW2MnvJZK1j68j4Hj-nbW3Ju5pXOu8F57i4XV5e0NhbHVS4C-1MbN7pyiWGS7np3jXD3Wocv4fyV3v3eLoaLnvsNJN7z8d_0PNsr7aR60PEV1SmMyybDcq4XBpwK7btqDCyPUkCfwLVWNVn0N35fQPart7TifnClPaykzqu-b8k0Z4kt5gJTntZPBRNgXtkud_9BR3AKq6iBwAA">REPL 1, Svelte 5 version</a></p>
        <p><a href="https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAE8VU3W7aMBR-laOoUpMWJcBoSxlkarIHmLTeLbswyUnjLdiR7YAmxP1u-wR7xT3CbKeQQClCvZkEiY9zvu_8n7WT0xKlM_m2dhhZoDNxHqrK6TnqV2UEucRSoZYlr0VqbqYyFbRSYcISFVyZZ6IeCypB_whUXCjgORRKVXISBA3ez3AZCKzKYDxEMri_ubsdDwej_O5mPuqPR_37-WCIw1vsDz4tUUjK2WzkD_2-YQdYFTQtYEUkrARVChkoDhkuOJNKEIU7Y09UFfXcT_nixe4P-XIIqJQ1yuB-cDv2EwZXgX4AXVh3Y67fDJl6gFzwBSSOH7R3fsOQOB-PQaIjkOg0JD4CibsQAypRQUYUgRlcSKWDdNfmGqASvHqYwOVlr5WjAznW8lyQornbeB3OJSlr_GxYMxR0iZlrrPiWFa5hJ8QGNA3aWrNpRpdhozeDKWVVrWBOWTaxlLN1y7OBIIS_f55_fymRSIS6ymyVUKCpnER95iugClZc_JT-NDDUHQuRtpA4LWO0SZxXSvGBUnyotAvVOnXdwTRfOvoaUYjQotrC78g6_WGp9mO1ObBezroeh9NOD71hIgKXoVSYgSy5kt5ri1FoCrcX86nUxyb1W5YX3BlpsMV6LHDbHbZSepwZVyCQpEo3CriUwVfbpPABCMtg5LWVC_Y8PhZr_Dq4-L8Gtw3sWBDGM73zFjyjOcXMmShR46a3W5FtZc_dlGb21o2XvWZmYWOm0Byl69lFYf55zbRXnEFaEPaELvGgM_hmMIid6UY_UReY55gq1_VgFm5B1ox3eoJ1ipoGPjJaUfu9O3pnZSQ6LyPvWIv7sRx2kZkg3R_vK2N80uldx3VsvJWR75t_pecaLFIHAAA=">REPL 2, Svelte 5 version</a></p>

    <h2>Hidden Circular Dependencies can Lose Updates</h2>
        <p>This one is due to a combination of how Svelte topologically sorts things, and how the &quot;dirty&quot; bitset is managed.</p>
        <p>As described above, Svelte components set a bit in their dirty bitset when a store or other reactive dependency changes, and this normally would cause any statements that rely on that store to rerun. But at the end of running a component&apos;s reactive statements, Svelte clears out the entire bitset. Normally this prevents infinite loops if a statement both reads and writes the same value, and Svelte&apos;s reordering of reactive statements in causal order makes everything work fine.</p>
        <p>The bug here occurs when a component calls a function in some external code which updates a store, and some other reactive statements in the component also rely on that store.</p>
        <p>Let&apos;s say reactive statement A is the one that calls the external function, and statement B is the one that reads from the store that the external function updates.</p>
        <p>Since this chain of causality isn&apos;t wholly inside a single component, Svelte doesn&apos;t know that it needs to place B after A &#x2014; their order in the component may be related to other dependencies, but the causal link from the store is not considered.</p>
        <p>There&apos;s also a luck factor here, since the relative placement of the two statements in the compiled code can affect if the bug occurs. I&apos;ve seen cases where trivial changes like switching how we wrote an if statement, or merging two reactive statements into one, was enough to cause the bug to occur or go away.</p>
        <p>This is difficult to replicate in a simple REPL, but it happens most often with complex layouts that have a set of components and some shared state between them.</p>
        When you get lucky with the order of the compiled output statements, the process is something like this:
          <ol class="list-numbered">
            <li>Reactive statement &quot;A&quot; runs, and calls the external function, which then updates the store.</li>
            <li>The listener in the Svelte component runs and updates <code>&#x24;store</code>, using the internal invalidate function to set the bit in the dirty bitset.</li>
            <li>Reactive statement &quot;B&quot; that depends on <code>&#x24;store</code> is checked. It runs because the store was updated.</li>
            <li>This cycle of running reactive code ends, so Svelte clears the bitset.</li>
          </ol>
        But if the two reactive statements are swapped, the order of events is something like this:
          <ol class="list-numbered">
            <li>Reactive statement &quot;B&quot; that depends on <code>&#x24;store</code> is checked. It doesn&apos;t run because the store wasn&apos;t updated.</li>
            <li>Reactive statement &quot;A&quot; runs, and calls the external function, which then updates the store.</li>
            <li>The listener in the Svelte component runs and updates <code>&#x24;store</code>, using the internal invalidate function to set the bit in the dirty bitset.</li>
            <li>This cycle of running reactive code ends, so Svelte clears the bitset.</li>
            <li>Statement &quot;B&quot; is not immediately run again, and so the values that it computes become out of sync. </li>
          </ol>
        <p>Keep in mind that you have no control over the order in which A and B run, at least with regard to the store&apos;s value.</p>
        <p>The way to work around this is to wait a <code>tick</code> somewhere in the chain, so that the store&apos;s update doesn&apos;t happen until after the current reactive cycle ends. But this solution is usually only reached after a long period of tricky debugging and walking through both the compiled output and internal Svelte code to see what&apos;s happening.</p>
        <p>The good news again is that Svelte 5 will fix this, and for the same reasons mentioned in the previous section. The compiler is not reordering statements anymore, nor does the compiler try to figure out which statements should run when; it&apos;s all done at runtime instead in a fashion that works fine with cross-module reactivity.</p>

    <h2>The Upshot</h2>
        <p>Svelte 5&apos;s runes system ultimately moves a lot of the state-tracking complexity out of the compiler and into the runtime. Not only does this fix the above bugs, but it will make it much easier to test and verify this code without the need to convince the compiler to generate various edge cases. It should be quite feasible to use more advanced testing methodologies such as model-based testing too, should the need arise.</p>
        <p>I do agree that there are some ergonomic questions remaining with Svelte 5. How will it work to edit complex nested objects? Will we constantly write lots of boilerplate to add accessors to things? Fortunately the Svelte team is listening to the community&apos;s concerns, and I believe that the final release of Svelte 5 will be a good experience for the developer, even if it&apos;s not quite as magical as Svelte 4. But being able to write bug-free code is paramount.</p>
        <p>Three years ago, <a href="https://www.twitter.com/swyx">@swyx</a> wrote, <a href="https://www.swyx.io/svelte-sites-react-apps">Svelte for Sites, React for Apps</a>. I don&apos;t know if he still stands by those words as Svelte and its ecosystem have come a long way since then (and Shawn has been a big part of that!), but I do think that Svelte 5 will allow us to be more confident in saying &quot;Svelte for Sites, and Svelte for Apps!&quot;</p>]]></description><link>https://imfeld.dev/writing/how_svelte_5_runes_will_fix_long_standing_svelte_bugs</link><guid isPermaLink="false">e7eacb7180aa575ec50d21b4bbbd776aeebe7ac0e698e56383171e182b685087</guid><category><![CDATA[Svelte]]></category><pubDate>Sat, 30 Sep 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Plausible.io Custom URLs with SvelteKit]]></title><description><![CDATA[<p><a href="https://plausible.io">Plausible Analytics</a> has a feature which lets you use custom URLs to help avoid adblockers and get better counts. Plausible is committed to respecting privacy, so I feel this is OK to do. (And they <a href="https://plausible.io/docs/proxy/introduction">address the topic here</a>).</p>
    <p>This site is built with SvelteKit and hosted on Vercel, and so none of the normal methods documented by Plausible work with this particular combination. But it&apos;s pretty simple to get going. Everything you see here except for the Vercel-specific edge function configuration will apply to other hosts too.</p>
    <p>We need two routes: one for the script itself, and another route to proxy events. I chose to place both of these routes under the <code>/plas</code> path.</p>
    <p>First, the route for fetching the script itself.</p>
    <pre><code><span class="sy-source sy-js"><span class="sy-comment sy-line sy-double-slash sy-js"><span class="sy-punctuation sy-definition sy-comment sy-js">//</span> src/routes/plas/script.js/+server.ts
</span>
<span class="sy-meta sy-export sy-js"><span class="sy-keyword sy-control sy-import-export sy-js">export</span> <span class="sy-storage sy-type sy-js">const</span> <span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-other sy-readwrite sy-js">config</span></span> <span class="sy-keyword sy-operator sy-assignment sy-js">=</span> <span class="sy-meta sy-mapping sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span>
  <span class="sy-comment sy-line sy-double-slash sy-js"><span class="sy-punctuation sy-definition sy-comment sy-js">//</span> Vercel-specific
</span>  <span class="sy-meta sy-mapping sy-key sy-js">runtime</span><span class="sy-punctuation sy-separator sy-key-value sy-js">:</span> <span class="sy-meta sy-string sy-js"><span class="sy-string sy-quoted sy-single sy-js"><span class="sy-punctuation sy-definition sy-string sy-begin sy-js">&apos;</span>edge<span class="sy-punctuation sy-definition sy-string sy-end sy-js">&apos;</span></span></span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span><span class="sy-punctuation sy-terminator sy-statement sy-js">;</span></span>

<span class="sy-meta sy-export sy-js"><span class="sy-keyword sy-control sy-import-export sy-js">export</span><span class="sy-meta sy-function sy-js"></span><span class="sy-meta sy-function sy-declaration sy-js"> <span class="sy-storage sy-type sy-function sy-js">function</span> <span class="sy-entity sy-name sy-function sy-js">GET</span><span class="sy-punctuation sy-section sy-group sy-begin sy-js">(</span><span class="sy-meta sy-binding sy-destructuring sy-mapping sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span> <span class="sy-meta sy-mapping sy-key sy-js"><span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-parameter sy-function sy-js">fetch</span></span> </span><span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-js">)</span></span><span class="sy-meta sy-function sy-js"> <span class="sy-meta sy-block sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span>
  <span class="sy-keyword sy-control sy-flow sy-return sy-js">return</span> <span class="sy-meta sy-function-call sy-js"><span class="sy-variable sy-function sy-js">fetch</span><span class="sy-meta sy-group sy-js"><span class="sy-punctuation sy-section sy-group sy-begin sy-js">(</span><span class="sy-meta sy-string sy-js"><span class="sy-string sy-quoted sy-single sy-js"><span class="sy-punctuation sy-definition sy-string sy-begin sy-js">&apos;</span>https://plausible.io/js/script.js<span class="sy-punctuation sy-definition sy-string sy-end sy-js">&apos;</span></span></span><span class="sy-punctuation sy-section sy-group sy-end sy-js">)</span></span></span><span class="sy-punctuation sy-terminator sy-statement sy-js">;</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span></span></span>
</span></code></pre>
    <p>This has a bit of configuration to run this route as an edge function, and then it just performs its own request for the actual Plausible script.</p>
    <p>Next, you need a route for the Plausible script to send events to. This is similar to the previous route, but it also passes the relevant headers and body from the client through to Plausible.</p>
    <pre><code><span class="sy-source sy-js"><span class="sy-comment sy-line sy-double-slash sy-js"><span class="sy-punctuation sy-definition sy-comment sy-js">//</span> src/routes/plas/event/+server.ts
</span>
<span class="sy-meta sy-export sy-js"><span class="sy-keyword sy-control sy-import-export sy-js">export</span> <span class="sy-storage sy-type sy-js">const</span> <span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-other sy-readwrite sy-js">config</span></span> <span class="sy-keyword sy-operator sy-assignment sy-js">=</span> <span class="sy-meta sy-mapping sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span>
  <span class="sy-comment sy-line sy-double-slash sy-js"><span class="sy-punctuation sy-definition sy-comment sy-js">//</span> Vercel-specific
</span>  <span class="sy-meta sy-mapping sy-key sy-js">runtime</span><span class="sy-punctuation sy-separator sy-key-value sy-js">:</span> <span class="sy-meta sy-string sy-js"><span class="sy-string sy-quoted sy-single sy-js"><span class="sy-punctuation sy-definition sy-string sy-begin sy-js">&apos;</span>edge<span class="sy-punctuation sy-definition sy-string sy-end sy-js">&apos;</span></span></span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span><span class="sy-punctuation sy-terminator sy-statement sy-js">;</span></span>

<span class="sy-meta sy-export sy-js"><span class="sy-keyword sy-control sy-import-export sy-js">export</span><span class="sy-meta sy-function sy-js"></span><span class="sy-meta sy-function sy-declaration sy-js"> <span class="sy-storage sy-type sy-js">async</span> <span class="sy-storage sy-type sy-function sy-js">function</span> <span class="sy-entity sy-name sy-function sy-js">POST</span><span class="sy-punctuation sy-section sy-group sy-begin sy-js">(</span><span class="sy-meta sy-binding sy-destructuring sy-mapping sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span> <span class="sy-meta sy-mapping sy-key sy-js"><span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-parameter sy-function sy-js">request</span></span></span><span class="sy-punctuation sy-separator sy-parameter sy-function sy-js">,</span> <span class="sy-meta sy-mapping sy-key sy-js"><span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-parameter sy-function sy-js">fetch</span></span> </span><span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-js">)</span></span><span class="sy-meta sy-function sy-js"> <span class="sy-meta sy-block sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span>
  <span class="sy-storage sy-type sy-js">let</span> <span class="sy-meta sy-binding sy-name sy-js"><span class="sy-variable sy-other sy-readwrite sy-js">response</span></span> <span class="sy-keyword sy-operator sy-assignment sy-js">=</span> <span class="sy-meta sy-function-call sy-js"><span class="sy-variable sy-function sy-js">fetch</span><span class="sy-meta sy-group sy-js"><span class="sy-punctuation sy-section sy-group sy-begin sy-js">(</span><span class="sy-meta sy-string sy-js"><span class="sy-string sy-quoted sy-single sy-js"><span class="sy-punctuation sy-definition sy-string sy-begin sy-js">&apos;</span>https://plausible.io/api/event<span class="sy-punctuation sy-definition sy-string sy-end sy-js">&apos;</span></span></span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span> <span class="sy-meta sy-mapping sy-js"><span class="sy-punctuation sy-section sy-block sy-begin sy-js">{</span>
    <span class="sy-meta sy-mapping sy-key sy-js">method</span><span class="sy-punctuation sy-separator sy-key-value sy-js">:</span> <span class="sy-variable sy-other sy-readwrite sy-js">request</span><span class="sy-punctuation sy-accessor sy-js">.</span><span class="sy-meta sy-property sy-object sy-js">method</span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span>
    <span class="sy-meta sy-mapping sy-key sy-js">headers</span><span class="sy-punctuation sy-separator sy-key-value sy-js">:</span> <span class="sy-variable sy-other sy-readwrite sy-js">request</span><span class="sy-punctuation sy-accessor sy-js">.</span><span class="sy-meta sy-property sy-object sy-js">headers</span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span>
    <span class="sy-meta sy-mapping sy-key sy-js">body</span><span class="sy-punctuation sy-separator sy-key-value sy-js">:</span> <span class="sy-variable sy-other sy-readwrite sy-js">request</span><span class="sy-punctuation sy-accessor sy-js">.</span><span class="sy-meta sy-property sy-object sy-js">body</span><span class="sy-punctuation sy-separator sy-comma sy-js">,</span>
  <span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-js">)</span></span></span><span class="sy-punctuation sy-terminator sy-statement sy-js">;</span>

  <span class="sy-keyword sy-control sy-flow sy-return sy-js">return</span> <span class="sy-variable sy-other sy-readwrite sy-js">response</span><span class="sy-punctuation sy-terminator sy-statement sy-js">;</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-js">}</span></span></span></span>

</span></code></pre>
    <p>Finally, in <code>app.html</code> we just include the script, with the appropriate paths for the script and event routes.</p>
    <pre><code><span class="sy-text sy-html sy-basic"><span class="sy-meta sy-tag sy-sgml sy-doctype sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;!</span><span class="sy-keyword sy-declaration sy-doctype sy-html">DOCTYPE</span> <span class="sy-constant sy-language sy-doctype sy-html">html</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
<span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">html</span> <span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">lang</span><span class="sy-punctuation sy-separator sy-key-value sy-html">=</span><span class="sy-string sy-quoted sy-double sy-html"><span class="sy-punctuation sy-definition sy-string sy-begin sy-html">&quot;</span>en<span class="sy-punctuation sy-definition sy-string sy-end sy-html">&quot;</span></span></span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
  <span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">head</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
    <span class="sy-comment sy-block sy-html"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-html">&lt;!--</span> Other head contents <span class="sy-punctuation sy-definition sy-comment sy-end sy-html">--&gt;</span></span>
    <span class="sy-meta sy-tag sy-script sy-begin sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;</span><span class="sy-entity sy-name sy-tag sy-script sy-html">script</span></span><span class="sy-meta sy-tag sy-script sy-begin sy-html">
      <span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">async</span>
      </span><span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">defer</span>
      </span><span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">data-domain</span><span class="sy-punctuation sy-separator sy-key-value sy-html">=</span><span class="sy-string sy-quoted sy-double sy-html"><span class="sy-punctuation sy-definition sy-string sy-begin sy-html">&quot;</span>your-domain.com<span class="sy-punctuation sy-definition sy-string sy-end sy-html">&quot;</span></span></span>
      <span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">data-api</span><span class="sy-punctuation sy-separator sy-key-value sy-html">=</span><span class="sy-string sy-quoted sy-double sy-html"><span class="sy-punctuation sy-definition sy-string sy-begin sy-html">&quot;</span>/plas/event<span class="sy-punctuation sy-definition sy-string sy-end sy-html">&quot;</span></span></span>
      <span class="sy-meta sy-attribute-with-value sy-html"><span class="sy-entity sy-other sy-attribute-name sy-html">src</span><span class="sy-punctuation sy-separator sy-key-value sy-html">=</span><span class="sy-string sy-quoted sy-double sy-html"><span class="sy-punctuation sy-definition sy-string sy-begin sy-html">&quot;</span>/plas/script.js<span class="sy-punctuation sy-definition sy-string sy-end sy-html">&quot;</span></span></span>
    <span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span><span class="sy-meta sy-tag sy-script sy-end sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;/</span><span class="sy-entity sy-name sy-tag sy-script sy-html">script</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
  <span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;/</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">head</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
  <span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">body</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span><span class="sy-comment sy-block sy-html"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-html">&lt;!--</span> body contents <span class="sy-punctuation sy-definition sy-comment sy-end sy-html">--&gt;</span></span><span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;/</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">body</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>
<span class="sy-meta sy-tag sy-structure sy-any sy-html"><span class="sy-punctuation sy-definition sy-tag sy-begin sy-html">&lt;/</span><span class="sy-entity sy-name sy-tag sy-structure sy-any sy-html">html</span><span class="sy-punctuation sy-definition sy-tag sy-end sy-html">&gt;</span></span>

</span></code></pre>
    <p>And that&apos;s it!</p>]]></description><link>https://imfeld.dev/writing/plausibleio_custom_urls_with_sveltekit</link><guid isPermaLink="false">3577932a7db2175a2b5ac7f0d5f24967ef4f6f96fd58e5caa61ead07dfcac40f</guid><pubDate>Thu, 21 Sep 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Creating a Custom Command Bar in Neovim]]></title><description><![CDATA[<p>Command bars are a useful addition to many applications that let you search for and execute commands. Neovim&apos;s <a href="https://github.com/nvim-telescope/telescope.nvim">Telescope</a> plugin provides the pieces to create your own with just a bit of Lua programming.</p>
    <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/vim-command-bar_1681452546770_0-w650-AYd-YcGLof67sIfdRG4sZw.avif" type="image/avif" width="650" height="389">
  <source srcset="https://images.imfeld.dev/blog/vim-command-bar_1681452546770_0-w650-AYd-YcGLof67sIfdRG4sZw.webp" type="image/webp" width="650" height="389">
  <source srcset="https://images.imfeld.dev/blog/vim-command-bar_1681452546770_0-w650-AYd-YcGLof67sIfdRG4sZw.png" type="image/png" width="650" height="389">
  <img src="https://images.imfeld.dev/blog/vim-command-bar_1681452546770_0-w650-AYd-YcGLof67sIfdRG4sZw.png" alt="vim-command-bar.png" width="650" height="389">
</picture>
</p>
    <p>Telescope can be <a href="https://github.com/nvim-telescope/telescope.nvim#installation">installed using any Neovim plugin manager</a>, and then you&apos;re ready to dive in. Even if you haven&apos;t used Lua before, this is fairly straightforward.</p>
    <p>First, we&apos;ll start by importing some modules.</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">telescope</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
<span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">pickers</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.pickers<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
<span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">finders</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.finders<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
</span></code></pre>
    <p>The main modules to be aware of here are <code>pickers</code> and <code>finders</code>. A picker is the actual Telescope window that pops up, and the finder provides the items to show in the picker.</p>
    <h2>Defining the Commands</h2>
    <p>Next, we&apos;ll define our commands. This may look a bit weird if you&apos;re not used to Lua, but objects and arrays are sort of the same thing here, so they both use braces. Lua calls them both &quot;tables.&quot;</p>
    <p>The actual structure of the commands can look however you want, since you&apos;ll convert them to the format that Telescope uses later. Here I have a name, a category, and a function to run when the command is selected, but you can add additional information or functions if you want.</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">commands</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
  <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">name</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>Organize imports<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">category</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>LS<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">action</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span> 
      <span class="sy-variable sy-other sy-lua">vim</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">fn</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">CocActionAsync</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>runCommand<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>editor.action.organizeImport<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
    <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span>
  </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
  <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">name</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>Format document<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">category</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>LS<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">action</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
      <span class="sy-variable sy-other sy-lua">vim</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">fn</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">CocActionAsync</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>runCommand<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>editor.action.formatDocument<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
    <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span>
  </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
  <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">name</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>Git Difftool<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">category</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>Git<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span> 
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">action</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span> <span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span> <span class="sy-variable sy-other sy-lua">vim</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">cmd</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>Git difftool<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span> <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span>
  </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span>
</span></code></pre>
    <p>Note that just using <code>CocAction</code> will cause the command to be run to completion before the picker closes. This can cause issues with certain commands and so <code>CocActionAsync</code> works much better.</p>
    <h2>Formatting</h2>
    <p>The picker in the screenshot above has two columns: the command&apos;s name and category. We can use the <code>entry_display</code> module to help with this formatting. It does not autosize columns though, so  first we need to find our column widths.</p>
    <p>This code snippet figures out the longest command name. (The <code>#</code> operator returns the length of a string.)</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">longest_command_name</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-lua">0</span>
<span class="sy-keyword sy-control sy-loop sy-lua">for</span> <span class="sy-variable sy-other sy-lua">_</span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-variable sy-other sy-lua">command</span> <span class="sy-keyword sy-control sy-loop sy-lua">in</span> <span class="sy-support sy-function sy-builtin sy-lua">ipairs</span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-other sy-lua">commands</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span> <span class="sy-meta sy-block sy-lua"><span class="sy-keyword sy-control sy-lua">do</span>
  <span class="sy-keyword sy-control sy-conditional sy-lua">if</span> <span class="sy-keyword sy-operator sy-length sy-lua">#</span><span class="sy-variable sy-other sy-lua">command</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">name</span> <span class="sy-keyword sy-operator sy-comparison sy-lua">&gt;</span> <span class="sy-variable sy-other sy-lua">longest_command_name</span> <span class="sy-meta sy-block sy-lua"><span class="sy-keyword sy-control sy-conditional sy-lua">then</span>
    <span class="sy-variable sy-other sy-lua">longest_command_name</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-keyword sy-operator sy-length sy-lua">#</span><span class="sy-variable sy-other sy-lua">command</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">name</span>
  <span class="sy-keyword sy-control sy-end sy-lua">end</span></span>
<span class="sy-keyword sy-control sy-end sy-lua">end</span></span>

</span></code></pre>
    <p>Next, we can create our formatter.</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">entry_display</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.pickers.entry_display<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
<span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">displayer</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-variable sy-other sy-lua">entry_display</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">create</span></span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">separator</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span> <span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">items</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
    <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">width</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">longest_command_name</span> <span class="sy-keyword sy-operator sy-arithmetic sy-lua">+</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-lua">2</span> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    <span class="sy-comment sy-line sy-lua"><span class="sy-punctuation sy-definition sy-comment sy-lua">--</span> The final column can be set to fill the remaining space
</span>    <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">remaining</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-constant sy-language sy-boolean sy-true sy-lua">true</span> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span> 
  <span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span></span>
</span></code></pre>
    <h2>The Finder</h2>
    <p>With your commands set up, you can create a finder to hold the items. Telescope&apos;s finders support a lot of functionality, but here we just have a fixed set of commands in a table. The <code>finders.new_table</code> method creates a simple finder that can populate its results from this table.</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">finder</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-variable sy-other sy-lua">finders</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">new_table</span></span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">results</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">commands</span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">entry_maker</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-parameter sy-function sy-lua">entry</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
    <span class="sy-keyword sy-control sy-return sy-lua">return</span> <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
      </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">value</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">entry</span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
      </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">display</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-parameter sy-function sy-lua">ent</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
        <span class="sy-keyword sy-control sy-return sy-lua">return</span> <span class="sy-variable sy-function sy-lua">displayer</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
          <span class="sy-variable sy-other sy-lua">ent</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">value</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">name</span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
          <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span> <span class="sy-variable sy-other sy-lua">ent</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">value</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">category</span><span class="sy-punctuation sy-separator sy-field sy-lua">,</span> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>TelescopeResultsComment<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span> <span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span>
        <span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span></span>
      <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
      </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">ordinal</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">entry</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">name</span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    <span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span>
  <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
<span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span></span>
</span></code></pre>
    The <code>entry_maker</code> function above returns information for the picker to use.
      <ul class="list-bullet">
        <li>The <code>value</code> can be any arbitrary data. In this case we just use the <code>entry</code> itself.</li>
        <li><code>display</code> is a function that formats the item. We use our <code>displayer</code> from above to format the name and the category, with a highlight group applied to the category.</li>
        <li><code>ordinal</code> is the input to the picker&apos;s sorting algorithm. Here we&apos;re just sorting by name.</li>
      </ul>
    <h2>Showing the Window</h2>
    <p>Now we&apos;re ready to actually show our picker.</p>
    <pre><code><span class="sy-source sy-lua"><span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-entity sy-name sy-function sy-lua">showCommandBar</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-parameter sy-function sy-lua">opts</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
  <span class="sy-variable sy-other sy-lua">opts</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-variable sy-other sy-lua">opts</span> <span class="sy-keyword sy-operator sy-logical sy-lua">or</span> <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span><span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span>
  
  <span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">conf</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.config<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">values</span>
  <span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">actions</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.actions<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
  <span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">action_state</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-support sy-function sy-builtin sy-lua">require</span> <span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>telescope.actions.state<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span>
  
  <span class="sy-variable sy-other sy-lua">pickers</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">new</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-other sy-lua">opts</span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-section sy-block sy-begin sy-lua">{</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">prompt_title</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>Common commands<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">finder</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">finder</span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    <span class="sy-comment sy-line sy-lua"><span class="sy-punctuation sy-definition sy-comment sy-lua">--</span> Use the default sorter
</span>    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-string sy-unquoted sy-key sy-lua">sorter</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-variable sy-other sy-lua">conf</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">generic_sorter</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-other sy-lua">opts</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-lua"><span class="sy-entity sy-name sy-function sy-lua">attach_mappings</span></span><span class="sy-meta sy-mapping sy-lua"> </span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-key-value sy-lua">=</span></span><span class="sy-meta sy-mapping sy-value sy-lua"> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-parameter sy-function sy-lua">prompt_bufnr</span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-variable sy-parameter sy-function sy-lua">map</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
      <span class="sy-variable sy-function sy-lua">map</span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>i<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-string sy-quoted sy-single sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&apos;</span>&lt;CR&gt;<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&apos;</span></span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-meta sy-function sy-lua"><span class="sy-meta sy-block sy-lua"><span class="sy-storage sy-type sy-function sy-lua">function</span><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span>
        <span class="sy-variable sy-other sy-lua">actions</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">close</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-other sy-lua">prompt_bufnr</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
        <span class="sy-storage sy-modifier sy-lua">local</span> <span class="sy-variable sy-other sy-lua">selection</span> <span class="sy-keyword sy-operator sy-assignment sy-lua">=</span> <span class="sy-variable sy-other sy-lua">action_state</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">get_selected_entry</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-variable sy-other sy-lua">prompt_bufnr</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
        <span class="sy-variable sy-other sy-lua">selection</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">value</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">action</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
      <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
      <span class="sy-keyword sy-control sy-return sy-lua">return</span> <span class="sy-constant sy-language sy-boolean sy-true sy-lua">true</span>
    <span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span></span><span class="sy-meta sy-mapping sy-lua"><span class="sy-punctuation sy-separator sy-field sy-lua">,</span>
  <span class="sy-punctuation sy-section sy-block sy-end sy-lua">}</span></span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span><span class="sy-punctuation sy-accessor sy-lua">:</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">find</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>

<span class="sy-keyword sy-control sy-end sy-lua">end</span></span></span>

<span class="sy-variable sy-other sy-lua">vim</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua">keymap</span><span class="sy-punctuation sy-accessor sy-lua">.</span><span class="sy-meta sy-property sy-lua"><span class="sy-variable sy-function sy-lua">set</span></span><span class="sy-meta sy-function-call sy-arguments sy-lua"><span class="sy-meta sy-group sy-lua"><span class="sy-punctuation sy-section sy-group sy-begin sy-lua">(</span><span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>n<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span><span class="sy-punctuation sy-separator sy-comma sy-lua">,</span> <span class="sy-string sy-quoted sy-double sy-lua"><span class="sy-punctuation sy-definition sy-string sy-begin sy-lua">&quot;</span>&lt;leader&gt;k<span class="sy-punctuation sy-definition sy-string sy-end sy-lua">&quot;</span></span><span class="sy-punctuation sy-accessor sy-lua">.</span> <span class="sy-meta sy-property sy-lua">showCommandBar</span><span class="sy-punctuation sy-section sy-group sy-end sy-lua">)</span></span></span>
</span></code></pre>
    <p>Here we use the default sorter from the Telescope configuration. The <code>attach_mappings</code> argument lets us add special actions into the picker, and we add one action so that the Enter key will close the picker, get the selected item, and run its action.</p>
    <p>Finally, we created a key mapping that would run the function. And that&apos;s it!</p>
    <h2>Next Steps</h2>
    <p>We covered just the basics here, but there&apos;s a lot of opportunity for more advanced functionality.</p>
    <p>By moving more of this code inside the <code>showCommandBar</code> function, you could customize the commands based on aspects of the current buffer, such as showing certain commands only for certain file types.</p>
    <p>My current full implementation of this technique can be <a href="https://github.com/dimfeld/dotfiles/blob/master/nvim/.config/nvim/lua/config/telescope.lua">found on Github</a>.</p>
    <p>If you build any other cool functionality around this, I&apos;d love to hear it!</p>]]></description><link>https://imfeld.dev/writing/creating_a_custom_command_bar_in_neovim</link><guid isPermaLink="false">5071f04e62539c91a6d672ce5425d3f5e9ca1caa81bb9e4bcb7f8766f14db8fc</guid><pubDate>Fri, 14 Apr 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Are LLMs Databases?]]></title><description><![CDATA[<p>Are LLMs Databases? This topic has been hot recently, and it&apos;s an interesting question, if only because it helps us to think more deeply about what the LLM is actually doing.</p>
    <p>The argument in favor of this, from what I&apos;ve seen, is that LLMs, like databases, take in a query and return some data related to the query, just like a database. But the metaphor falls apart under closer examination.</p>
    <p>Databases let you write queries with an expected result. LLMs sort of do this, but the query parsing is unpredictable even when you set temperature to 0. Databases have a way to query and or aggregate for exactly what you want, whereas LLMs do not.</p>
    <p>Most significantly, LLMs will invent results instead of returning an empty set.</p>
    <p>Much of this is because the LLM doesn&apos;t actually store individual records. It has only sets of probabilities, given a string of tokens, for what the next token should be. While some argue that these connections are database-like, I would counter that <em class="italic">tokens</em> are not the actual unit of information that the user cares about.</p>
    <p>At best, an LLM could be thought of as a database which is lossily compressed. The data goes in, is translated into a smaller form, and then records can be pulled back out but with a loss of precision. Even this metaphor doesn&apos;t describe them well though. Lossy compression is usually applied on images, audio, or time-series data older than a certain date. But in this case, the nature of the compression is understood, and the quality of the reconstructed output is well-characterized. This is not the case for LLMs.</p>
    <p>Others have argued that LLMs are better thought of as &quot;reasoning engines&quot; than as databases. This is better, partially because it comes closer to describing the behavior, but also because it is a term without decades of prior art to compare with.</p>]]></description><link>https://imfeld.dev/writing/are_llms_databases</link><guid isPermaLink="false">2b10cce6fd84a5d41cad6940045fcda22cdab0a269ac776d13aba2ecba43c11c</guid><pubDate>Tue, 11 Apr 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Administrative and Statistical Regions in Geospatial Analysis]]></title><description><![CDATA[<p>In the previous article we looked at <a href="https://imfeld.dev/writing/loading_geographic_data_in_a_format_you_can_actually_use">loading and converting data for use in a web application</a>. Now it&apos;s time to cover some of the structure of this data, and different types of regions that you might want to use.</p>
    <p>As you start to work with international mapping data, you&apos;ll notice that region fields tend to be named generic things like <code>admin2</code>. This seems odd at first, but it is done with good reason. In this article we&apos;ll look at how administrative boundaries differ and are represented in mapping data, and then look at various types of official and unofficial regions used in the United States.</p>
    <h2>Worldwide values </h2>
        <p>Most countries divide their regions into multiple levels. These official divisions of countries are called administrative regions or administrative divisions. Administrative divisions are distinguished by level, and each one corresponds to the level of the division in a country, irrespective of how it compares to that of other countries.</p>
        <p>There are usually up to four administrative region levels, but both the structure and the names of the region types varies by country. The first level usually corresponds to states, provinces, and so on. The second level may be counties or districts, in countries that use them. The third level may be cities. This isn&apos;t a hard and fast rule though &#x2014; it&apos;s very much dependent on how a particular country divides itself up.</p>
        <p>In mapping data these levels are usually designated <code>admin0</code> for the country, <code>admin1</code> for the first level of divisions, <code>admin2</code> for the second level, and so on. Again, the exact meaning of these is particular to the country.</p>
        <p>Canada has ten provinces, each of which has a different way of splitting itself up.</p>
        <p>Iceland has one of the simpler region structures. Its level one division is 64 municipalities that cover the country, and there are no further official levels.</p>
        <p>The Philippines uses four levels of division. The first level is just called the &quot;region&quot;, and the second level consists of provinces or districts, and also &quot;independent cities&quot; which are geographically located inside a province but don&#x2019;t officially belong to it. The third level then consists of cities and municipalities inside provinces, and the fourth level is the <em class="italic">barangay</em>, which is something like a neighborhood but with its own small government.</p>
        <p>Independent cities usually go straight from the level two city to the level four <em class="italic">barangay</em>, so map creators will often just fill in a level three division which has the same name and size as the city.</p>
        <p>All this is to say that administrative divisions vary widely as you look at different places around the world. So the simple numbering of divisions was done with good reason and makes it much easier to use the data without needing to handle each country&apos;s peculiarities right away.</p>
        <p>Each region will have a unique ID that identifies it in addition to the name, for continuity across name changes and to help when joining to other data. The ID values for a country&apos;s regions are often managed by that country&apos;s government, so different sources of geographic data can all share the same set of IDs.</p>

    <h2>Unofficial Divisions </h2>
        <p>Administrative divisions reflect political boundaries, but there are many unofficial types of divisions used as well. I live in the United States, so I&apos;ll use it for these example, but most other countries have their own versions of these ideas.</p>
        <p>The USA is officially divided into states, counties, and cities and towns. Some states have variations, such as Virginia&apos;s independent cities, which sit within counties but are not actually part of those counties.</p>
        <p>Mapping with administrative regions is useful both because they reflect meaningful governmental boundaries and because people living in those areas are familiar with them, but they aren&apos;t always convenient for statistical analysis.</p>
        <p>In the San Francisco Bay Area, you can drive through three counties in less than an hour with no clear delineation between them. The towns of Palo Alto and Mountain View are in separate counties, but you wouldn&apos;t know it without a map.</p>
        <p>So what other kinds of regions do we have?</p>
        <h3>Census Regions </h3>
            <p>Beyond the administrative divisions, the US Census maintains additional breakdowns. These are useful for research and statistical purposes both because they correspond more to areas where people actually live, and because they update occasionally as population patterns shift throughout the country.</p>
            <p>At the highest level, the Census splits the USA into four regions, each consisting of a group of states, and each region is further split into two or three divisions.</p>
            <p>Metropolitan Statistical Areas (MSAs) are centered around an urban area with at least 50,000 people. These areas commonly encompass more than one city, such as the Los Angeles-Long Beach-Anaheim MSA, and also include surrounding areas from where people commute.</p>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/LaLongBeachMSA_1677818616455_0-w650-AYaotj50-3toIaZTUP3IYw.avif" type="image/avif" width="650" height="388">
  <source srcset="https://images.imfeld.dev/blog/LaLongBeachMSA_1677818616455_0-w650-AYaotj50-3toIaZTUP3IYw.webp" type="image/webp" width="650" height="388">
  <source srcset="https://images.imfeld.dev/blog/LaLongBeachMSA_1677818616455_0-w650-AYaotj50-3toIaZTUP3IYw.png" type="image/png" width="650" height="388">
  <img src="https://images.imfeld.dev/blog/LaLongBeachMSA_1677818616455_0-w650-AYaotj50-3toIaZTUP3IYw.png" alt="LaLongBeachMSA.png" width="650" height="388">
</picture>
</p>
            <p>Large MSAs are sometimes split into Metropolitan Divisions as well, when there is a primary core of at least 2.5 million people and additional smaller cores in the same general area.</p>
            <p>A Micropolitan Statistical Area (sometimes abbreviated &#x3bc;SA) is similar, but covers urban areas with between 10,000 and 50,000 people.</p>
            <p>Metropolitan and Micropolitan Statistical Areas together are called Core-Based Statistical Areas, or CBSAs. Many rural areas of the USA are not  in any CBSA, due to the lower limit of 10,000 people on Micropolitan areas.</p>
            <p>There are also 172 Combined Statistical Areas in the USA, which are groups of adjacent CBSAs. The New York&#x2013;Newark CSA, pictured below, is comprised of seven individual CBSAs.</p>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/New_York_Combined_Metro_Area_1677818334917_0-w650-AYaotj50VtE9NLGMMn7B0Q.avif" type="image/avif" width="650" height="596">
  <source srcset="https://images.imfeld.dev/blog/New_York_Combined_Metro_Area_1677818334917_0-w650-AYaotj50VtE9NLGMMn7B0Q.webp" type="image/webp" width="650" height="596">
  <source srcset="https://images.imfeld.dev/blog/New_York_Combined_Metro_Area_1677818334917_0-w650-AYaotj50VtE9NLGMMn7B0Q.png" type="image/png" width="650" height="596">
  <img src="https://images.imfeld.dev/blog/New_York_Combined_Metro_Area_1677818334917_0-w650-AYaotj50VtE9NLGMMn7B0Q.png" alt="New_York_Combined_Metro_Area.png" width="650" height="596">
</picture>
</p>
            <p>At the local level, the US Census divides counties into Census Tracts, which are not administrative divisions, but sized to contain between 1,200 to 8,000 people each. These regions&apos; boundaries are relatively stable to enable better statistical comparison over time, but they do occasionally change in response to drastic population shifts. Tracts are further divided into block groups, areas of between roughly 600 to 3,000 people.</p>
            <p>The Census publishes <a href="https://www.census.gov/geographies/mapping-files/time-series/geo/cartographic-boundary.html">shapefiles for all of these region types</a>, but they use <a href="https://www.census.gov/library/reference/code-lists/ansi.html">FIPS code</a> labels such as <code>STATEFP</code> instead of the <code>admin</code> labels used by data designed to span multiple countries.</p>

        <h3>ZIP Codes </h3>
            <p>ZIP Codes are a complex topic unto themselves. We think of them as areas, but a ZIP code is actually just a collection of mail delivery routes or links to a primary mail distribution center, and does not officially represent an actual area.</p>
            <p>This presents a challenge since ZIP codes are used for a lot of other purposes in which they do need to represent areas, so the US Census has created the <a href="https://www.census.gov/programs-surveys/geography/guidance/geo-areas/zctas.html">ZIP Code Tabulation Area (ZCTA)</a> as a solution. They mostly are the same as ZIP codes, but there are a few differences.</p>
            <p>ZCTAs are defined by the most frequently occurring ZIP code in a census block group. A block group occasionally will more than one ZIP code covering it, so a small amount of addresses in the country may be in a ZCTA that does not match the actual ZIP code. ZCTAs can also be expanded to cover small areas that have no ZIP code, and there may not be a ZCTA for &quot;unique&quot; ZIP codes which are assigned to a single large institution or building.</p>

        <h3>Other Region Types</h3>
            <p>Healthcare researchers commonly use geographic data in their work, and the <a href="https://data.dartmouthatlas.org/">Dartmouth Atlas of Health</a> has created their own set of divisions in the USA. They split the country into 306 Healthcare Referral Regions (HRRs), which group people by where they tend to go for more complex procedures and surgery, and 3,436 Healthcare Service Areas (HSAs), which group together populations by where they receive hospitalizations.</p>
            <p>School districts are valuable in researching children&apos;s education. Their boundaries often reflect social and political divisions, and the correlations between measures in a school district and other economic or social measures can yield valuable insights.</p>
            <p>Legislative districts are another common mapping case. These determine who represents a particular geographic area in a branch of the government, and are often a source of controversy as they are continually redrawn in ways that shift the balance of power toward one party or another.</p>

        <p>With all this in mind, you should start to feel more comfortable looking at geographic data files. Later in this article series, we&apos;ll look at using the region data to display useful insights in a web application.</p>]]></description><link>https://imfeld.dev/writing/administrative_and_statistical_regions_in_geospatial_analysis</link><guid isPermaLink="false">979fe8038152eb675d30bd405e349fc098b0c80b5662b1abf9761bb3402a4c21</guid><category><![CDATA[Geodata]]></category><pubDate>Sat, 04 Mar 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Loading Geographic Data in a Format You Can Actually Use]]></title><description><![CDATA[<p>In <a href="https://imfeld.dev/writing/introduction_to_geojson">the previous article</a> we covered the GeoJSON format, which is the most common format encountered when working with geographic data in Javascript.</p>
    <p>But geographic data often comes in specialized formats which are not seen elsewhere. Like much else in this world, it can seem intimidating at first, but with a little bit of knowledge you can do quite a lot. Let&apos;s take a look.</p>
    <h2>Data Formats</h2>
        <h3>Shapefiles </h3>
            <p>Shapefiles are the most common format for publishing geographic data. They were invented in the early 1990s by ESRI, a well-known maker of geographic information system (GIS) software. This format has since been adopted by most other publishers of geographic data.</p>
            A shapefile set consists of a few different files, which are differentiated by their extension.
              <ul class="list-bullet">
                <li>The <code>.shp</code> file holds the actual geometries for each shape in the shapefile. The format is binary but the set of shape types supported roughly overlaps with the set of shapes supported by GeoJSON. You&apos;ll find that this overlap occurs for most formats.</li>
                <li>The <code>.dbf</code> file holds attributes for each feature, such as the name or a numeric identifier. This is a dBase database file, which is rarely encountered nowadays, but was popular in the early 1990s when the shapefile format was invented.</li>
                <li>The <code>.shx</code> file  provides a quick lookup to a location of a particular shape inside the <code>.shp</code> file. This can be useful for seeking to a particular shape in a shapefile, but is generally not needed for conversion purposes.</li>
                <li>The optional <code>.prj</code> file contains information about what type of projection the data is in. This assists map renderers in displaying the data, and is crucial when converting it into another format. I&apos;ll discuss projections in a later section.</li>
              </ul>
            <p>Looking at a download from the US Census, we see these files.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> ls<span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>l</span></span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rw-rw----</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell">    5 dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.cpg</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rw-rw----</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 243k dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.dbf</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rw-rw----</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell">  165 dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.prj</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rw-rw----</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 6.6M dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.shp</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rwxrwxrwx</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell">  16k dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.shp.ea.iso.xml</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rwxrwxrwx</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell">  33k dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.shp.iso.xml</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">.rw-rw----</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 7.6k dimfeld  8 Apr  2022 cb_2021_us_cbsa_500k.shx</span>

</span></code></pre>
            <p>In addition to the file types mentioned above, you can see there are other auxiliary files which may be included with a shapefile set. These are mostly just other ways of indexing or describing the data, and are not useful when converting data away from the shapefile format, but the <a href="https://en.wikipedia.org/wiki/Shapefile">Wikipedia page</a> describes them all if you&apos;re curious.</p>
            <p>You probably will not have to deal with these individual files yourself. Shapefile importers do the work of combining the shapes from the <code>.shp</code> with the attributes in the <code>.dbf</code> and writing them out all together.</p>
            Shapefiles for different regions can be found all over the internet. If you have a specific region in mind, government-related websites and universities are often a good place to look. For more general needs, here are a few of the best sources:
              <ul class="list-bullet">
                <li><a href="https://datacatalog.worldbank.org/search/dataset/0038272/World-Bank-Official-Boundaries">The World Bank</a> provides shapefiles for every country.</li>
                <li><a href="https://hub.arcgis.com/search?collection=Dataset">ArcGIS Hub</a> is one of the best sources for shapefiles for international use.</li>
                <li>The <a href="https://www.census.gov/geographies/mapping-files.html">US Census</a> publishes detailed shapefiles for every region in the USA.</li>
              </ul>
            <p>Many shapefile datasets require attribution, and some place limits on commercial use, so be sure to comply with the terms when publishing your maps.</p>

        <h3>US Census </h3>
            <p>If you&apos;re making maps in the USA, this is one of the best data sources. The US Census Bureau not only publishes demographic information on the USA, but also detailed mapping data covering the entire country.</p>
            <h3>TIGER/Line Shapefiles</h3>
                <p>The <a href="https://www.census.gov/geographies/mapping-files/time-series/geo/tiger-line-file.html">TIGER/Line Shapefiles</a> dataset has detail down to the road and street level, and can be used to create just about any map of the USA that you want.</p>
                <p>PostgreSQL/PostGIS also has <a href="https://postgis.net/docs/Extras.html#Tiger_Geocoder">facilities to use this data for geocoding</a>, which is the process of converting between addresses and latitude/longitude coordinates. If you want to load this data, your best bet is to use the <a href="https://postgis.net/docs/Loader_Generate_Script.html">scripts provided by PostGIS</a>.</p>
                <p>For most applications, you don&apos;t actually need this level of data, and if you want to show streets in your map it&apos;s much simpler to use a tile layer &#x2014; the background layer of the map &#x2014; that includes them. We&apos;ll discuss doing this in a later article.</p>

            <h3>Cartographic Boundaries</h3>
                <p>If you don&apos;t need the TIGER/Line dataset&apos;s extreme level of detail, the <a href="https://www.census.gov/geographies/mapping-files/time-series/geo/cartographic-boundary.html">Cartographic Boundary Shapefiles</a> are for you. These are much smaller datasets which show region boundaries in the USA, and come in three different scales, or levels of detail.</p>
                <p>These shapefiles cover many different types of regions that the census works with, from states down to block groups. Counties and states are a good place to start since people are familiar with them.</p>
                <p>Core Based Statistical Areas (CBSAs) are less well-known, but also a good choice for some applications. They are formed around regions in which people actually live, as opposed to county boundaries which don&apos;t always relate to actual population distributions. CBSAs do not cover the whole country though. Each one is placed around an urban center with at least 10,000 people, so many rural areas will not be inside a CBSA.</p>
                <p>Finally, ZIP Code Tabulation Areas (ZCTAs) are mostly &#x2014; but not exactly &#x2014; like ZIP codes. ZIP codes sometimes have weird shapes for mapping since they&apos;re just designed for use by the Postal Service, but they can be useful if you need more granular shapes for regions that cover the entire country, and also want to use something that the average non-GIS expert is familiar with.</p>

            <p>I&apos;ll cover the various types of US regions and how each one is actually defined in a later article in this series.</p>

        <h3>KML </h3>
            <p>Keyhole Markup Language (KML) is an XML-based format which was invented for Google Earth. KML tends to compress a bit better than shapefiles, but the uncompressed files are much larger.</p>
            <p>Most sources of KML also publish the same data in shapefile format, so you won&apos;t often need to work with it.</p>

        <h3>GPS Data </h3>
            <p>GPS data comes in many formats. GPX is one of the most common and is based on XML. Garmin&apos;s FIT format is also popular, especially in fitness-centered applications.</p>
            <p>Geographic data is usually not published in these formats, but you are likely to encounter it if you create an application that lets users upload GPS data from their own activity.</p>

        <h3>OpenStreetMap </h3>
            <p>The <a href="https://www.openstreetmap.org/">OpenStreetMap</a> format is used by the organization of the same name. You generally won&apos;t encounter this data anywhere except from OpenStreetMap, but it&apos;s an excellent source if you need global mapping with features down to the street level.</p>
            <p>Like the US Census TIGER/Line dataset, it is extremely large. But if you do need this level of detail in a smaller region than the whole Earth, there are ways to create smaller regional extracts.</p>
            <p>I won&apos;t cover importing their data in this post, but the <a href="https://wiki.openstreetmap.org/wiki/Downloading_data">OpenStreetMap Wiki</a> has a good guide.</p>


    <h2>Coordinate Systems and Projections </h2>
        <p>Before loading the data, it helps to have a basic understanding of projections.</p>
        <p>Coordinate systems and projections are a complex topic worth an article (or more!) unto themselves, but put simply, a projection defines how to translate between latitude/longitude coordinates and actual points on the two-dimensional map.</p>
        <p>Many projections have an &quot;SRID&quot; registered with the <a href="https://en.wikipedia.org/wiki/EPSG_Geodetic_Parameter_Dataset">EPSG registry</a>, and you&apos;ll need this ID when loading your data.</p>
        <p>Fortunately, once you&apos;ve identified the projection, you don&apos;t really have to deal with the details or math yourself &#x2014; if you set the proper SRID, geography libraries such as PostGIS will do this hard work for you.</p>
        <h4>Coordinate Systems</h4>
            <p>Some SRIDs only reference coordinate systems. A coordinate system (or spatial reference system) indicates how latitude/longitude coordinates translate to exact spots on our not-quite-spherical Earth.</p>
            <p>GeoJSON uses the <a href="https://epsg.io/4326">WGS84</a> spatial reference system, which has SRID <code>4326</code>. This is one of the most widely-used coordinate systems.</p>
            <p>US Census shapefiles use SRID <code>4269</code>, which indicates the <a href="https://epsg.io/4269">NAD83</a> coordinate system. This is close to WGS84 but has a few small differences, and specifically accounts for North American tectonic plate movement over time. It differs from WGS84 by a few feet, which means that for most applications the difference is negligible.</p>

        <h4>Projections </h4>
            <p>Coordinate systems by themselves do not define a particular projection; that is, they don&apos;t specify a way to translate from coordinates to a 2D map.</p>
            <p>This is where projections come in. Some attempt to depict the entire Earth while making reasonable tradeoffs about the distortions that necessarily come with that translation. <a href="https://en.wikipedia.org/wiki/Mercator_projection">Mercator</a>, <a href="https://en.wikipedia.org/wiki/Albers_projection">Albers</a>, and <a href="https://en.wikipedia.org/wiki/Goode_homolosine_projection">Goode</a> are common examples of these types of projections.</p>
            <p>Other projections are designed for smaller areas. For example, the <a href="https://epsg.io/32618">UTM18 projection</a> (SRID <code>32618</code>) is specifically designed to accurately portray areas in the northern hemisphere, between 72 and 78 degrees West.</p>
            <p>When you have data that uses one of these projections, the points are not in longitude/latitude coordinates, but have been pre-converted to the locations where they would show up on a map or screen.</p>
            <p>This means that it&apos;s especially important to get the right SRID for the projection, since the data will look totally wrong otherwise. Fortunately, pasting the contents of the <code>.prj</code> file into Google usually brings up the answer if you aren&apos;t sure.</p>


    <h2>Loading Shapefiles </h2>
        <p>GIS professionals tend to use mapping software with native support for shapefiles. Web application developers usually do not, so we need to transfer it into a more suitable format.</p>
        <h3>PostgresSQL </h3>
            <p>PostGIS includes the <code>shp2pgsql</code> utility, which will read in a shapefile and dump out SQL to load it into a PostgreSQL database. It has various options on how to add the data, but the default is to create a new table with one column for each of the attributes in the <code>.dbf</code> file, and a column named <code>geom</code> to hold the shape itself.</p>
            <p>First, you&apos;ll need to install PostGIS and enable it in your database, if you haven&apos;t already. The PostGIS website has <a href="https://postgis.net/workshops/postgis-intro/installation.html">installation instructions for both Windows and Mac</a>. On Linux/Unix the system package manager should have everything you need.</p>
            <p>On Mac you can also use the <a href="https://brew.sh/">Homebrew package manager</a>, or just install <a href="https://postgresapp.com/downloads.html">Postgres.app</a> and <a href="https://postgresapp.com/documentation/cli-tools.html">set up its CLI tools</a>.</p>
            <p>Once you have PostgreSQL and PostGIS installed, you can create your database and enable the PostGIS extension.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> psql<span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>d</span> postgres</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">psql</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> (14.7 (Homebrew</span><span class="sy-meta sy-function-call sy-shell"></span>)<span class="sy-meta sy-function-call sy-shell"></span>)
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">Type</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>help<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> for help.</span>

<span class="sy-variable sy-other sy-readwrite sy-assignment sy-shell">postgres</span><span class="sy-keyword sy-operator sy-assignment sy-shell">=</span><span class="sy-string sy-unquoted sy-shell">#</span> <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">create</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> database geodataapp</span><span class="sy-keyword sy-operator sy-logical sy-continue sy-shell">;</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">CREATE</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> DATABASE</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">Time:</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 189.309 ms</span>
<span class="sy-variable sy-other sy-readwrite sy-assignment sy-shell">postgres</span><span class="sy-keyword sy-operator sy-assignment sy-shell">=</span><span class="sy-string sy-unquoted sy-shell">#</span> <span class="sy-constant sy-character sy-escape sy-shell">\c</span> <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">geodataapp</span></span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">You</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> are now connected to database <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>geodataapp<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> as user <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>dimfeld<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span>.</span>
<span class="sy-variable sy-other sy-readwrite sy-assignment sy-shell">geodataapp</span><span class="sy-keyword sy-operator sy-assignment sy-shell">=</span><span class="sy-string sy-unquoted sy-shell">#</span> <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">create</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> extension postgis</span><span class="sy-keyword sy-operator sy-logical sy-continue sy-shell">;</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">CREATE</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> EXTENSION</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">Time:</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 1638.587 ms (00:01.639</span><span class="sy-meta sy-function-call sy-shell"></span>)
</span></code></pre>
            <p>With this done, you can load your data.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> shp2pgsql<span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>h</span></span>
<span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Shows all the options</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span><span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Omitted for brevity</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span>
<span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> shp2pgsql <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell">  -</span>s</span> 4296 <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Set the SRID \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-D <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Output in dump format, faster to insert \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-I <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Generate an index on the geometry \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">cb_2021_us_cbsa_500k.shp</span></span> <span class="sy-keyword sy-operator sy-logical sy-pipe sy-shell">|</span> <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> US Census CBSA shapes \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span>    <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">psql</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>d</span> geodataapp</span>
</span></code></pre>
            <p>If we look at the generated SQL instead of piping it directly into <code>psql</code>, we see something like this.</p>
            <pre><code><span class="sy-source sy-sql"><span class="sy-keyword sy-other sy-DML sy-sql">SET</span> CLIENT_ENCODING TO UTF8;
<span class="sy-keyword sy-other sy-DML sy-sql">SET</span> STANDARD_CONFORMING_STRINGS TO ON;
<span class="sy-keyword sy-other sy-LUW sy-sql">BEGIN</span>;
<span class="sy-meta sy-create sy-sql"><span class="sy-keyword sy-other sy-create sy-sql">CREATE</span> <span class="sy-keyword sy-other sy-sql">TABLE</span> </span><span class="sy-meta sy-toc-list sy-full-identifier sy-sql">&quot;<span class="sy-entity sy-name sy-function sy-sql">cb_2021_us_cbsa_500k</span>&quot;</span> (gid <span class="sy-storage sy-type sy-sql">serial</span>,
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>csafp<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">3</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>cbsafp<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">5</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>affgeoid<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">14</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>geoid<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">5</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>name<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">100</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>namelsad<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">100</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>lsad<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> <span class="sy-storage sy-type sy-sql">varchar</span>(<span class="sy-constant sy-numeric sy-sql">2</span>),
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>aland<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> float8,
  <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>awater<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> float8);
<span class="sy-meta sy-alter sy-sql"><span class="sy-keyword sy-other sy-create sy-sql">ALTER</span> <span class="sy-keyword sy-other sy-table sy-sql">TABLE</span> </span><span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>cb_2021_us_cbsa_500k<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> ADD <span class="sy-storage sy-modifier sy-sql">PRIMARY KEY</span> (gid);
<span class="sy-keyword sy-other sy-DML sy-sql">SELECT</span> AddGeometryColumn(<span class="sy-string sy-quoted sy-single sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&apos;</span><span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&apos;</span></span>,<span class="sy-string sy-quoted sy-single sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&apos;</span>cb_2021_us_cbsa_500k<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&apos;</span></span>,<span class="sy-string sy-quoted sy-single sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&apos;</span>geom<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&apos;</span></span>,<span class="sy-string sy-quoted sy-single sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&apos;</span>4296<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&apos;</span></span>,<span class="sy-string sy-quoted sy-single sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&apos;</span>MULTIPOLYGON<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&apos;</span></span>,<span class="sy-constant sy-numeric sy-sql">2</span>);
COPY <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>cb_2021_us_cbsa_500k<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span> (<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>csafp<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>cbsafp<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>affgeoid<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>geoid<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>name<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>namelsad<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>lsad<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>aland<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>awater<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>,geom) <span class="sy-keyword sy-other sy-DML sy-sql">FROM</span> stdin;
   ... many lines of data here
<span class="sy-meta sy-create sy-sql"><span class="sy-keyword sy-other sy-create sy-sql">CREATE</span> <span class="sy-keyword sy-other sy-sql">INDEX</span> </span><span class="sy-meta sy-toc-list sy-full-identifier sy-sql">ON &quot;cb_2021_us_cbsa_500k&quot; USING </span><span class="sy-meta sy-toc-list sy-full-identifier sy-sql"><span class="sy-entity sy-name sy-function sy-sql">GIST</span></span> (<span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>geom<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>);
<span class="sy-keyword sy-other sy-LUW sy-sql">COMMIT</span>;
ANALYZE <span class="sy-string sy-quoted sy-double sy-sql"><span class="sy-punctuation sy-definition sy-string sy-begin sy-sql">&quot;</span>cb_2021_us_cbsa_500k<span class="sy-punctuation sy-definition sy-string sy-end sy-sql">&quot;</span></span>;

</span></code></pre>

        <h3>SQLite </h3>
            <p>Spatialite, a geography extension for SQLite, also includes <a href="https://www.gaia-gis.it/fossil/spatialite-tools/index">tools for loading shapefiles</a>. Their loader tool is called, appropriately enough, <code>spatialite_tool</code>.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> spatialite_tool <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell">  -</span>i <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Import mode \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-shp</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> cb_2021_us_cbsa_500k <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Name of the shapefile (without extension) \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-d</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> db.sqlite <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Database file to write into \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-t</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> cbsas <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Table in the database to create \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-s</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> 4296 <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> The SRID \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">--charset</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> utf8 <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Character encoding listed in the CPG file. Use utf8 if not sure.</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span></code></pre>
            <p>Spatialite seems sparsely documented and I&apos;ve barely used it, but the <a href="http://www.gaia-gis.it/gaia-sins/spatialite-cookbook-5/cookbook_topics.01.html">cookbook</a> is a good starting point. Once you have it set up, the SQL functions for querying the data have a lot of overlap with PostGIS.</p>

        <h3>GeoJSON </h3>
            <p>Depending on your needs, you may just convert your data to GeoJSON and use it directly in your application. This makes it harder to filter and aggregate the shapes inside a database, but it is definitely the simplest way, especially if you haven&apos;t set up a database.</p>
            <p>The <a href="https://www.npmjs.com/package/shapefile">shapefile</a> NPM package includes a command named <code>shp2json</code> that will read a shapefile and output a <code>FeatureCollection</code> containing all the data.</p>
            <p>Wrapping everything in a <code>FeatureCollection</code> is nice because you can just parse the entire thing as a single JSON object. You can also pass the <code>-n</code> option to skip the <code>FeatureCollection</code> and write each <code>Feature</code> on its own line, as <a href="http://ndjson.org/">newline-delimited JSON</a>.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> npm<span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>g</span> install shapefile</span>

<span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Write each Feature on its own line</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> shp2json<span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell"> -</span>n</span> cb_2021_us_county_20m.shp <span class="sy-keyword sy-operator sy-assignment sy-redirection sy-shell">&gt;</span> counties.ndjson</span>

<span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Write to a FeatureCollection</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> shp2json cb_2021_us_county_20m.shp <span class="sy-keyword sy-operator sy-assignment sy-redirection sy-shell">&gt;</span> counties.json</span>
</span></code></pre>
            <aside class="note">
                <p>Previous versions of this article mentioned another tool for converting shapefiles to GeoJSON, but I&apos;ve since found that it doesn&apos;t handle some types of polygons properly, and so I&apos;ve removed the paragraph.</p>
</aside>


    <h2>Loading Other Formats </h2>
        <h3>Using ogr2ogr</h3>
            <p>The open-source GDAL package provides a tool named <a href="https://gdal.org/programs/ogr2ogr.html">ogr2ogr</a> which can convert from and to almost any format. It&apos;s a little more awkward to use and has a lot of options, but if you encounter some unusual format it can probably convert it.</p>
            <p>Generally it&apos;s worth using dedicated tools for the job though, as <code>ogr2ogr</code>&apos;s generalist nature can cause some quirks. One big exception is when your data is in an unusual projection and you&apos;re converting to GeoJSON.</p>
            <p>Most shapefile conversion tools will not reproject the data, but <code>ogr2ogr</code> has options to do just that.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">ogr2ogr</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell">  -</span>s_srs</span> <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>EPSG:3857<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Projection to convert from (3857 is Mercator) \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-t_srs</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>WGS84<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Projection to convert to \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">-f</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> GeoJSON <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Format to conver to \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">output.json <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Output destination \</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span>  <span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">shapes.shp <span class="sy-comment sy-line sy-number-sign sy-shell"><span class="sy-punctuation sy-definition sy-comment sy-begin sy-shell">#</span></span><span class="sy-comment sy-line sy-number-sign sy-shell"> Input file</span><span class="sy-comment sy-line sy-number-sign sy-shell">
</span></span></span></span></code></pre>
            <p>If you&apos;re using MySQL, <code>ogr2ogr</code> also appears to be the tool of choice for loading geographic data.</p>

        <h3>Loading GeoJSON into the Database</h3>
            <p>Sometimes you come across data that is already in GeoJSON format, but you want to load it into your database. While you can just use a <code>jsonb</code> column, this doesn&apos;t work well if you need to actually manipulate or filter the shapes with SQL.</p>
            <p>This is one good use case for <code>ogr2ogr</code> and since GeoJSON always uses the WGS84 coordinate system, you won&apos;t have to worry about projection issues causing problems. <code>ogr2ogr</code> can write directly into the database.</p>
            <pre><code><span class="sy-source sy-shell sy-bash"><span class="sy-meta sy-function-call sy-shell"><span class="sy-variable sy-function sy-shell">&#x24;</span></span><span class="sy-meta sy-function-call sy-arguments sy-shell"> ogr2ogr <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell">  -</span>f</span> <span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>PostgreSQL<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span>  PG:<span class="sy-string sy-quoted sy-double sy-shell"><span class="sy-punctuation sy-definition sy-string sy-begin sy-shell">&quot;</span>dbname=your-database-name user=your-username password=password<span class="sy-punctuation sy-definition sy-string sy-end sy-shell">&quot;</span></span> <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span>  data.json <span class="sy-punctuation sy-separator sy-continuation sy-line sy-shell">\
</span><span class="sy-variable sy-parameter sy-option sy-shell"><span class="sy-punctuation sy-definition sy-parameter sy-shell">  -</span>nln</span> table-name-to-create</span>
</span></code></pre>
            <p>If you don&apos;t mind doing your load in two parts, you can also load the GeoJSON data into a temporary table, then use the <code>ST_GeomFromGeoJSON</code> function to convert the data and write it into another table. You&apos;ll have to unpack the Feature attributes into columns manually though.</p>

        <h3>KML</h3>
            <p>The easiest thing to do with KML is just convert it into a shapefile or GeoJSON, and then load the resulting data into your application.</p>
            <p>As I mentioned above, most sources of KML also provide shapefiles, but if you have to deal with KML, <code>ogr2ogr</code> or the <a href="https://github.com/tmcw/togeojson-cli">togeojson</a> utility are good ways to handle it.</p>

        <h3>GPS Data</h3>
            <p><a href="https://www.gpsbabel.org/">GPSBabel</a> is a versatile tool for converting GPS data.  It supports reading GPX, FIT, and many other formats, and can write to both shapefile and GeoJSON.</p>


    <h2>Next Steps</h2>
        <p>Now that you know how to load geographic data, how do you actually use it? The next article in this series will start to answer that question.</p>
        <p>Also, many thanks to <a href="https://www.twitter.com/techniq35">Sean Lynch</a> for feedback on this article&apos;s initial draft, and to <a href="https://twitter.com/bramus">Bramus</a> for the tip about ogr2ogr&apos;s ability to convert between projections.</p>]]></description><link>https://imfeld.dev/writing/loading_geographic_data_in_a_format_you_can_actually_use</link><guid isPermaLink="false">2943025a6b45f7165f79cb22c9a2714fa6460c95cd7e822ec5880328f62c9ecd</guid><category><![CDATA[Geodata]]></category><pubDate>Sat, 18 Feb 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Introduction to GeoJSON]]></title><description><![CDATA[<p>Geographic data is ubiquitous in our lives. It is found in small applications like planning a vacation, and in complex worldwide topics such as population health and demographic studies. While the terms and systems involved may seem daunting at first, understanding geographic data can open up a lot of possibilities for visualizing and understanding the world.</p>
    <p>Nearly every web application that works with geographic data uses represents it as GeoJSON. This is a short overview of GeoJSON and its structure to help make more sense of it.</p>
    <p>In later articles in this series, I&apos;ll cover more interesting things you can do with geographic data and how to actually work with it, but this will provide a good foundation to build upon.</p>
    <p>As the name implies, GeoJSON is just a format for representing geographic data as JSON. It defines six types of geometries, and a few different containers that group them together or provide extra information.</p>
    <p>All images below are from <a href="https://geojson.io/">geojson.io</a>, a great tool for playing with and visualizing GeoJSON.</p>
    <h2>Points and Positions </h2>
        <p>The simplest geometry is the <code>Point</code>. Points are commonly used to indicate places of interest and other markers on maps where you just want to show the location, and don&apos;t need an area or boundary.</p>
        <p>A Point contains just a single position. In GeoJSON, a &quot;position&quot; is an array with two numbers: the longitude and the latitude, in that order.</p>
        <p>You may be accustomed to the more common &quot;latitude first, longitude second&quot; ordering. This is a common source of confusion when getting started, so it helps to think in terms of <code>[x, y]</code> coordinates instead.</p>
        <p>A position array may have a third value to represent elevation, but this is usually omitted unless the application requires it.</p>
        <p>Every GeoJSON geometry has a <code>type</code> field indicating what type of geometry it is, and a <code>coordinates</code> field that defines the shape itself. A point representing a random location in southern Australia looks like this:</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Point<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-float sy-decimal sy-json">137<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-32</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-point_1676017854016_0-w650-AYY6cyE0zHs99aPDwux8kA.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-point_1676017854016_0-w650-AYY6cyE0zHs99aPDwux8kA.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-point_1676017854016_0-w650-AYY6cyE0zHs99aPDwux8kA.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-point_1676017854016_0-w650-AYY6cyE0zHs99aPDwux8kA.jpg" alt="geojson-point.jpeg" width="650" height="650">
</picture>
</p>
</div>
        <p>You may also place multiple points into a single geometry using the <code>MultiPoint</code> type. In this case, the coordinates are an array of positions.</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>MultiPoint<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">137<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-32</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">133<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>1</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-30</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-multipoint_1676017913216_0-w650-AYY6dTadl78pqLFhnfsIbg.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multipoint_1676017913216_0-w650-AYY6dTadl78pqLFhnfsIbg.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multipoint_1676017913216_0-w650-AYY6dTadl78pqLFhnfsIbg.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-multipoint_1676017913216_0-w650-AYY6dTadl78pqLFhnfsIbg.jpg" alt="geojson-multipoint.jpeg" width="650" height="650">
</picture>
</p>
</div>
        <p><code>MultiPoint</code> should only be used when the set of points are conceivably actually part of the same object. There are better ways to represent multiple, independent points, which I&apos;ll cover later.</p>

    <h2>Lines </h2>
        <p>The <code>LineString</code> is useful when drawing lines on the map, such as when suggesting a route between two places. It contains a set of points that join together, connect-the-dots style, to form a line. As with <code>MultiPoint</code>, it contains an array of positions, but a valid <code>LineString</code> must contain at least two positions.</p>
        <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>LineString<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-46<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>64</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-23<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>577</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-22<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>9</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>94</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-19<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>89</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
        <p>GeoJSON also provides the <code>MultiLineString</code> type, which represents a set of related lines. Its coordinates are an array of <code>LineString</code> coordinates, with each array member drawing a single line.</p>
        <p>Although the lines are considered part of the same geometry, they are not connected together.</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>MultiLineString<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-46<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>64</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-23<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>577</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
	  <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-22<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>9</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>94</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-19<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>89</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-48<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>18</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-21<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>77</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-47<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>46</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-20<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>58</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-46<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>57</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-21<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>78</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-multilinepoint_1676019339259_0-w650-AYY6iZSUno63fEt6GHuw3g.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multilinepoint_1676019339259_0-w650-AYY6iZSUno63fEt6GHuw3g.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multilinepoint_1676019339259_0-w650-AYY6iZSUno63fEt6GHuw3g.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-multilinepoint_1676019339259_0-w650-AYY6iZSUno63fEt6GHuw3g.jpg" alt="geojson-multilinepoint.jpeg" width="650" height="650">
</picture>
</p>
</div>

    <h2>Making Geometries More Useful </h2>
        <p>A geometry on its own is just a shape, with no way to attach any other information to it. GeoJSON solves this with the <code>Feature</code> type, which wraps a geometry and allows you add any metadata you want.</p>
        <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Feature<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>id<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>marker-001<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>properties<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
    </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>name<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>My favorite place<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>icon<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>star<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>rating<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>a billion<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span>
  <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>geometry<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
    </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>LineString<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
    </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-46<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>64</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-23<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>577</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-22<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>9</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-43<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>94</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-19<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>89</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
        <p>The <code>id</code> property is optional but can be useful for linking a <code>Feature</code> back to a particular object in a database, or something similar.</p>
        <p>There is no defined schema for <code>properties</code> &#x2014; you can put any JSON object inside there.</p>

    <h2>Groups of Objects </h2>
        <p>A <code>FeatureCollection</code> allows you to group multiple <code>Feature</code> objects together in a single object.</p>
        <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>FeatureCollection<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>features<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> 
      </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Feature<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span> 
      </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>properties<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> 
        </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>name<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>my house<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span>
      <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span> 
      </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>geometry<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> 
      	</span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Point<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
        </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">1</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">2</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
      <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span> 
    <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-comment sy-line sy-double-slash sy-js"><span class="sy-punctuation sy-definition sy-comment sy-json">//</span> And so on....
</span>    <span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Feature<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span> </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>properties<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span> </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>geometry<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span> <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
        <p>The <code>GeometryCollection</code> type is similar, but for raw geometries instead of <code>Feature</code>. You probably won&apos;t encounter <code>GeometryCollection</code> often. Usually, one of the &quot;Multi&quot; objects or a <code>FeatureCollection</code> is a better fit, but it&apos;s good to know about.</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>GeometryCollection<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>geometries<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Point<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span> </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">0</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">51<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span> <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> 
      </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>LineString<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
      </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">0</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">51<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">1<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>55</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">50<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>7</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">2<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>35</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">48<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>85</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
      <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-geometrycollection_1676018882698_0-w650-AYY6gp6_mUDvFAOHUPtGKQ.webp" type="image/webp" width="650" height="649">
  <source srcset="https://images.imfeld.dev/blog/geojson-geometrycollection_1676018882698_0-w650-AYY6gp6_mUDvFAOHUPtGKQ.avif" type="image/avif" width="650" height="649">
  <source srcset="https://images.imfeld.dev/blog/geojson-geometrycollection_1676018882698_0-w650-AYY6gp6_mUDvFAOHUPtGKQ.jpg" type="image/jpg" width="650" height="649">
  <img src="https://images.imfeld.dev/blog/geojson-geometrycollection_1676018882698_0-w650-AYY6gp6_mUDvFAOHUPtGKQ.jpg" alt="geojson-geometrycollection.jpeg" width="650" height="649">
</picture>
</p>

</div>

    <h2>Polygons </h2>
        <p>The <code>Polygon</code> is commonly used to draw boundaries around geographic regions or other areas. This is one of the most used geometries in GeoJSON, but they do add additional complexity.</p>
        <p>Unlike a <code>LineString</code>, a <code>Polygon</code> must be explicitly closed. That is, the first and last points in the <code>Polygon</code> must be identical for it to be valid.</p>
        <p>Furthermore, the points in a <code>Polygon</code> must be in counterclockwise order. This rule makes it easier for renderers to figure out which side of the polygon is the outside vs. the inside, without needing to do additional calculations.</p>
        <p>There is no limit on the number of segments in a polygon. It can be as simple as a triangle or complex enough to follow the contours of a shoreline.</p>
        <p>The last <code>LineString</code> above would be represented like this:</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span> 
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Polygon<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">0</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">51<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">2<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>35</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">48<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>85</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">1<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>55</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">50<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>7</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">0</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">51<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-simplepolygon_1676081330066_0-w650-AYY-O31TUBkHVmxcvshijg.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-simplepolygon_1676081330066_0-w650-AYY-O31TUBkHVmxcvshijg.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-simplepolygon_1676081330066_0-w650-AYY-O31TUBkHVmxcvshijg.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-simplepolygon_1676081330066_0-w650-AYY-O31TUBkHVmxcvshijg.jpg" alt="geojson-simplepolygon.jpeg" width="650" height="650">
</picture>
</p>
</div>
        <p>You&apos;ll note that although there&apos;s just a single shape here, the array nesting looks more like a <code>MultiLineString</code>. This is because <code>Polygon</code> allows you to specify holes inside the shape as well.</p>
        <p>The below <code>Polygon</code> is a square with two smaller square holes inside it. The first entry represents the outer ring that gives the overall shape, and the other entries define the holes inside the polygon.</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>Polygon<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-28</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">30</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-28</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">30</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">27</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">27</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>         
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">29</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">29</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span><span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-polygonholes_1676081519094_0-w650-AYY-Pl-Y7AJDZfJVLDhtCQ.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-polygonholes_1676081519094_0-w650-AYY-Pl-Y7AJDZfJVLDhtCQ.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-polygonholes_1676081519094_0-w650-AYY-Pl-Y7AJDZfJVLDhtCQ.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-polygonholes_1676081519094_0-w650-AYY-Pl-Y7AJDZfJVLDhtCQ.jpg" alt="geojson-polygonholes.jpeg" width="650" height="650">
</picture>
</p>
</div>
        <p>While the outer ring of the <code>Polygon</code> has its points in counterclockwise order, the inner holes&apos; points must be in clockwise order, which again helps renderers to determine which side of the edge is inside the polygon.</p>
        <p>Ensuring that the points are in the correct order may seem difficult, but geometry libraries generally handle this for you. They also provide functions such as <a href="http://turfjs.org/docs/#rewind">turf&apos;s rewind</a> or <a href="https://postgis.net/docs/ST_ForcePolygonCCW.html">PostGIS&apos;s ST_ForcePolygonCCW</a>, which will take a polygon and &quot;fix&quot; the point order so that the outer line is counterclockwise and the inner ones are clockwise.</p>

    <h2>MultiPolygons </h2>
        <p>By now you can probably guess what a <code>MultiPolygon</code> is. These are very useful in representing geographic regions such as the state of Michigan or anything with islands, which can&apos;t be represented as a single contiguous shape.</p>
        <p>It starts to get hard to read with all the nested arrays, but the coordinates for a <code>MultiPolygon</code> is just an array of <code>Polygon</code> coordinates. This example shows a <code>MultiPolygon</code> that contains two polygons &#x2014; the square with holes from above, and a simple triangle.</p>
        <div class="code-and-image">
            <pre><code><span class="sy-source sy-json"><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-section sy-mapping sy-begin sy-json">{</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>type<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>MultiPolygon<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span><span class="sy-punctuation sy-separator sy-mapping sy-pair sy-json">,</span>
  </span><span class="sy-meta sy-mapping sy-key sy-json"><span class="sy-string sy-quoted sy-double sy-json"><span class="sy-punctuation sy-definition sy-string sy-begin sy-json">&quot;</span>coordinates<span class="sy-punctuation sy-definition sy-string sy-end sy-json">&quot;</span></span></span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-punctuation sy-separator sy-mapping sy-key-value sy-json">:</span> </span><span class="sy-meta sy-mapping sy-value sy-json"><span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-28</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">30</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-28</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">30</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">25</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-23</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
      <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">27</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">27</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">26</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-24</span><span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>         
      <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">29</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">29</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-25</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">28</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-26</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
      <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>

    <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
      <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">28<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-28<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">25<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>1</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-integer sy-decimal sy-json">-30</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">30<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-31<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span>
        <span class="sy-meta sy-sequence sy-json"><span class="sy-punctuation sy-section sy-sequence sy-begin sy-json">[</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">28<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>5</span><span class="sy-punctuation sy-separator sy-sequence sy-json">,</span> <span class="sy-constant sy-numeric sy-float sy-decimal sy-json">-28<span class="sy-punctuation sy-separator sy-decimal sy-json">.</span>2</span> <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
      <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
    <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
  <span class="sy-punctuation sy-section sy-sequence sy-end sy-json">]</span></span>
<span class="sy-punctuation sy-section sy-mapping sy-end sy-json">}</span></span>
</span></code></pre>
            <p>
<picture>
  <source srcset="https://images.imfeld.dev/blog/geojson-multipolygon_1676081931304_0-w650-AYY-RKhwfcEWOoItPDKUKw.avif" type="image/avif" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multipolygon_1676081931304_0-w650-AYY-RKhwfcEWOoItPDKUKw.webp" type="image/webp" width="650" height="650">
  <source srcset="https://images.imfeld.dev/blog/geojson-multipolygon_1676081931304_0-w650-AYY-RKhwfcEWOoItPDKUKw.jpg" type="image/jpg" width="650" height="650">
  <img src="https://images.imfeld.dev/blog/geojson-multipolygon_1676081931304_0-w650-AYY-RKhwfcEWOoItPDKUKw.jpg" alt="geojson-multipolygon.jpeg" width="650" height="650">
</picture>
</p>
</div>

    <h2>Summing Up </h2>
        <p>That covers all the different types of objects that you can create in GeoJSON. In future articles in this series, we&apos;ll look more into actually processing data and working with these objects in real applications.</p>]]></description><link>https://imfeld.dev/writing/introduction_to_geojson</link><guid isPermaLink="false">c99f2ebfec9931fa85978a7960eaab0177f1ba724f2a1a3fa169a0583e5b3be7</guid><category><![CDATA[Geodata]]></category><pubDate>Sat, 11 Feb 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Avoiding Deadlock from Rayon Thread Pool Exhaustion]]></title><description><![CDATA[<p>Tags: Rust</p><p><a href="https://github.com/rayon-rs/rayon/">Rayon</a> has a well-deserved reputation as one of the most useful Rust libraries. Its most famous feature is the ability to
parallelize almost any iterator computation by simply calling <code>par_iter()</code> instead of <code>iter()</code>. This is a groundbreaking feature among
programming languages in its class.</p>
<p>It transparently handles deciding how much to parallelize the iteration, spreading the data out to multiple threads, and then recombining
everything at the end. It even maintains a pool of precreated threads, so that you can use <code>par_iter</code> liberally without having
to worry about the overhead of creating and destroying threads.</p>
<p>But this thread pool did lead to an unexpected problem recently when I used Rayon in a <a href="https://github.com/dimfeld/perceive/blob/fa4f742d5d7a40b288d430f0df2a879df08772d1/crates/perceive-core/sources/pipeline/reprocess.rs#L85">data processing pipeline</a>.</p>
<h2 id="pipeline-design">Pipeline Design <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#pipeline-design">&#x1f517;</a></h2>
<p>The pipeline code is part of a <a href="https://github.com/dimfeld/perceive">search project</a> I&#x2019;ve been working on. The project uses an article parser for HTML &#x2013; think reader mode in your browser or <a href="https://readwise.io/read">Readwise</a> &#x2013; and the pipeline is designed to reprocess scanned data after installing an improved version of the parser.</p>
<p>There are four stages here:</p>
<ol>
<li>Read the items from the database</li>
<li>Reprocess the content for each item, and send it to the next stage.</li>
<li>If an item&#x2019;s processed output has changed with the new code, run it through the machine learning model to generate embeddings for
semantic search.</li>
<li>Update the database with the new information.</li>
</ol>
<p>Stage 2 uses Rayon to parallelize the processing algorithm across batches of content.
I didn&#x2019;t know it at the time, but stage 3 also uses Rayon when tokenizing the input to the ML model (which uses the excellent
<a href="https://github.com/guillaume-be/rust-bert/">rust-bert</a> crate).
The <a href="https://github.com/zesterer/flume">flume</a> crate provides channels to pass data from one stage to another.</p>
<p>But the pipeline would sometimes stall, with no obvious indication of problems other than a lack of progress and
the CPU/GPU utilization dropping to zero.</p>
<h2 id="debugging">Debugging <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#debugging">&#x1f517;</a></h2>
<p>Since GPU support for Mac in <code>libtorch</code> is still encountering some minor issues here and there, I first suspected that might have been the problem,
and so I resorted to the time-honored technique of sprinkling <code>dbg!</code> statements throughout the code to print to
the console as things happened.</p>
<p>This finally narrowed it down to the model&#x2019;s tokenizer starting to run, but never completing. But this part of the code was pure Rust and just did a bunch of string processing, with no <code>torch</code> code involved at all.</p>
<p>This seemed the least likely place for the pipeline to stall, until I looked into the tokenizer code itself and
saw that it was using Rayon as well. Armed with this revelation and no other ideas of what could possibly be
happening, I formed a theory.</p>
<h3 id="the-problem">The Problem <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#the-problem">&#x1f517;</a></h3>
<p>The ML model processes items in batches of 64 at a time, and running with an M1 Pro GPU this could take five to six
seconds for an average batch. When the pipeline is working, it looks something like this:</p>
<ol>
<li>Stage 2 sends a bunch of content to stage 3 through a channel.</li>
<li>Stage 3 reads the channel, and when it has accumulated 64 items that need to be run through the ML model, it processes them as a batch.</li>
<li>While the batch is processing, stage 2 continues to output content and fills up the channel again.</li>
<li>This repeats until all the items are processed.</li>
</ol>
<p>Depending on the thread scheduling, it could be possible for stage 2 to fill up the channel again between the time when stage
3 would read items from the channel, and when it would actually start processing a batch.</p>
<p>So finally &#x2013; and I should have just done this first &#x2013; I loaded the program into the debugger, ran until it got stuck, and halted the program.
As the debugger showed all the threads and their call stacks, I could see that stage 2 was running a bunch of Rayon threads, all waiting to output data into the full channel.</p>
<p>Stage 3&#x2019;s threads were in some Rayon code, waiting for a free thread from Rayon&#x2019;s thread pool to run on. But it couldn&#x2019;t get one until stage 2&#x2019;s code stopped blocking, and
they couldn&#x2019;t become unblocked until stage 3 processed its batch and consumed more data from the channel: a classic deadlock.</p>
<p>It turns out that the Rayon docs <a href="https://docs.rs/rayon/latest/rayon/fn.join.html#warning-about-blocking-io">do actually warn about this
too</a>, albeit in a less commonly used function.</p>
<h2 id="fixing-the-problem">Fixing the Problem <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#fixing-the-problem">&#x1f517;</a></h2>
<p>I didn&#x2019;t want to give up the parallelism in stage 2, because depending on how many of the items were different after
reprocessing, it could actually be the bottleneck. Fortunately Rayon provides a simple solution by allowing manual
creation of additional thread pools.</p>
<p>So stage 2 started out looking something like this:</p>
<pre><code class="language-rust"><span class="hljs-comment">// Simplified for readability</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">reprocess</span></span>(
    db_items_rx: flume::Receiver&lt;<span class="hljs-built_in">Vec</span>&lt;Item&gt;&gt;,
    processed_tx: flume::Sender&lt;ScanItem&gt;,
) -&gt; <span class="hljs-built_in">Result</span>&lt;()&gt; {
    <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> db_items_rx {
        batch.into_par_iter().try_for_each(|<span class="hljs-keyword">mut</span> item| {
            <span class="hljs-keyword">let</span> processed_item = reprocess(item)?;
            processed_tx.send(processed_item)
            <span class="hljs-literal">Ok</span>(())
        })?;
    }

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>And with the new thread pool, it changed to this:</p>
<pre><code class="language-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">reprocess</span></span>(
    db_items_rx: flume::Receiver&lt;<span class="hljs-built_in">Vec</span>&lt;Item&gt;&gt;,
    processed_tx: flume::Sender&lt;ScanItem&gt;,
) -&gt; <span class="hljs-built_in">Result</span>&lt;()&gt; {
    <span class="hljs-keyword">let</span> pool = rayon::ThreadPoolBuilder::new().build()?;

    pool.install(|| {
        <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> db_items_rx {
            batch.into_par_iter().try_for_each(|<span class="hljs-keyword">mut</span> item| {
                <span class="hljs-keyword">let</span> result = scanner.reprocess(&amp;<span class="hljs-keyword">mut</span> item)?;
                processed_tx.send(processed_item)
                <span class="hljs-literal">Ok</span>(())
            })?;
        }

        <span class="hljs-literal">Ok</span>(())
    })?;

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>The <code>ThreadPool::install</code> function takes a closure, and registers the thread pool so that any uses of Rayon inside that closure will use it instead of the global thread pool.</p>
<p>With that small change, everything worked properly.</p>
<h2 id="alternative-solutions">Alternative Solutions <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#alternative-solutions">&#x1f517;</a></h2>
<p>For a data pipeline like this, the auto-parallelism of Rayon is arguably not even a good fit, since the pipeline stages are long-lived and well defined.
Another solution would be to manually create the threads for each pipeline stage.</p>
<p>Since channel senders and receivers in <code>flume</code> (and most other channel libraries) can be cloned while referencing the same channel, this doesn&#x2019;t
take much effort, and would look something like this:</p>
<pre><code class="language-rust">std::thread::scope(|scope| {
    <span class="hljs-keyword">const</span> NUM_THREADS: <span class="hljs-built_in">usize</span> = <span class="hljs-number">4</span>;
    <span class="hljs-keyword">let</span> stage_tasks = itertools::repeat_n((db_items_rx, processed_tx), NUM_THREADS)
        .into_iter()
        .map((|db_items_rx, processed_tx)| {
            scope.spawn(|| reprocess(db_items_rx, processed_tx))   
        })
        .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;_&gt;&gt;();

    <span class="hljs-comment">// Spawn other tasks, handle thread results, etc.</span>
});
</code></pre>
<h2 id="takeaways">Takeaways <a class="header-anchor" href="https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion#takeaways">&#x1f517;</a></h2>
<p>Thread pools are great, but can cause problems when multiple pieces of code with control flow dependencies are sharing
the same pool.</p>
<p>Use the debugger as a first resort! VS Code&#x2019;s Rust debugging support works great. I believe NeoVim&#x2019;s support is quite good now too,
but I haven&#x2019;t tried it yet.</p>
]]></description><link>https://imfeld.dev/writing/avoiding_rayon_thread_pool_exhaustion</link><guid isPermaLink="false">36601e210c1bbf5e45c9a685ab2687f0e2fe50f6e1aa65819fe3c40221cc15a5</guid><category><![CDATA[Rust]]></category><pubDate>Mon, 09 Jan 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Switching Result and Option in Rust with Transpose]]></title><description><![CDATA[<p>Tags: Rust</p><p>When writing Rust code, it&#x2019;s common to have an <code>Option</code> value that you want to map through some fallible operation. For example, you have an <code>Option&lt;String&gt;</code> and you want to parse it as an integer. You could do something like this:</p>
<pre><code class="language-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">parse_maybe_int</span></span>(s: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;) -&gt; <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">i32</span>, ParseIntError&gt;&gt; {
    s.map(|s| s.parse::&lt;<span class="hljs-built_in">i32</span>&gt;())
}
</code></pre>
<p>But this gets awkward if you want to return an error when the parsing fails, but don&#x2019;t want to unwrap the <code>Option</code> just yet. When I first started writing Rust I would use the match syntax to take care of it.</p>
<pre><code class="language-rust"><span class="hljs-keyword">let</span> input = <span class="hljs-literal">Some</span>(<span class="hljs-string">&quot;3&quot;</span>.to_string());
<span class="hljs-keyword">let</span> value = <span class="hljs-keyword">match</span> parse_maybe_int(input) {
    <span class="hljs-literal">Some</span>(<span class="hljs-literal">Ok</span>(value)) =&gt; value,
    <span class="hljs-literal">Some</span>(<span class="hljs-literal">Err</span>(e)) =&gt; <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(e),
    <span class="hljs-literal">None</span> =&gt; <span class="hljs-literal">None</span>,
};
</code></pre>
<p>But one of Rust&#x2019;s best features is the <code>?</code>  operator, which allows you to unwrap a <code>Result</code> and return if it&#x2019;s an error.
So having to write this match every time gets old quick.</p>
<p>Fortunately, there&#x2019;s a method in the standard library that addresses this exact problem. When you have an
<code>Option&lt;Result&lt;T, _&gt;&gt;</code> or a <code>Result&lt;Option&lt;T&gt;, _&gt;</code> you can use the <code>transpose</code> method to swap the <code>Result</code> and <code>Option</code>.</p>
<pre><code class="language-rust"><span class="hljs-keyword">let</span> input = <span class="hljs-literal">Some</span>(<span class="hljs-string">&quot;3&quot;</span>.to_string());
<span class="hljs-keyword">let</span> value = parse_maybe_int(input).transpose()?;
</code></pre>
<p>And then from there, you can build the transpose straight into the method:</p>
<pre><code class="language-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">parse_maybe_int</span></span>(s: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt;, ParseIntError&gt; {
    s.map(|s| s.parse::&lt;<span class="hljs-built_in">i32</span>&gt;()).transpose()
}

<span class="hljs-keyword">let</span> input = <span class="hljs-literal">Some</span>(<span class="hljs-string">&quot;3&quot;</span>.to_string());
<span class="hljs-keyword">let</span> value = parse_maybe_int(input)?;
</code></pre>
<p>Much better.  I haven&#x2019;t seen <code>transpose</code> mentioned much, but I&#x2019;ve found it very useful, so I hope this helps someone.</p>
]]></description><link>https://imfeld.dev/writing/rust_option_result_transpose</link><guid isPermaLink="false">368ed0f0c0f314f62065b2232a5ef1b2f87bb2f715245b1cb75df2c42659626f</guid><category><![CDATA[Rust]]></category><pubDate>Thu, 05 Jan 2023 00:00:00 GMT</pubDate></item><item><title><![CDATA[Process Streaming Uploads with Axum]]></title><description><![CDATA[<p>Tags: Rust</p><p>Many web services allow the user to upload a file and save it to some other place such as Amazon S3. Commonly, you can tell S3 to generate a special presigned URL which the client can use to upload the file to a specific location.</p>
<p>But sometimes you also want to be able to process the data as it streams through, which means it&#x2019;s easiest to handle it
yourself.</p>
<p>I had a need for this in my <a href="https://imfeld.dev/notes/projects_pic_store">Pic Store</a> project recently. When the user uploads an image, it passes the data through to the destination backing store, such as S3, but it also needs to calculate a hash of the image and figure out the format and dimensions.</p>
<p>This project uses the Rust <a href="https://github.com/tokio-rs/axum">Axum</a> framework, but the same techniques work across other
frameworks as well.</p>
<h1 id="receive-the-request-as-a-stream">Receive the request as a stream <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#receive-the-request-as-a-stream">&#x1f517;</a></h1>
<p>First, we set up our route handler with a streaming reader. Axum provides a <code>BodyStream</code> extractor which does the hard work for us.</p>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">upload_image</span></span>(
  <span class="hljs-comment">// Other data -- app state, user info, etc.</span>
  State(state): State&lt;AppState&gt;,
  Authenticated(user): Authenticated,
  Path(image_id): Path&lt;BaseImageId&gt;,
  <span class="hljs-comment">// The actual request body</span>
  stream: BodyStream,
) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-keyword">impl</span> IntoResponse, Error&gt; {
  <span class="hljs-keyword">let</span> image_location = get_base_image(&amp;state, &amp;user, image_id).<span class="hljs-keyword">await</span>?;
  todo!();
}

<span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">configure_router</span></span>() -&gt; Router {
    Router::new()
        .post(&apos;/images/:image_id/upload&apos;, upload_image)
        <span class="hljs-comment">// And so on...</span>
}
</code></pre>
<p>The handler starts by reading the database to figure out where the image should be stored, if the user has permission to upload this image, and so on. I&#x2019;ll skip over the details here since they&#x2019;re not really related, which means it&#x2019;s time to look at the data.</p>
<h1 id="setting-up-the-destination-writer">Setting up the Destination Writer <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#setting-up-the-destination-writer">&#x1f517;</a></h1>
<p>There&#x2019;s a lot of ways to handle the S3 write, but my application needed something that could potentially talk to multiple storage services. The <a href="https://docs.rs/object_store/latest/object_store/">object_store</a> crate is a good choice here. It&#x2019;s part of the Apache Arrow project so it sees active development, and I found it very easy to use.</p>
<p>Since we&#x2019;re streaming the data, we&#x2019;ll use a multipart upload which removes the need to buffer the data locally. The <code>object_store</code> transparently manages the buffers and metadata around the multipart upload process.</p>
<pre><code class="language-rust"><span class="hljs-keyword">let</span> store = object_store::aws::AmazonS3Builder::new()
  .with_bucket_name(bucket)
  <span class="hljs-comment">// Auth options go here too if you&apos;re using a fixed access key and secret.</span>
  .build();

<span class="hljs-keyword">let</span> (upload_id, <span class="hljs-keyword">mut</span> writer) = operator.put_multipart(image_location).<span class="hljs-keyword">await</span>?;
<span class="hljs-keyword">let</span> upload_result = handle_body(&amp;<span class="hljs-keyword">mut</span> writer, stream).<span class="hljs-keyword">await</span>;

todo!(<span class="hljs-string">&quot;Handle the result&quot;</span>);

<span class="hljs-comment">/// Handle the request body</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle_body</span></span>(
  writer: &amp;<span class="hljs-keyword">mut</span> <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> AsyncWrite + Unpin + <span class="hljs-built_in">Send</span>&gt;,
  <span class="hljs-keyword">mut</span> stream: BodyStream,
) -&gt; <span class="hljs-built_in">Result</span>&lt;(<span class="hljs-built_in">String</span>, ImageInfo), Error&gt; {
  todo!();
}
</code></pre>
<p>The <code>put_multipart</code> function returns an object that implements <a href="https://docs.rs/tokio/latest/tokio/io/trait.AsyncWrite.html"><code>AsyncWrite</code></a>, and also an upload ID. The upload ID can be used to cancel the multipart upload in case of an error.</p>
<p>We&#x2019;ll write a separate <code>handle_body</code> function to do the actual work here, so that we can easily catch any error that occurs and perform the cancellation.</p>
<h1 id="handling-the-data">Handling the Data <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#handling-the-data">&#x1f517;</a></h1>
<p>Now that the writer is ready, we can also set up our other operations &#x2013; calculating the hash and figuring out the image format and dimensions.</p>
<h2 id="accumulating-the-header">Accumulating the header <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#accumulating-the-header">&#x1f517;</a></h2>
<p>I used the <a href="https://docs.rs/imageinfo">imageinfo</a> crate here to examine the image, and it requires just the first 1024 bytes of the file to accomplish this.</p>
<p>There&#x2019;s a good chance that the first chunk of the body will be larger than 1024 bytes, but we can&#x2019;t count on that, so we use a <code>Header</code> object to accumulate data until we have enough.</p>
<p>This is actually the most complicated block of code in this article, but all it&#x2019;s really doing is filling up a buffer and trying not to make more copies than it needs to. I&#x2019;m including this since you might find it useful, but feel free to <a href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#consuming-the-stream">skip to the next section</a> if you don&#x2019;t care about the details here.</p>
<pre><code class="language-rust"><span class="hljs-keyword">const</span> HEADER_CAP: <span class="hljs-built_in">usize</span> = <span class="hljs-number">1024</span>;

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Header</span></span> {
  buf: HeaderBuf,
}

<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">HeaderBuf</span></span> {
  Empty,
  <span class="hljs-built_in">Vec</span>(<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;),
  Ref(Bytes),
}

<span class="hljs-keyword">impl</span> Header {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; Header {
      Header {
          buf: HeaderBuf::Empty,
      }
  }

  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">as_slice</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; &amp;[<span class="hljs-built_in">u8</span>] {
      <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.buf {
          HeaderBuf::<span class="hljs-built_in">Vec</span>(vec) =&gt; vec.as_slice(),
          HeaderBuf::Ref(bytes) =&gt; bytes.as_ref(),
          HeaderBuf::Empty =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">&quot;as_slice on empty header&quot;</span>),
      }
  }


  <span class="hljs-comment">/// See if the buffer is full enough</span>
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">ready</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">bool</span> {
      <span class="hljs-keyword">let</span> len = <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.buf {
          HeaderBuf::<span class="hljs-built_in">Vec</span>(vec) =&gt; vec.len(),
          HeaderBuf::Ref(bytes) =&gt; bytes.len(),
          HeaderBuf::Empty =&gt; <span class="hljs-number">0</span>,
      };

      len &gt;= HEADER_CAP
  }

  <span class="hljs-comment">/// Add more data to the header buffer.</span>
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_chunk</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, bytes: &amp;Bytes) {
      <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.ready() {
          <span class="hljs-keyword">return</span>;
      }

      <span class="hljs-keyword">self</span>.buf = <span class="hljs-keyword">match</span> std::mem::replace(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>.buf, HeaderBuf::Empty) {
          <span class="hljs-comment">// This is the first chunk.</span>
          HeaderBuf::Empty =&gt; HeaderBuf::Ref(bytes.clone()),
          <span class="hljs-comment">// It&apos;s already a Vec, so add an additional chunk to the Vec.</span>
          HeaderBuf::<span class="hljs-built_in">Vec</span>(<span class="hljs-keyword">mut</span> vec) =&gt; {
              <span class="hljs-keyword">let</span> needed = HEADER_CAP - vec.len();
              <span class="hljs-keyword">let</span> actual = needed.min(bytes.len());
              vec.extend(bytes.slice(<span class="hljs-number">0</span>..actual));
              HeaderBuf::<span class="hljs-built_in">Vec</span>(vec)
          }
          HeaderBuf::Ref(first_bytes) =&gt; {
              <span class="hljs-comment">// We had a first chunk of bytes but it wasn&apos;t big enough, so</span>
              <span class="hljs-comment">// create a new Vec from the first chunk...</span>
              <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> vec = <span class="hljs-built_in">Vec</span>::with_capacity(HEADER_CAP);
              vec.extend(first_bytes.iter().take(HEADER_CAP));

              <span class="hljs-comment">// And then add the current chunk</span>
              <span class="hljs-keyword">let</span> needed = HEADER_CAP - vec.len();
              <span class="hljs-keyword">let</span> actual = needed.min(bytes.len());
              vec.extend(bytes.slice(<span class="hljs-number">0</span>..actual));

              HeaderBuf::<span class="hljs-built_in">Vec</span>(vec)
          }
      };
  }

  <span class="hljs-comment">/// Try to get the image information.</span>
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">parse</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;ImageInfo, ImageInfoError&gt; {
      <span class="hljs-built_in">assert!</span>(<span class="hljs-keyword">self</span>.ready());
      <span class="hljs-keyword">let</span> bytes = <span class="hljs-keyword">self</span>.as_slice();
      ImageInfo::from_raw_data(bytes)
  }
}
</code></pre>
<h2 id="consuming-the-stream">Consuming the Stream <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#consuming-the-stream">&#x1f517;</a></h2>
<p>With our header accumulation ready, we can fill in our <code>handle_body</code> function and actually consume the stream. First, we&#x2019;ll initialize our other data handling. I used <a href="https://docs.rs/blake3">blake3</a> for the hash and the aforementioned <a href="https://docs.rs/imageinfo">imageinfo</a> for the image processing.</p>
<pre><code class="language-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> hasher = blake3::Hasher::new();

<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> header = Header::new();
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> info: <span class="hljs-built_in">Option</span>&lt;ImageInfo&gt; = <span class="hljs-literal">None</span>;
</code></pre>
<p>The <code>Stream</code> abstraction provides a few ways to consume the data. For our purposes, a <code>while</code> loop is easiest. Each chunk then goes through the hasher and the image header object, and finally out to the writer.</p>
<pre><code class="language-rust"><span class="hljs-keyword">while</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(chunk) = stream.try_next().<span class="hljs-keyword">await</span>? {
  hasher.update(&amp;chunk);

  <span class="hljs-keyword">if</span> info.is_none() {
    header.add_chunk(&amp;chunk);
    <span class="hljs-keyword">if</span> header.ready() {
      <span class="hljs-keyword">let</span> i = header.parse()?;
      info = <span class="hljs-literal">Some</span>(i);
    }
  }

  writer.write_all(&amp;chunk).<span class="hljs-keyword">await</span>?;
}
</code></pre>
<h1 id="finishing-up">Finishing up <a class="header-anchor" href="https://imfeld.dev/writing/process_streaming_uploads_with_axum#finishing-up">&#x1f517;</a></h1>
<p>Once the loop is done, we just have to clean things up. First we&#x2019;ll look at the results of our data processing tasks and return from <code>handle_body</code>.</p>
<pre><code class="language-rust"><span class="hljs-comment">// Unwrap the `Option`, returning an error if we never saw enough data to fill the buffer.</span>
<span class="hljs-keyword">let</span> info = info
  .ok_or(Error::ImageHeaderDecode(ImageInfoError::UnrecognizedFormat))?;

<span class="hljs-comment">// Get the calculated hash.</span>
<span class="hljs-keyword">let</span> hash = hasher.finalize();
<span class="hljs-keyword">let</span> hash_hex = hash.to_string();

<span class="hljs-literal">Ok</span>((hash_hex, info))
</code></pre>
<p>Finally, we update our original call to <code>handle_body</code> to examine its result.</p>
<pre><code class="language-rust"><span class="hljs-keyword">let</span> upload_result = handle_body(&amp;<span class="hljs-keyword">mut</span> writer, stream).<span class="hljs-keyword">await</span>;
<span class="hljs-keyword">let</span> (hash_hex, info) = <span class="hljs-keyword">match</span> upload_result {
  <span class="hljs-literal">Ok</span>(data) =&gt; {
    writer.shutdown().<span class="hljs-keyword">await</span>?;
    data
  }
  <span class="hljs-literal">Err</span>(e) =&gt; {
    store
      .abort_multipart(&amp;image_location, &amp;upload_id)
      .<span class="hljs-keyword">await</span>
      .ok();
    <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(e);
  }
};
</code></pre>
<p>If everything succeeded, we call <a href="https://docs.rs/tokio/latest/tokio/io/trait.AsyncWriteExt.html#method.shutdown">shutdown</a>, which closes the stream and ensures that all the data has been written. <code>object_store</code> requires that you explicitly shutdown the stream, since it also uses this opportunity to tell S3 that the upload is complete.</p>
<p>If something failed, then we just tell the store to abort the upload, which lets S3 know that it should purge the data uploaded so far.</p>
<p>And then we&#x2019;re done! My <a href="https://github.com/dimfeld/pic-store/blob/f76f4c903f22aafe62452060de65a1f03df360dc/api/src/routes/image/upload.rs">actual application code</a> goes on to save the resulting metadata to the database and set up some background jobs to convert the image to other formats.</p>
<p>Handling streaming request bodies can feel like a daunting task. But I hope this has demonstrated how the Rust ecosystem provides great tools for making this an ergonomic and relatively painless process.</p>
]]></description><link>https://imfeld.dev/writing/process_streaming_uploads_with_axum</link><guid isPermaLink="false">14bc93bfbe619e254b22c81fed7dbde0fb7e3c73df34b535b264a1c66a477894</guid><category><![CDATA[Rust]]></category><pubDate>Sat, 26 Nov 2022 00:00:00 GMT</pubDate></item><item><title><![CDATA[Setting up Let's Encrypt with NGINX in Docker]]></title><description><![CDATA[<p>Tags: LetsEncrypt, nginx</p><p>I was setting up Let&#x2019;s Encrypt today for the first time, and it&#x2019;s impressive how easy they&#x2019;ve made this process that used to be a big hassle. Our NGINX configuration at work is too complicated for certbot&#x2019;s bulit-in configuration management, and so we write the configuration ourselves.</p>
<h1 id="nginx-configuration">NGINX Configuration <a class="header-anchor" href="https://imfeld.dev/writing/letsencrypt_nginx_manual_setup#nginx-configuration">&#x1f517;</a></h1>
<p>First, you need to respond to the ACME request on non-secure HTTP. This configuration does that while redirecting everything else to HTTPS.</p>
<pre><code class="language-nginx"><span class="hljs-section">server</span> {
  <span class="hljs-attribute">listen</span> <span class="hljs-number">80</span>;
  <span class="hljs-attribute">server_name</span>   _;
  <span class="hljs-comment"># The directory that certbot will use to respond to the ACME challenge</span>
  <span class="hljs-attribute">root</span> /var/www;

  <span class="hljs-attribute">location</span> /.well-known/acme-challenge {
    <span class="hljs-attribute">try_files</span> &#x24;request_uri =<span class="hljs-number">404</span>;
  }

  <span class="hljs-attribute">location</span> / {
    <span class="hljs-attribute">rewrite</span><span class="hljs-regexp"> ^</span> https://&#x24;host&#x24;request_uri? <span class="hljs-literal">permanent</span>;
  }
}
</code></pre>
<p>After that, you can set up your server as normal, but one problem remains&#x2026;</p>
<h1 id="ssl-certificate-bootstrapping">SSL Certificate Bootstrapping <a class="header-anchor" href="https://imfeld.dev/writing/letsencrypt_nginx_manual_setup#ssl-certificate-bootstrapping">&#x1f517;</a></h1>
<p>You don&#x2019;t have the SSL certificates yet, and NGINX won&#x2019;t start if they aren&#x2019;t present.</p>
<p>This would present a chicken-and-egg problem, but we can supply a fake chicken in the form of a self-signed certificate.</p>
<p>Browsers will reject this, but that&#x2019;s ok. All we really need to do is get NGINX to start so it can serve the port 80 ACME requests, then certbot will be able to function.</p>
<aside class="note"><p>You could also just comment out the <code>server</code> block that needs the SSL certificate, but that is more of a hassle IMO.</p>
</aside><p>Since I always forget how to generate a simple self-signed SSL cert, here&#x2019;s one method:</p>
<pre><code class="language-sh">openssl req -nodes -batch -x509 -newkey rsa:2048 \
  -keyout privkey.pem -out fullchain.pem -days 360
</code></pre>
<p>Then you can copy the resulting files into the proper location in <code>/etc/letsencrypt/live/&#x24;CERTNAME/</code>, and start NGINX.</p>
<p>Now, <code>certbot</code> doesn&#x2019;t really like if there&#x2019;s some fake self-signed certificate in the directory it&#x2019;s expecting to use, so once NGINX is started you&#x2019;ll want to delete the files you just created.</p>
<pre><code class="language-sh">sudo rm -i /etc/letsencrypt/live/<span class="hljs-variable">&#x24;CERTNAME</span>/*.pem
sudo rmdir /etc/letsencrypt/live/<span class="hljs-variable">&#x24;CERTNAME</span>
</code></pre>
<p>Finally, you can run <code>certbot certonly --nginx --cert-name &#x24;CERTNAME -d &#x24;DOMAIN</code> to generate the certificate.</p>
<h1 id="nginx-inside-docker">NGINX inside Docker <a class="header-anchor" href="https://imfeld.dev/writing/letsencrypt_nginx_manual_setup#nginx-inside-docker">&#x1f517;</a></h1>
<p>If you&#x2019;re running NGINX inside a Docker container, you should use certbot&#x2019;s <code>webroot</code> method instead of the <code>nginx</code> method.</p>
<pre><code class="language-sh">certbot certonly \
  --webroot -w /var/www \
  --key-type ecdsa \
  --cert-name <span class="hljs-variable">&#x24;CERTNAME</span> \
  -d <span class="hljs-variable">&#x24;DOMAIN</span>
</code></pre>
<p>In this case you&#x2019;ll also need to tell the NGINX in the docker container to reload, and certbot makes this easy with post-renewal hooks.</p>
<p>Create the file <code>/etc/letsencrypt/renewal-hooks/post/nginx-docker-reload.sh</code> with these contents:</p>
<pre><code class="language-sh"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-built_in">set</span> -e
docker <span class="hljs-built_in">exec</span> -it nginx nginx -s reload
<span class="hljs-built_in">echo</span> Reloaded nginx!
</code></pre>
<p>You can test this script by running <code>sudo certbot renew --dry-run</code>.</p>
<p>If you need to copy the SSL certificates from <code>/etc/letsencrypt/live/&#x24;CERTNAME</code> to somewhere else that the Docker container can
see, you can also do it in that hook.</p>
<h1 id="alternative-methods">Alternative Methods <a class="header-anchor" href="https://imfeld.dev/writing/letsencrypt_nginx_manual_setup#alternative-methods">&#x1f517;</a></h1>
<p>I should note that ACME/LetsEncrypt/certbot can also work via DNS records. For this particular case that was not an option, but it could make things easier, and certbot has a number of plugins to interface with various DNS providers.</p>
]]></description><link>https://imfeld.dev/writing/letsencrypt_nginx_manual_setup</link><guid isPermaLink="false">179d6897a9ab363f0ca6b53f1cf024a5bf05b8c356b79db9d7378f0494064f27</guid><category><![CDATA[LetsEncrypt]]></category><category><![CDATA[nginx]]></category><pubDate>Thu, 17 Nov 2022 00:00:00 GMT</pubDate></item><item><title><![CDATA[Starting with Solana, Part 4 - A Todo List with Rewards]]></title><description><![CDATA[<p>Tags: Solana, web3</p><p>In <a href="https://imfeld.dev/writing/starting_with_solana_part03">part 3</a> we looked at testing and deploying our Solana program. I was going to put
together an article about using Svelte with Solana for part 4, but that will wait for part 5 instead while we focus on
making a more interesting Solana program &#x2013; a todo list where anyone can add an item and attach a reward for
completion.</p>
<h1 id="program-structure">Program Structure <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#program-structure">&#x1f517;</a></h1>
<p>The program workflow will look something like this:</p>
<ol>
<li>Someone creates a list.</li>
<li>A second person adds an item to the list.</li>
<li>When the task is done, the list owner marks it finished.</li>
<li>The person who added the item also marks it finished.</li>
<li>The token balance on the item is transferred to the list owner.</li>
</ol>
<p>Our program will have four instructions to manage a list and its items:</p>
<ul>
<li>NewList to make a new todo list.</li>
<li>Add to add an item to a list.</li>
<li>Cancel to delete an item, unfinished, and return the reward to the item creator.</li>
<li>Finish to remove an item and transfer the reward when both the list&#x2019;s owner and the item&#x2019;s creator agree it&#x2019;s finished.</li>
</ul>
<aside class="warn"><p>The Finish instruction&#x2019;s escrow mechanism is intentionally simple to avoid overloading this post with new information.
Real programs would want to use something more secure. <a href="https://paulx.dev/blog/2021/01/14/programming-on-solana-an-introduction/">paulx&#x2019;s blog</a>
has a thorough explanation of how to do it right.</p>
</aside><h2 id="program-derived-addresses">Program-Derived Addresses <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#program-derived-addresses">&#x1f517;</a></h2>
<p>With this program, each todo list is a Solana account, and each item in the list is also an account. Anyone can add an
item with an attached token balance, and when the list owner and the item creator both mark it finished, the item&#x2019;s balance transfers
to the list owner&#x2019;s account as a reward.</p>
<p>Normally, to use such a list you would need to know two public keys, one for the list&#x2019;s owner and another for the list
itself. But Solana lets us use <a href="https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses">program derived
addresses</a>
(PDAs) as a
better solution. These addresses are calculated from a hash of the program ID and various &#x201c;seed&#x201d; values which can include
public keys or other strings of bytes, up to 32 bytes each.</p>
<aside class="note"><p>Don&#x2019;t worry if this seems complex right now. PDAs are a big part of Solana, but once we use them below it will make more
sense.</p>
</aside><p>Solana also requires that program derived addresses can not have an associated private key, and it enforces this by
checking that that they are not valid values on the <a href="https://en.wikipedia.org/wiki/EdDSA">ed25519 elliptical curve</a> used
to generate keys. After calculating the hash above, a &#x201c;bump&#x201d; value is added to the hash until a value is found that is
not on the curve. This bump starts at 255 and is decremented until it finds a value not on the curve, and that
becomes the actual address.</p>
<p>It&#x2019;s not guaranteed that this &#x201c;check and decrement&#x201d; bump process will generate a valid PDA, but the chances are very high, and importantly
it is deterministic &#x2014; given a program ID and seeds, the same PDA will always be derived. And since the
address is not a real public key, it&#x2019;s guaranteed that the program from which the PDA came is the only thing that can
generate a signed transaction from it.</p>
<p>Programs generate signed transactions for a PDA by attaching the seeds and bump value
to an invocation that uses it. The Solana runtime can then use this information to verify that the PDA actually
belongs to the program.</p>
<h2 id="returning-errors">Returning Errors <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#returning-errors">&#x1f517;</a></h2>
<p>The program may need to return some custom errors when things go wrong. Anchor has an <code>#[error]</code> macro
to allow this, and we can place it on an enum to create the error values and associated error messages.</p>
<p>The error functionality here is not very expressive; the Solana program itself can only return a number, and so
the error messages themselves are stored in the generated Anchor IDL file and translated by the Anchor runtime. This means that
your error messages can only be static strings, without any associated data or other formatting capability.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[error]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">TodoListError</span></span> {
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;This list is full&quot;</span>)]</span>
    ListFull,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Bounty must be enough to mark account rent-exempt&quot;</span>)]</span>
    BountyTooSmall,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Only the list owner or item creator may cancel an item&quot;</span>)]</span>
    CancelPermissions,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Only the list owner or item creator may finish an item&quot;</span>)]</span>
    FinishPermissions,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Item does not belong to this todo list&quot;</span>)]</span>
    ItemNotFound,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Specified list owner does not match the pubkey in the list&quot;</span>)]</span>
    WrongListOwner,
    <span class="hljs-meta">#[msg(<span class="hljs-meta-string">&quot;Specified item creator does not match the pubkey in the item&quot;</span>)]</span>
    WrongItemCreator,
}
</code></pre>
<h1 id="test-infrastructure">Test Infrastructure <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#test-infrastructure">&#x1f517;</a></h1>
<p>Of course, we also need tests for all this. I put together a few utility functions to perform
common operations which you may also find useful. Feel free to copy them into your own tests if you&#x2019;d like.</p>
<p>First, we define our imports and set up the Anchor provider and program.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> anchor = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;@project-serum/anchor&apos;</span>);
<span class="hljs-keyword">const</span> BN = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;bn.js&apos;</span>);
<span class="hljs-keyword">const</span> expect = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;chai&apos;</span>).expect;
<span class="hljs-keyword">const</span> { SystemProgram, LAMPORTS_PER_SOL } = anchor.web3;

<span class="hljs-keyword">const</span> provider = anchor.Provider.env();
anchor.setProvider(provider);
<span class="hljs-keyword">const</span> mainProgram = anchor.workspace.Todo;
</code></pre>
<p>Our tests need to check that the program is transferring balances around properly, so
the <code>getAccountBalance</code> function handles that. User accounts also pay small transaction
fees, so the <code>expectBalance</code> function wraps the proper call to check a balance with a bit of slack
to account for that. Each of these functions is small, but together they are called about 50 times
so the savings and convenience adds up.</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAccountBalance</span>(<span class="hljs-params">pubkey</span>) </span>{
  <span class="hljs-keyword">let</span> account = <span class="hljs-keyword">await</span> provider.connection.getAccountInfo(pubkey);
  <span class="hljs-keyword">return</span> account?.lamports ?? <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">expectBalance</span>(<span class="hljs-params">actual, expected, message, slack = <span class="hljs-number">20000</span></span>) </span>{
  expect(actual, message).within(expected - slack, expected + slack);
}
</code></pre>
<p>Most of the tests simulate multiple users interacting with a contract. For this we have the
<code>createUser</code> function which makes a user account with an airdropped balance and an anchor <code>Provider</code>
for the user. The <code>createUsers</code> function makes multiple users in parallel to speed up tests a bit.</p>
<p>Each Anchor <code>Program</code> instance is linked to a particular <code>Provider</code>, which is in turn linked to a particular user and wallet.
To make it easier to call a program from various users, the <code>programForUser</code> function creates a new <code>Program</code> instance,
based on <code>mainProgram</code> but with the given user&#x2019;s <code>Provider</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">airdropBalance</span>) </span>{
  airdropBalance = airdropBalance ?? <span class="hljs-number">10</span> * LAMPORTS_PER_SOL;
  <span class="hljs-keyword">let</span> user = anchor.web3.Keypair.generate();
  <span class="hljs-keyword">let</span> sig = <span class="hljs-keyword">await</span> provider.connection.requestAirdrop(user.publicKey, airdropBalance);
  <span class="hljs-keyword">await</span> provider.connection.confirmTransaction(sig);

  <span class="hljs-keyword">let</span> wallet = <span class="hljs-keyword">new</span> anchor.Wallet(user);
  <span class="hljs-keyword">let</span> userProvider = <span class="hljs-keyword">new</span> anchor.Provider(provider.connection, wallet, provider.opts);

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">key</span>: user,
    wallet,
    <span class="hljs-attr">provider</span>: userProvider,
  };
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUsers</span>(<span class="hljs-params">numUsers</span>) </span>{
  <span class="hljs-keyword">let</span> promises = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numUsers; i++) {
    promises.push(createUser());
  }

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.all(promises);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">programForUser</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> anchor.Program(mainProgram.idl, mainProgram.programId, user.provider);
}
</code></pre>
<p>The full test file can be found on this <a href="https://github.com/dimfeld/starting-with-solana/blob/master/tests/todo.js">Github
repository</a> and
I&#x2019;ll walk through the parts relevant to specific instructions in later sections.</p>
<h1 id="creating-a-list">Creating a List <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#creating-a-list">&#x1f517;</a></h1>
<p>Anyone can run the <code>NewList</code> instruction to create a new todo list. The <code>TodoList</code> account structure holds all the
information for a list, including the list&#x2019;s owner and name, how many items it can hold, and references to the accounts
for each item in the list. Finally it also holds the bump value that was used to calculate its PDA, which feeds into
Anchor&#x2019;s autogenerated verification processes.</p>
<p>The address for the todo list is calculated from a combination of the owner&#x2019;s pubkey and the name of the list, so a user
could also create different lists with different names.</p>
<h2 id="todolist-data-structure">TodoList Data Structure <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#todolist-data-structure">&#x1f517;</a></h2>
<pre><code class="language-rust"><span class="hljs-meta">#[account]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TodoList</span></span> {
    <span class="hljs-keyword">pub</span> list_owner: Pubkey,
    <span class="hljs-keyword">pub</span> bump: <span class="hljs-built_in">u8</span>,
    <span class="hljs-keyword">pub</span> capacity: <span class="hljs-built_in">u16</span>,
    <span class="hljs-keyword">pub</span> name: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> lines: <span class="hljs-built_in">Vec</span>&lt;Pubkey&gt;,
}
</code></pre>
<p>We also add a function to calculate the space needed for a TodoList structure. We could do this all
within Anchor&#x2019;s <code>account</code> macro but this is much easier to manage. Remember that accounts that don&#x2019;t have any
dynamically-sized data (Strings or Vecs) can just <code>#[derive(Default)]</code> to have Anchor automatically calculate the
size.</p>
<pre><code class="language-rust"><span class="hljs-keyword">impl</span> TodoList {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">space</span></span>(name: &amp;<span class="hljs-built_in">str</span>, capacity: <span class="hljs-built_in">u16</span>) -&gt; <span class="hljs-built_in">usize</span> {
        <span class="hljs-comment">// discriminator + owner pubkey + bump + capacity</span>
        <span class="hljs-number">8</span> + <span class="hljs-number">32</span> + <span class="hljs-number">1</span> + <span class="hljs-number">2</span> +
            <span class="hljs-comment">// name string</span>
            <span class="hljs-number">4</span> + name.len() +
            <span class="hljs-comment">// vec of item pubkeys</span>
            <span class="hljs-number">4</span> + (capacity <span class="hljs-keyword">as</span> <span class="hljs-built_in">usize</span>) * std::mem::size_of::&lt;Pubkey&gt;()
    }
}
</code></pre>
<h2 id="newlist-instruction-accounts">NewList Instruction Accounts <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#newlist-instruction-accounts">&#x1f517;</a></h2>
<p>There&#x2019;s a lot going on in the <code>#[account]</code> macro for the NewList instruction so we&#x2019;ll go over them one by one.</p>
<pre><code class="language-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">name_seed</span></span>(name: &amp;<span class="hljs-built_in">str</span>) -&gt; &amp;[<span class="hljs-built_in">u8</span>] {
    <span class="hljs-keyword">let</span> b = name.as_bytes();
    <span class="hljs-keyword">if</span> b.len() &gt; <span class="hljs-number">32</span> { &amp;b[<span class="hljs-number">0</span>..<span class="hljs-number">32</span>] } <span class="hljs-keyword">else</span> { b }
}

<span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-meta">#[instruction(name: String, capacity: u16, list_bump: u8)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">NewList</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(init, payer=user,
      space=TodoList::space(&amp;name, capacity),
      seeds=[
        b<span class="hljs-meta-string">&quot;todolist&quot;</span>,
        user.to_account_info().key.as_ref(),
        name_seed(&amp;name)
      ]</span>,
      bump=list_bump)]
    <span class="hljs-keyword">pub</span> list: Account&lt;<span class="hljs-symbol">&apos;info</span>, TodoList&gt;,
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> system_program: Program&lt;<span class="hljs-symbol">&apos;info</span>, System&gt;,
}
</code></pre>
<p>The <code>#[instruction]</code> macro tells Anchor to deserialize the instruction arguments inside the autogenerated code so that
the rest of the <code>#[account]</code> macros here can use their values. Note that Anchor doesn&#x2019;t verify that the
arguments listed in <code>#[instruction]</code> actually match the arguments in the implementation function.</p>
<ul>
<li><code>init</code> and <code>payer</code> are the same as before &#x2013; they tell Anchor to create the specified account and who should
pay for it.</li>
<li><code>space</code> just calls <code>TodoList::space</code>, which we wrote above.</li>
<li><code>seeds</code> tells Anchor that this account is a PDA and lists the seed values which are hashed to calculate it. Anchor
generates code to rederive the PDA from the seeds and ensure that they match the passed-in value.
Each seed value can be no more than 32 bytes, so the <code>name_seed</code> function helps with that.</li>
<li><code>bump</code> is also used by Anchor&#x2019;s PDA verification to avoid using a &#x201c;check and decrement&#x201d; loop to find the right bump value,
which can be costly when operating under Solana&#x2019;s strict
computation budget. In most cases the caller will run the loop to find a proper bump value, since it tends
to be operating in an environment such as a web browser where an extra <code>for</code> loop doesn&#x2019;t matter much, and in many
cases it would have already had the bump value on hand.</li>
</ul>
<h2 id="newlist-implementation">NewList Implementation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#newlist-implementation">&#x1f517;</a></h2>
<p>Finally, we write the actual implementation. Not much to do here; we just copy the instruction&#x2019;s arguments
into the TodoList data structure.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[program]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-keyword">mod</span> todo {
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new_list</span></span>(
        ctx: Context&lt;NewList&gt;,
        name: <span class="hljs-built_in">String</span>,
        capacity: <span class="hljs-built_in">u16</span>,
        account_bump: <span class="hljs-built_in">u8</span>,
    ) -&gt; ProgramResult {
        <span class="hljs-comment">// Create a new account</span>
        <span class="hljs-keyword">let</span> list = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.list;
        list.list_owner = *ctx.accounts.user.to_account_info().key;
        list.bump = account_bump;
        list.name = name;
        list.capacity = capacity;
        <span class="hljs-literal">Ok</span>(())
    }
}
</code></pre>
<h2 id="testing-list-creation">Testing List Creation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#testing-list-creation">&#x1f517;</a></h2>
<p>Every test needs to create a list, and the <code>createList</code> function makes that reusable.</p>
<p>The list account is a PDA, so the first step is to calculate its value. We pass the program ID and the seed values to <code>findProgramAddress</code>, and it
returns the calculated PDA and the bump value used to calculate it. From there, we can call <code>newList</code>.
Finally, the function fetches the data from the initialized list and returns it.</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createList</span>(<span class="hljs-params">owner, name, capacity = <span class="hljs-number">16</span></span>) </span>{
  <span class="hljs-keyword">const</span> [listAccount, bump] = <span class="hljs-keyword">await</span> anchor.web3.PublicKey.findProgramAddress(
    [<span class="hljs-string">&apos;todolist&apos;</span>, owner.key.publicKey.toBytes(), name.slice(<span class="hljs-number">0</span>, <span class="hljs-number">32</span>)],
    mainProgram.programId
  );

  <span class="hljs-keyword">let</span> program = programForUser(owner);
  <span class="hljs-keyword">await</span> program.rpc.newList(name, capacity, bump, {
    <span class="hljs-attr">accounts</span>: {
      <span class="hljs-attr">list</span>: listAccount,
      <span class="hljs-attr">user</span>: owner.key.publicKey,
      <span class="hljs-attr">systemProgram</span>: SystemProgram.programId,
    },
  });

  <span class="hljs-keyword">let</span> list = <span class="hljs-keyword">await</span> program.account.todoList.fetch(listAccount);
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">publicKey</span>: listAccount, <span class="hljs-attr">data</span>: list };
}
</code></pre>
<p>With that out of the way, the actual test is small. We create the user, create the list, and then
check that all the fields of the empty list look like what we expect.</p>
<pre><code class="language-js">describe(<span class="hljs-string">&apos;new list&apos;</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">&apos;creates a list&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> owner = <span class="hljs-keyword">await</span> createUser();
    <span class="hljs-keyword">let</span> list = <span class="hljs-keyword">await</span> createList(owner, <span class="hljs-string">&apos;A list&apos;</span>);

    expect(list.data.listOwner.toString(), <span class="hljs-string">&apos;List owner is set&apos;</span>).equals(owner.key.publicKey.toString());
    expect(list.data.name, <span class="hljs-string">&apos;List name is set&apos;</span>).equals(<span class="hljs-string">&apos;A list&apos;</span>);
    expect(list.data.lines.length, <span class="hljs-string">&apos;List has no items&apos;</span>).equals(<span class="hljs-number">0</span>);
  });
});
</code></pre>
<h1 id="adding-an-item">Adding an Item <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#adding-an-item">&#x1f517;</a></h1>
<p>Anyone can call the <code>Add</code> instruction against any todo list. The arguments are the item name and the number of tokens for the item bounty. The account&#x2019;s
pubkey will also be added to the main todo list account.</p>
<h2 id="listitem-data-structure">ListItem Data Structure <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#listitem-data-structure">&#x1f517;</a></h2>
<p>Each list item keeps track of who created it and who has marked it finished. The reward amount is just the balance on
the account, so we don&#x2019;t need to explicitly track it here. As before, there&#x2019;s a <code>space</code> function to better colocate
the space calculation with the actual list of fields.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[account]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ListItem</span></span> {
    <span class="hljs-keyword">pub</span> creator: Pubkey,
    <span class="hljs-keyword">pub</span> creator_finished: <span class="hljs-built_in">bool</span>,
    <span class="hljs-keyword">pub</span> list_owner_finished: <span class="hljs-built_in">bool</span>,
    <span class="hljs-keyword">pub</span> name: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> ListItem {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">space</span></span>(name: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">usize</span> {
        <span class="hljs-comment">// discriminator + creator pubkey + 2 bools + name string</span>
        <span class="hljs-number">8</span> + <span class="hljs-number">32</span> + <span class="hljs-number">1</span> + <span class="hljs-number">1</span> + <span class="hljs-number">4</span> + name.len()
    }
}
</code></pre>
<h2 id="add-accounts">Add Accounts <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#add-accounts">&#x1f517;</a></h2>
<p>Once again, the <code>list</code> account includes the necessary <code>seeds</code> and <code>bump</code> to verify the PDA. We also
pass the list owner&#x2019;s pubkey and the list name to assist in verifying the PDA address. The <code>item</code>
account initializes the new list with enough space to hold the name and other data.</p>
<p>Here we also see Anchor&#x2019;s <code>@</code> macro syntax. This can be used in a constraint to tell it
to return a particular error instead of the default error for that constraint type.</p>
<p>Another new thing here is the way we define the <code>list_owner</code> field. Since we don&#x2019;t want to read the data
from the <code>list_owner</code> account, we can just use the <code>AccountInfo</code> type directly in the structure. Here
we just need it to assist in the PDA verification.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-meta">#[instruction(list_name: String, item_name: String, bounty: u64)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Add</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(
      mut,
      has_one=list_owner @ TodoListError::WrongListOwner,
      seeds=[
        b<span class="hljs-meta-string">&quot;todolist&quot;</span>,
        list_owner.to_account_info().key.as_ref(),
        name_seed(&amp;list_name)
      ]</span>,
      bump=list.bump)]
    <span class="hljs-keyword">pub</span> list: Account&lt;<span class="hljs-symbol">&apos;info</span>, TodoList&gt;,
    <span class="hljs-keyword">pub</span> list_owner: AccountInfo&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-comment">// 8 byte discriminator,</span>
    <span class="hljs-meta">#[account(init, payer=user, space=ListItem::space(&amp;item_name))]</span>
    <span class="hljs-keyword">pub</span> item: Account&lt;<span class="hljs-symbol">&apos;info</span>, ListItem&gt;,
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> system_program: Program&lt;<span class="hljs-symbol">&apos;info</span>, System&gt;,
}
</code></pre>
<h2 id="add-implementation">Add Implementation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#add-implementation">&#x1f517;</a></h2>
<p>The add function both adds the new item to the list and attaches the reward amount to the item.</p>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(
    ctx: Context&lt;Add&gt;,
    _list_name: <span class="hljs-built_in">String</span>,
    item_name: <span class="hljs-built_in">String</span>,
    bounty: <span class="hljs-built_in">u64</span>,
) -&gt; ProgramResult {
    <span class="hljs-keyword">let</span> user = &amp;ctx.accounts.user;
    <span class="hljs-keyword">let</span> list = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.list;
    <span class="hljs-keyword">let</span> item = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.item;

    <span class="hljs-comment">// Check that the list isn&apos;t already full.</span>
    <span class="hljs-keyword">if</span> list.lines.len() &gt;= list.capacity <span class="hljs-keyword">as</span> <span class="hljs-built_in">usize</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(TodoListError::ListFull.into());
    }

    list.lines.push(*item.to_account_info().key);
    item.name = item_name;
    item.creator = *user.to_account_info().key;

    <span class="hljs-comment">// Move the bounty to the account. We account for the rent amount</span>
    <span class="hljs-comment">// that Anchor&apos;s init already transferred into the account.</span>
    <span class="hljs-keyword">let</span> account_lamports = **item.to_account_info().lamports.borrow();
    <span class="hljs-keyword">let</span> transfer_amount = bounty
        .checked_sub(account_lamports)
        .ok_or(TodoListError::BountyTooSmall)?;

    <span class="hljs-keyword">if</span> transfer_amount &gt; <span class="hljs-number">0</span> {
        invoke(
            &amp;transfer(
                user.to_account_info().key,
                item.to_account_info().key,
                transfer_amount,
            ),
            &amp;[
                user.to_account_info(),
                item.to_account_info(),
                ctx.accounts.system_program.to_account_info(),
            ],
        )?;
    }

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>Anchor initializes an account with enough lamports to mark the account as rent-exempt, so we calculate
how many more lamports should be transferred to equal the total reward amount, and
<a href="https://docs.rs/solana-sdk/1.8.2/solana_sdk/program/fn.invoke.html"><code>invoke</code></a> the
<a href="https://docs.rs/solana-sdk/1.8.2/solana_sdk/system_instruction/fn.transfer.html"><code>transfer</code></a>
instruction on the system program to actually move the balance onto the item&#x2019;s account.</p>
<h2 id="testing-item-addition">Testing Item Addition <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#testing-item-addition">&#x1f517;</a></h2>
<p>Once again, we&#x2019;ll create a utility function to add items to a list. You could use a PDA here for the item account, but
we don&#x2019;t bother since the keys are stored in the list account anyway. This <code>addItem</code> function is similar to <code>newList</code> &#x2013; we
call the instruction to add the item to the list and then fetch the account data for both the list and the item.</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addItem</span>(<span class="hljs-params">{ list, user, name, bounty }</span>) </span>{
  <span class="hljs-keyword">const</span> itemAccount = anchor.web3.Keypair.generate();
  <span class="hljs-keyword">let</span> program = programForUser(user);
  <span class="hljs-keyword">await</span> program.rpc.add(list.data.name, name, <span class="hljs-keyword">new</span> BN(bounty), {
    <span class="hljs-attr">accounts</span>: {
      <span class="hljs-attr">list</span>: list.publicKey,
      <span class="hljs-attr">listOwner</span>: list.data.listOwner,
      <span class="hljs-attr">item</span>: itemAccount.publicKey,
      <span class="hljs-attr">user</span>: user.key.publicKey,
      <span class="hljs-attr">systemProgram</span>: SystemProgram.programId,
    },
    <span class="hljs-attr">signers</span>: [user.key, itemAccount],
  });

  <span class="hljs-keyword">let</span> [listData, itemData] = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
    program.account.todoList.fetch(list.publicKey),
    program.account.listItem.fetch(itemAccount.publicKey),
  ]);

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">list</span>: {
      <span class="hljs-attr">publicKey</span>: list.publicKey,
      <span class="hljs-attr">data</span>: listData,
    },
    <span class="hljs-attr">item</span>: {
      <span class="hljs-attr">publicKey</span>: itemAccount.publicKey,
      <span class="hljs-attr">data</span>: itemData,
    },
  };
}
</code></pre>
<p>So first, a test to check that adding items actually works.</p>
<pre><code class="language-js">describe(<span class="hljs-string">&apos;add&apos;</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">&apos;Anyone can add an item to a list&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> [owner, adder] = <span class="hljs-keyword">await</span> createUsers(<span class="hljs-number">2</span>);

    <span class="hljs-keyword">const</span> adderStartingBalance = <span class="hljs-keyword">await</span> getAccountBalance(adder.key.publicKey);
    <span class="hljs-keyword">const</span> list = <span class="hljs-keyword">await</span> createList(owner, <span class="hljs-string">&apos;list&apos;</span>);
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> addItem({
      list,
      <span class="hljs-attr">user</span>: adder,
      <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;Do something&apos;</span>,
      <span class="hljs-attr">bounty</span>: <span class="hljs-number">1</span> * LAMPORTS_PER_SOL,
    });

    expect(result.list.data.lines, <span class="hljs-string">&apos;Item is added&apos;</span>).deep.equals([result.item.publicKey]);
    expect(result.item.data.creator.toString(), <span class="hljs-string">&apos;Item marked with creator&apos;</span>).equals(adder.key.publicKey.toString());
    expect(result.item.data.creatorFinished, <span class="hljs-string">&apos;creator_finished is false&apos;</span>).equals(<span class="hljs-literal">false</span>);
    expect(result.item.data.listOwnerFinished, <span class="hljs-string">&apos;list_owner_finished is false&apos;</span>).equals(<span class="hljs-literal">false</span>);
    expect(result.item.data.name, <span class="hljs-string">&apos;Name is set&apos;</span>).equals(<span class="hljs-string">&apos;Do something&apos;</span>);
    expect(<span class="hljs-keyword">await</span> getAccountBalance(result.item.publicKey), <span class="hljs-string">&apos;List account balance&apos;</span>).equals(<span class="hljs-number">1</span> * LAMPORTS_PER_SOL);

    <span class="hljs-keyword">let</span> adderNewBalance = <span class="hljs-keyword">await</span> getAccountBalance(adder.key.publicKey);
    expectBalance(
      adderStartingBalance - adderNewBalance,
      LAMPORTS_PER_SOL,
      <span class="hljs-string">&apos;Number of lamports removed from adder is equal to bounty&apos;</span>
    );

    <span class="hljs-comment">// Test that another add works</span>
    <span class="hljs-keyword">const</span> again = <span class="hljs-keyword">await</span> addItem({
      list,
      <span class="hljs-attr">user</span>: adder,
      <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;Another item&apos;</span>,
      <span class="hljs-attr">bounty</span>: <span class="hljs-number">1</span> * LAMPORTS_PER_SOL,
    });
    expect(again.list.data.lines, <span class="hljs-string">&apos;Item is added&apos;</span>).deep.equals([result.item.publicKey, again.item.publicKey]);
  });
});
</code></pre>
<p>We should also test that any error conditions are properly checked. This test
creates a list, fills it to capacity, and then checks that additional add operations fail.</p>
<pre><code class="language-js">it(<span class="hljs-string">&apos;fails if the list is full&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> MAX_LIST_SIZE = <span class="hljs-number">4</span>;
  <span class="hljs-keyword">const</span> owner = <span class="hljs-keyword">await</span> createUser();
  <span class="hljs-keyword">const</span> list = <span class="hljs-keyword">await</span> createList(owner, <span class="hljs-string">&apos;list&apos;</span>, MAX_LIST_SIZE);

  <span class="hljs-comment">// Add 4 items, in parallel for speed.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(MAX_LIST_SIZE).fill(<span class="hljs-number">0</span>).map(<span class="hljs-function">(<span class="hljs-params">_, i</span>) =&gt;</span> {
      <span class="hljs-keyword">return</span> addItem({
        list,
        <span class="hljs-attr">user</span>: owner,
        <span class="hljs-attr">name</span>: <span class="hljs-string">`Item <span class="hljs-subst">&#x24;{i}</span>`</span>,
        <span class="hljs-attr">bounty</span>: <span class="hljs-number">1</span> * LAMPORTS_PER_SOL,
      });
    })
  );

  <span class="hljs-keyword">const</span> adderStartingBalance = <span class="hljs-keyword">await</span> getAccountBalance(owner.key.publicKey);

  <span class="hljs-comment">// Now the list should be full.</span>
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> addResult = <span class="hljs-keyword">await</span> addItem({
      list,
      <span class="hljs-attr">user</span>: owner,
      <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;Full item&apos;</span>,
      <span class="hljs-attr">bounty</span>: <span class="hljs-number">1</span> * LAMPORTS_PER_SOL,
    });

    <span class="hljs-built_in">console</span>.dir(addResult, { <span class="hljs-attr">depth</span>: <span class="hljs-literal">null</span> });
    expect.fail(<span class="hljs-string">&apos;Adding to full list should have failed&apos;</span>);
  } <span class="hljs-keyword">catch</span> (e) {
    expect(e.toString()).contains(<span class="hljs-string">&apos;This list is full&apos;</span>);
  }

  <span class="hljs-keyword">let</span> adderNewBalance = <span class="hljs-keyword">await</span> getAccountBalance(owner.key.publicKey);
  expect(adderStartingBalance, <span class="hljs-string">&apos;Adder balance is unchanged&apos;</span>).equals(adderNewBalance);
});
</code></pre>
<p>There are various ways to check an error condition, but the test here calls the failing function
from within a <code>try</code> block, and then calls <code>expect.fail</code> to fail the test if <code>addItem</code> doesn&#x2019;t throw an exception. In the
<code>catch</code> block we then check that the error message matches the one we expected to see.</p>
<p>In the <a href="https://github.com/dimfeld/starting-with-solana/blob/master/tests/todo.js">actual file</a>
I also tested creating an item with a too-small reward, which should also throw an error.</p>
<h1 id="cancelling-an-item">Cancelling an Item <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#cancelling-an-item">&#x1f517;</a></h1>
<p>Either the list&#x2019;s owner or the creator of an item can cancel the item, in which case the reward tokens are
returned to the item&#x2019;s creator.</p>
<h2 id="cancel-instruction-accounts">Cancel Instruction Accounts <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#cancel-instruction-accounts">&#x1f517;</a></h2>
<p>This should look familiar by now. The main addition here is the <code>item_creator</code> account, which we need to
transfer the item&#x2019;s balance back to its creator. The <code>address</code> constraint in the account macro
checks that the address of <code>item.creator</code> is the same as <code>item_creator</code>.</p>
<p>Also note that we need to mark
<code>item_creator</code> with <code>mut</code> &#x2013; although we don&#x2019;t modify its data, transferring a balance to an account requires
it to be writable. Solana validators use the &#x201c;read-only vs. writable&#x201d; distinction to allow multiple transactions
to use accounts that are only used in read-only mode at a particular time. This is a similar concept to an
<code>RWMutex</code> or Rust&#x2019;s mutable borrow model, if you&#x2019;re familiar with those.</p>
<p>From here on I&#x2019;ll omit the <code>seeds</code> and <code>bump</code> from the account macro to save some space, but they are
identical to the values in the <code>Add</code> instruction.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-meta">#[instruction(list_name: String)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cancel</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(mut,
      has_one=list_owner @ TodoListError::WrongListOwner,
      ... omitted seeds and bump for brevity)]</span>
    <span class="hljs-keyword">pub</span> list: Account&lt;<span class="hljs-symbol">&apos;info</span>, TodoList&gt;,
    <span class="hljs-keyword">pub</span> list_owner: AccountInfo&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> item: Account&lt;<span class="hljs-symbol">&apos;info</span>, ListItem&gt;,
    <span class="hljs-meta">#[account(mut, address=item.creator @ TodoListError::WrongItemCreator)]</span>
    <span class="hljs-keyword">pub</span> item_creator: AccountInfo&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
}
</code></pre>
<h2 id="cancel-implementation">Cancel Implementation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#cancel-implementation">&#x1f517;</a></h2>
<p>The cancel instruction performs two checks:</p>
<ul>
<li>The caller is either the list owner or the item creator</li>
<li>The cancelled item is actually in this todo list.</li>
</ul>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">cancel</span></span>(ctx: Context&lt;Cancel&gt;, _list_name: <span class="hljs-built_in">String</span>) -&gt; ProgramResult {
    <span class="hljs-keyword">let</span> list = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.list;
    <span class="hljs-keyword">let</span> item = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.item;
    <span class="hljs-keyword">let</span> item_creator = &amp;ctx.accounts.item_creator;

    <span class="hljs-keyword">let</span> user = ctx.accounts.user.to_account_info().key;

    <span class="hljs-keyword">if</span> &amp;list.list_owner != user &amp;&amp; &amp;item.creator != user {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(TodoListError::CancelPermissions.into());
    }

    <span class="hljs-keyword">if</span> !list.lines.contains(item.to_account_info().key) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(TodoListError::ItemNotFound.into());
    }

    <span class="hljs-comment">// Return the tokens to the item creator</span>
    item.close(item_creator.to_account_info())?;

    <span class="hljs-keyword">let</span> item_key = ctx.accounts.item.to_account_info().key;
    list.lines.retain(|key| key != item_key);

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>Here we use <code>item.close</code> to tell Anchor/Solana to delete the account and also transfer any balance on it
to the <code>item_creator</code> account. The final step is to actually remove the item from the list. Rust&#x2019;s <code>Vec::retain</code>
works similarly to a <code>filter</code> operation except it modifies the list in place.</p>
<h2 id="testing-cancellation">Testing Cancellation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#testing-cancellation">&#x1f517;</a></h2>
<p>In the interest of space I&#x2019;ll only show the full code here for one of the passing tests. We create the list and
item, do a quick check that it works right, and then cancel the item, checking again that the balance
was returned and the item is removed.</p>
<pre><code class="language-js">it(<span class="hljs-string">&apos;List owner can cancel an item&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> [owner, adder] = <span class="hljs-keyword">await</span> createUsers(<span class="hljs-number">2</span>);
  <span class="hljs-keyword">const</span> list = <span class="hljs-keyword">await</span> createList(owner, <span class="hljs-string">&apos;list&apos;</span>);

  <span class="hljs-keyword">const</span> adderStartingBalance = <span class="hljs-keyword">await</span> getAccountBalance(adder.key.publicKey);

  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> addItem({
    list,
    <span class="hljs-attr">user</span>: adder,
    <span class="hljs-attr">bounty</span>: LAMPORTS_PER_SOL,
    <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;An item&apos;</span>,
  });

  <span class="hljs-keyword">const</span> adderBalanceAfterAdd = <span class="hljs-keyword">await</span> getAccountBalance(adder.key.publicKey);

  expect(result.list.data.lines, <span class="hljs-string">&apos;Item is added to list&apos;</span>).deep.equals([result.item.publicKey]);
  expect(adderBalanceAfterAdd, <span class="hljs-string">&apos;Bounty is removed from adder&apos;</span>).lt(adderStartingBalance);

  <span class="hljs-keyword">const</span> cancelResult = <span class="hljs-keyword">await</span> cancelItem({
    list,
    <span class="hljs-attr">item</span>: result.item,
    <span class="hljs-attr">itemCreator</span>: adder,
    <span class="hljs-attr">user</span>: owner,
  });

  <span class="hljs-keyword">const</span> adderBalanceAfterCancel = <span class="hljs-keyword">await</span> getAccountBalance(adder.key.publicKey);
  expectBalance(adderBalanceAfterCancel, adderBalanceAfterAdd + LAMPORTS_PER_SOL, <span class="hljs-string">&apos;Cancel returns bounty to adder&apos;</span>);
  expect(cancelResult.list.data.lines, <span class="hljs-string">&apos;Cancel removes item from list&apos;</span>).deep.equals([]);
});
</code></pre>
<p>In the actual test file we run the same test but with the list owner cancelling the item, and then there
are three error checking tests:</p>
<ul>
<li>Other users can not cancel an item &#x2013; Similar to the above except we create a third user and try it have it cancel the
item.</li>
<li>The <code>item_creator</code> account must match the <code>creator</code> field on the item.</li>
<li>The item must be in the list &#x2013; Here we create two lists, add an item to one of them, but then pass the account of the
other list when trying to cancel the item.</li>
</ul>
<h1 id="finishing-an-item">Finishing an Item <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#finishing-an-item">&#x1f517;</a></h1>
<p>We&#x2019;re almost done! The Finish instruction awards an item&#x2019;s balance to the list owner when both the item creator and the list owner mark it finished.</p>
<aside class="warn"><p>Once again, a reminder that this is not a proper escrow implementation and there are all sorts of ways to exploit it.</p>
</aside><h2 id="finish-instruction-accounts">Finish Instruction Accounts <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#finish-instruction-accounts">&#x1f517;</a></h2>
<p>Once again, we have the accounts for the list, the list owner, the item, and the user initiating the transaction.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-meta">#[instruction(list_name: String)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Finish</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(mut,
      has_one=list_owner @ TodoListError::WrongListOwner,
      ... omitted seeds and bump for brevity)]</span>
    <span class="hljs-keyword">pub</span> list: Account&lt;<span class="hljs-symbol">&apos;info</span>, TodoList&gt;,
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> list_owner: AccountInfo&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> item: Account&lt;<span class="hljs-symbol">&apos;info</span>, ListItem&gt;,
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
}
</code></pre>
<h2 id="finish-implementation">Finish Implementation <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#finish-implementation">&#x1f517;</a></h2>
<p>The finish process sets the <code>creator_finished</code> flag or the <code>list_owner_finished</code> flag depending
on who called it. If both of the flags are set, then the item is finished.</p>
<p>Finishing the item looks very similar to the cancel instruction, except we transfer the item&#x2019;s reward
to the list owner.</p>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">finish</span></span>(ctx: Context&lt;Finish&gt;, _list_name: <span class="hljs-built_in">String</span>) -&gt; ProgramResult {
    <span class="hljs-keyword">let</span> item = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.item;
    <span class="hljs-keyword">let</span> list = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.list;
    <span class="hljs-keyword">let</span> user = ctx.accounts.user.to_account_info().key;

    <span class="hljs-keyword">if</span> !list.lines.contains(item.to_account_info().key) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(TodoListError::ItemNotFound.into());
    }

    <span class="hljs-keyword">let</span> is_item_creator = &amp;item.creator == user;
    <span class="hljs-keyword">let</span> is_list_owner = &amp;list.list_owner == user;

    <span class="hljs-keyword">if</span> !is_item_creator &amp;&amp; !is_list_owner {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(TodoListError::FinishPermissions.into());
    }

    <span class="hljs-keyword">if</span> is_item_creator {
        item.creator_finished = <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">if</span> is_list_owner {
        item.list_owner_finished = <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">if</span> item.creator_finished &amp;&amp; item.list_owner_finished {
        <span class="hljs-keyword">let</span> item_key = item.to_account_info().key;
        list.lines.retain(|key| key != item_key);
        item.close(ctx.accounts.list_owner.to_account_info())?;
    }

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h2 id="testing-finish">Testing Finish <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#testing-finish">&#x1f517;</a></h2>
<p>We can test the finish instruction using a very similar process. We create a list, add an item, and then
try various ways to call finish.</p>
<p>The first test has the list owner call finish first, then the item creator.</p>
<pre><code class="language-js">it(<span class="hljs-string">&apos;List owner then item creator&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> [owner, adder] = <span class="hljs-keyword">await</span> createUsers(<span class="hljs-number">2</span>);

  <span class="hljs-keyword">const</span> list = <span class="hljs-keyword">await</span> createList(owner, <span class="hljs-string">&apos;list&apos;</span>);
  <span class="hljs-keyword">const</span> ownerInitial = <span class="hljs-keyword">await</span> getAccountBalance(owner.key.publicKey);

  <span class="hljs-keyword">const</span> bounty = <span class="hljs-number">5</span> * LAMPORTS_PER_SOL;
  <span class="hljs-keyword">const</span> { item } = <span class="hljs-keyword">await</span> addItem({
    list,
    <span class="hljs-attr">user</span>: adder,
    bounty,
    <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;An item&apos;</span>,
  });

  expect(<span class="hljs-keyword">await</span> getAccountBalance(item.publicKey), <span class="hljs-string">&apos;initialized account has bounty&apos;</span>).equals(bounty);

  <span class="hljs-keyword">const</span> firstResult = <span class="hljs-keyword">await</span> finishItem({
    list,
    item,
    <span class="hljs-attr">user</span>: owner,
    <span class="hljs-attr">listOwner</span>: owner,
  });

  expect(firstResult.list.data.lines, <span class="hljs-string">&apos;Item still in list after first finish&apos;</span>).deep.equals([item.publicKey]);
  expect(firstResult.item.data.creatorFinished, <span class="hljs-string">&apos;Creator finish is false after owner calls finish&apos;</span>).equals(<span class="hljs-literal">false</span>);
  expect(firstResult.item.data.listOwnerFinished, <span class="hljs-string">&apos;Owner finish flag gets set after owner calls finish&apos;</span>).equals(<span class="hljs-literal">true</span>);
  expect(<span class="hljs-keyword">await</span> getAccountBalance(firstResult.item.publicKey), <span class="hljs-string">&apos;Bounty remains on item after one finish call&apos;</span>).equals(
    bounty
  );

  <span class="hljs-keyword">const</span> finishResult = <span class="hljs-keyword">await</span> finishItem({
    list,
    item,
    <span class="hljs-attr">user</span>: adder,
    <span class="hljs-attr">listOwner</span>: owner,
    <span class="hljs-attr">expectAccountClosed</span>: <span class="hljs-literal">true</span>,
  });

  expect(finishResult.list.data.lines, <span class="hljs-string">&apos;Item removed from list after both finish&apos;</span>).deep.equals([]);
  expect(<span class="hljs-keyword">await</span> getAccountBalance(finishResult.item.publicKey), <span class="hljs-string">&apos;Bounty remains on item after one finish call&apos;</span>).equals(
    <span class="hljs-number">0</span>
  );
  expectBalance(<span class="hljs-keyword">await</span> getAccountBalance(owner.key.publicKey), ownerInitial + bounty, <span class="hljs-string">&apos;Bounty transferred to owner&apos;</span>);
});
</code></pre>
<p>In the Github repository, we also test the opposite order of calls to <code>finish</code>, which should end in the same result.</p>
<p>The error checks here are similar to those for the cancel instruction:</p>
<ul>
<li>Disallowed users can not call finish</li>
<li>The list owner account must match the owner recorded on the list</li>
<li>Calling finish on an item not in the list does not work.</li>
<li>Calling finish on an already-finished item does not work.</li>
</ul>
<h1 id="next-steps">Next Steps <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part04#next-steps">&#x1f517;</a></h1>
<p>And that&#x2019;s it! A lot of code here but hopefully it gives you a good idea on how a slightly more complex contract
would fit together. In part 5 we&#x2019;ll finally build a Svelte-based web interface to the todo list.</p>
]]></description><link>https://imfeld.dev/writing/starting_with_solana_part04</link><guid isPermaLink="false">abcb3fae89e002e62e442dabf42134d339aa468836c71e2944ba0ace5671a3b9</guid><category><![CDATA[Solana]]></category><category><![CDATA[web3]]></category><pubDate>Fri, 05 Nov 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Hot Module Reloading for Content in Sveltekit]]></title><description><![CDATA[<p>Tags: Svelte, HMR, Vite, Sveltekit</p><p>I recently converted my website from <a href="https://sapper.svelte.dev/">Sapper</a> to <a href="https://kit.svelte.dev">SvelteKit</a>.
SvelteKit uses the <a href="https://https://vitejs.dev/">Vite</a> build tool, and one of Vite&#x2019;s great features is Hot Module Reloading,
or HMR, which can reload changed parts of a site without reloading the entire browser page.</p>
<p>This is great for speeding up developer productivity, and so I wanted to see if I could support HMR when changing the Markdown
and HTML files that make up the content of this site as well. Between Vite&#x2019;s HMR API and some SvelteKit
features, it was easier than I expected.</p>
<aside class="note"><p>Sometimes you may be able to just use Vite&#x2019;s <a href="https://vitejs.dev/guide/features.html#glob-import"><code>import.meta.glob</code></a> to accomplish this. If this doesn&#x2019;t fit your needs, read on!</p>
</aside><h1 id="vite-hmr-plugin">Vite HMR Plugin <a class="header-anchor" href="https://imfeld.dev/writing/hmr_for_markdown_in_sveltekit#vite-hmr-plugin">&#x1f517;</a></h1>
<p>The first step is to add a build plugin into the Vite configuration. With SvelteKit, this configuration goes inside your <code>svelte.config.js</code>.</p>
<p>Vite plugins have a similar API to <a href="https://rollupjs.org/">Rollup</a> plugins, but with some extra methods. The plugins provide
one or more hooks into the build process, and then Vite calls those hooks at the appropriate time.</p>
<p>First, our plugin provides a <code>configureServer</code> hook which tells Vite to watch the content directories for changes.
In Rollup this would be done in the <code>buildStart</code> hook and call <code>this.watch</code> to add the paths, but that doesn&#x2019;t work
for Vite dev mode. Instead, you call <code>server.watcher.add(path)</code>. In the snippet below, you can see I add three directories
to the watcher.</p>
<p>Adding these directories tells Vite to monitor them for changes and have them participate in the HMR process.
When a change occurs, Vite will call the <a href="https://vitejs.dev/guide/api-plugin.html#handlehotupdate"><code>handleHotUpdate</code></a> hook
with one argument of type <code>HmrContext</code>.</p>
<pre><code class="language-typescript"><span class="hljs-keyword">interface</span> HmrContext {
  <span class="hljs-attr">file</span>: <span class="hljs-built_in">string</span>;
  timestamp: <span class="hljs-built_in">number</span>;
  modules: <span class="hljs-built_in">Array</span>&lt;ModuleNode&gt;;
  read: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">string</span> | <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">string</span>&gt;;
  server: ViteDevServer;
}
</code></pre>
<p><a href="https://vitejs.dev/guide/api-plugin.html#handlehotupdate">The full documentation</a> explains it in more detail,
but you can then return <code>modules</code>, filter down the list of modules to reload fewer modules, or send a custom event to
the client side using <code>server.ws.send</code>. In our case, we look for a path matching one of the content directories, and send
a custom client event. The full plugin is below.</p>
<pre><code class="language-js"><span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import(&apos;@sveltejs/kit&apos;).Config}</span> </span>*/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-attr">kit</span>: {
    <span class="hljs-attr">vite</span>: <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-attr">plugins</span>: [
        {
          <span class="hljs-attr">name</span>: <span class="hljs-string">&apos;watch-content&apos;</span>,
          <span class="hljs-function"><span class="hljs-title">configureServer</span>(<span class="hljs-params">server</span>)</span> {
            server.watcher.add(path.join(dirname, <span class="hljs-string">&apos;posts&apos;</span>));
            server.watcher.add(path.join(dirname, <span class="hljs-string">&apos;notes&apos;</span>));
            server.watcher.add(path.join(dirname, <span class="hljs-string">&apos;pkm-pages&apos;</span>));
          },
          <span class="hljs-function"><span class="hljs-title">handleHotUpdate</span>(<span class="hljs-params">ctx</span>)</span> {
            <span class="hljs-keyword">let</span> m = <span class="hljs-regexp">/(notes|posts|pkm-pages)\/(.*)\.(md|html)&#x24;/</span>.exec(ctx.file);
            <span class="hljs-keyword">if</span> (m) {
              <span class="hljs-keyword">let</span> contentType = m[<span class="hljs-number">1</span>];
              <span class="hljs-keyword">let</span> id = m[<span class="hljs-number">2</span>];

              <span class="hljs-comment">// This is just a conversion from the directory</span>
              <span class="hljs-comment">// names to the URLs used in the site.</span>
              <span class="hljs-keyword">if</span> (contentType === <span class="hljs-string">&apos;pkm-pages&apos;</span>) {
                contentType = <span class="hljs-string">&apos;notes&apos;</span>;
              } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (contentType === <span class="hljs-string">&apos;posts&apos;</span>) {
                contentType = <span class="hljs-string">&apos;writing&apos;</span>;
              }

              ctx.server.ws.send({
                <span class="hljs-attr">type</span>: <span class="hljs-string">&apos;custom&apos;</span>,
                <span class="hljs-attr">event</span>: <span class="hljs-string">&apos;content-update&apos;</span>,
                <span class="hljs-attr">data</span>: {
                  <span class="hljs-attr">type</span>: contentType,
                  id,
                },
              });

              <span class="hljs-comment">// Return an empty module list since we</span>
              <span class="hljs-comment">// handled it manually.</span>
              <span class="hljs-keyword">return</span> [];
            }

            <span class="hljs-comment">// Not an event we care about, so just do</span>
            <span class="hljs-comment">// the default behavior.</span>
            <span class="hljs-keyword">return</span> ctx.modules;
          },
        },
      ];
    },
  },
};
</code></pre>
<h1 id="the-client-side">The Client Side <a class="header-anchor" href="https://imfeld.dev/writing/hmr_for_markdown_in_sveltekit#the-client-side">&#x1f517;</a></h1>
<p>Once we can send events to the client, we need to handle them and actually perform the reload. Happily, SvelteKit makes this
easy to do. Each article page uses a SvelteKit <code>load</code> function to fetch the content, and SvelteKit also lets you force these load
functions to rerun using the <code>invalidate</code> function.</p>
<p>Vite&#x2019;s HMR API is fairly complex, but for our case of just listening to a custom event, it&#x2019;s straightforward. We check for the
presence of <code>import.meta.hot</code> to see if Vite is running, and if so it&#x2019;s just a matter of adding the event
listener for the custom <code>content-update</code> event.</p>
<pre><code class="language-svelte"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span></span><span class="javascript">
  <span class="hljs-keyword">import</span> { invalidate } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;&#x24;app/navigation&apos;</span>;

  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">import</span>.meta.hot) {
    <span class="hljs-keyword">import</span>.meta.hot.on(<span class="hljs-string">&apos;content-update&apos;</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (data.type === <span class="hljs-string">&apos;notes&apos;</span>) {
        invalidate(<span class="hljs-string">&apos;/notes/list.json&apos;</span>);
        invalidate(<span class="hljs-string">&apos;/notes/tags.json&apos;</span>);
        invalidate(<span class="hljs-string">`/notes/note/<span class="hljs-subst">&#x24;{data.id}</span>.json`</span>);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (data.type === <span class="hljs-string">&apos;writing&apos;</span>) {
        invalidate(<span class="hljs-string">&apos;/writing/list.json&apos;</span>);
        invalidate(<span class="hljs-string">`/writing/<span class="hljs-subst">&#x24;{data.id}</span>.json`</span>);
      }
    });
  }
</span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</span></code></pre>
<p>Here I just placed a single event listener at the root <code>__layout.svelte</code> file of the site, which examines the event and
invalidates all the relevant endpoints. Larger sites would probably want to break this out to have each component manage its
own HMR event handling, but the concept is the same.</p>
<p>SvelteKit internally tracks the URLs fetched by each <code>load</code> function, and to <code>invalidate</code> then compares its argument to the tracked
URLs, and reruns any <code>load</code> functions on active pages or layout components that match. And that&#x2019;s it!</p>
]]></description><link>https://imfeld.dev/writing/hmr_for_markdown_in_sveltekit</link><guid isPermaLink="false">eb3b745a4c94a4e3de5ea9c5f2f1de1958856500bbe756ebee708ad0784ddfdd</guid><category><![CDATA[Svelte]]></category><category><![CDATA[HMR]]></category><category><![CDATA[Vite]]></category><category><![CDATA[Sveltekit]]></category><pubDate>Mon, 01 Nov 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Starting with Solana, Part 3 - Testing a Solana Program]]></title><description><![CDATA[<p>Tags: Solana, web3</p><p><a href="https://imfeld.dev/writing/starting_with_solana_part02">In part 2</a>, we took a look at the account macros that Anchor uses to get data in and out of your Solana program.
Now let&#x2019;s go back to <a href="https://dev.to/dabit3/the-complete-guide-to-full-stack-solana-development-with-react-anchor-rust-and-phantom-3291">Nader Dabit&#x2019;s tutorial</a>
and finish our first program.</p>
<p>To recap, the Rust source for the program looks like this.</p>
<pre><code class="language-rust"><span class="hljs-keyword">use</span> anchor_lang::prelude::*;

declare_id!(<span class="hljs-string">&quot;Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS&quot;</span>);

<span class="hljs-meta">#[program]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-keyword">mod</span> p0001 {
    <span class="hljs-keyword">use</span> super::*;
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">create</span></span>(ctx: Context&lt;Create&gt;) -&gt; ProgramResult {
        <span class="hljs-keyword">let</span> base_account = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.base_account;
        base_account.count = <span class="hljs-number">0</span>;
        <span class="hljs-literal">Ok</span>(())
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">increment</span></span>(ctx: Context&lt;Increment&gt;) -&gt; ProgramResult {
        <span class="hljs-keyword">let</span> base_account = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.base_account;
        base_account.count += <span class="hljs-number">1</span>;
        <span class="hljs-literal">Ok</span>(())
    }
}

<span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Create</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(init, payer=user, space= 8 + 8)]</span>
    <span class="hljs-keyword">pub</span> base_account: Account&lt;<span class="hljs-symbol">&apos;info</span>, BaseAccount&gt;,
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> system_program: Program&lt;<span class="hljs-symbol">&apos;info</span>, System&gt;,
}

<span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Increment</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> base_account: Account&lt;<span class="hljs-symbol">&apos;info</span>, BaseAccount&gt;,
}

<span class="hljs-meta">#[account]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BaseAccount</span></span> {
    <span class="hljs-keyword">pub</span> count: <span class="hljs-built_in">u64</span>,
}
</code></pre>
<h1 id="setting-the-program-id">Setting The Program ID <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part03#setting-the-program-id">&#x1f517;</a></h1>
<p>Again, the <code>anchor build</code> command will compile the program and generate a keypair that can be used to deploy it. Since Anchor&#x2019;s template always has the same
program ID at the top, we need to take the ID from the generated keypair and use it in our program.</p>
<p>The build output tells us where to find it.</p>
<pre><code class="language-shell">The program address will default to this keypair (override with --program-id):
  /home/projects/solana/p0001/target/deploy/p0001-keypair.json
</code></pre>
<p>The keypair JSON file is actually an array of numbers, designed to conveniently translate into a byte array. But the <code>solana</code> CLI command
can extract the public key &#x2013; which is also the address &#x2013; for us.</p>
<pre><code>&#x24; solana address -k target/deploy/p0001-keypair.json
6UrdK99AdvoFdM8WrteDfK9XS2ENSLEHFkXDSmMPryk
</code></pre>
<p>Here, your value should be different from the one I have. The address needs to go in two places:</p>
<ul>
<li>The <code>declare_id!</code> macro at the top of our program&#x2019;s source code.</li>
<li>The <code>Anchor.toml</code> file under the key with the same name as your program.</li>
</ul>
<pre><code class="language-toml"><span class="hljs-comment"># Anchor.toml first section</span>
<span class="hljs-section">[programs.localnet]</span>
<span class="hljs-attr">p0001</span> = <span class="hljs-string">&quot;6UrdK99AdvoFdM8WrteDfK9XS2ENSLEHFkXDSmMPryk&quot;</span>
</code></pre>
<aside class="warn"><p>The keypair file will persist across builds, but a new one with a different address will be generated if you delete it.</p>
</aside><h1 id="writing-a-test">Writing a Test <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part03#writing-a-test">&#x1f517;</a></h1>
<p>Anchor generates a test file for us, but you may remember from <a href="https://imfeld.dev/writing/starting_with_solana_part01">part 1</a> that it doesn&#x2019;t do much. Nader&#x2019;s article creates a test
that calls both of the instructions and verifies that they work, so let&#x2019;s walk through that.</p>
<p>The shell of the test imports the Anchor framework JavaScript files and gets the program ready to run. The tests default to using the <code>mocha</code> test framework,
so the <code>it</code> function defines a test and <code>describe</code> can be used to group tests together.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;assert&apos;</span>);
<span class="hljs-keyword">const</span> anchor = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;@project-serum/anchor&apos;</span>);
<span class="hljs-keyword">const</span> { SystemProgram } = anchor.web3;

describe(<span class="hljs-string">&apos;p0001&apos;</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> provider = anchor.Provider.env();
  anchor.setProvider(provider);
  <span class="hljs-keyword">const</span> program = anchor.workspace.p0001;
  <span class="hljs-comment">// To be filled in by the create test and used by the increment test.</span>
  <span class="hljs-keyword">let</span> _baseAccount;

  <span class="hljs-comment">// Tests here</span>
});
</code></pre>
<p>We then have two tests, one for each instruction. More complex instructions might require multiple tests.</p>
<h2 id="testing-the-create-instruction">Testing the Create Instruction <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part03#testing-the-create-instruction">&#x1f517;</a></h2>
<p>The first test calls the create instruction, then gets the data for the created account
and verifies that it exists and has a zero value for <code>count</code>.</p>
<pre><code class="language-js">it(<span class="hljs-string">&apos;Creates a counter&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> baseAccount = anchor.web3.Keypair.generate();
  <span class="hljs-keyword">await</span> program.rpc.create({
    <span class="hljs-attr">accounts</span>: {
      <span class="hljs-attr">baseAccount</span>: baseAccount.publicKey,
      <span class="hljs-attr">user</span>: provider.wallet.publicKey,
      <span class="hljs-attr">systemProgram</span>: SystemProgram.programId,
    },
    <span class="hljs-attr">signers</span>: [baseAccount],
  });

  <span class="hljs-comment">// The account should have been created.</span>
  <span class="hljs-keyword">const</span> account = <span class="hljs-keyword">await</span> program.account.baseAccount.fetch(
    baseAccount.publicKey
  );
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;Initial count: &apos;</span>, account.count.toString());
  assert.ok(account.count.toString() == <span class="hljs-number">0</span>);
  _baseAccount = baseAccount;
});
</code></pre>
<p>Notice that although the system program has a fixed ID, we do still have to pass its address into the program.</p>
<p>Be sure that you are <em>not</em> running a local copy of <code>solana-test-validator</code>, and then use <code>anchor test</code> to run your test.</p>
<aside class="note"><p>Mocha needs to be installed globally, using <code>npm install -g mocha</code> or your package manager of choice. If you get the error below,
that may be your problem.</p>
<pre><code>&#x24; anchor test
... other build output
&gt; Failed to run test: mocha -t 1000000 tests/: No such file or directory (os error 2)
</code></pre>
</aside><p>One oddity here is that <code>count</code> in our Rust program is a number, but the test calls <code>toString()</code> on it. Because JavaScript numbers are
64-bit floating point values, it can only accurately represent up to 53 bits worth of integers, so Anchor deserializes any value of 64 bits or above
as a <a href="https://www.npmjs.com/package/bn.js">bn.js</a> BigNum object.</p>
<pre><code>&gt; console.dir(account.count);
BN { negative: 0, words: [ 0, 0, 0 ], length: 1, red: null }

&gt; console.log(account.count.toString());
0
</code></pre>
<h2 id="testing-the-increment-instructions">Testing the Increment Instructions <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part03#testing-the-increment-instructions">&#x1f517;</a></h2>
<p>The next test is for the increment instruction, which reuses the <code>baseAccount</code> from the first test.</p>
<pre><code class="language-js">it(<span class="hljs-string">&apos;Increments a counter&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> baseAccount = _baseAccount;
  <span class="hljs-keyword">await</span> program.rpc.increment({
    <span class="hljs-attr">accounts</span>: {
      <span class="hljs-attr">baseAccount</span>: baseAccount.publicKey,
    },
  });

  <span class="hljs-keyword">const</span> account = <span class="hljs-keyword">await</span> program.account.baseAccount.fetch(
    baseAccount.publicKey
  );
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;After increment: &apos;</span>, account.count.toString());
  assert.ok(account.count.toString() == <span class="hljs-number">1</span>);
});
</code></pre>
<p>Not much to say about this one.</p>
<h1 id="deploy-to-localhost">Deploy to Localhost <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part03#deploy-to-localhost">&#x1f517;</a></h1>
<p>With <code>solana-test-validator</code> running on your local machine, you can deploy the contract.</p>
<pre><code>&#x24; anchor deploy
Deploying workspace: http://localhost:8899
Upgrade authority: /home/projects/.config/solana/id.json
Deploying program &quot;p0001&quot;...
Program path: /home/projects/solana/p0001/target/deploy/p0001.so...
Program Id: 6UrdK99AdvoFdM8WrteDfK9XS2ENSLEHFkXDSmMPryk

Deploy success
</code></pre>
<p>In <a href="https://imfeld.dev/writing/starting_with_solana_part04">part 4</a> we&#x2019;ll take the lessons learned in these first three parts and create a
todo list application with attached rewards. <a href="https://imfeld.dev/writing/starting_with_solana_part04">Check it out now!</a></p>
]]></description><link>https://imfeld.dev/writing/starting_with_solana_part03</link><guid isPermaLink="false">ef40473d96dc59bd37c35ae4ff483235b5afcc72513845110166ab96d0a51284</guid><category><![CDATA[Solana]]></category><category><![CDATA[web3]]></category><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Starting with Solana, Part 2 - Anchor's Account Macros]]></title><description><![CDATA[<p>Tags: Solana, web3</p><p><a href="https://imfeld.dev/writing/starting_with_solana_part01">Last time</a>, we set up our Solana and Anchor toolchains, and started to create a simple Solana program, following
<a href="https://dev.to/dabit3/the-complete-guide-to-full-stack-solana-development-with-react-anchor-rust-and-phantom-3291">Nader Dabit&#x2019;s tutorial</a>.
The end of the post started to look into what a Solana &#x201c;Account&#x201d; actually is, so we&#x2019;ll continue there with the Anchor framework&#x2019;s
<code>#[account]</code> macro.</p>
<p>There are actually 2 <code>#[account]</code> macros in Anchor. One is used on <code>Account</code> structures to facilitate reading and writing Accounts
from their raw data into Rust structures. The other is used in conjunction with the <code>Accounts</code> trait derive macro, which is placed
on structures used for instruction inputs.</p>
<h1 id="-account-on-an-account-structure"><code>#[account]</code> on an Account Structure <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part02#-account-on-an-account-structure">&#x1f517;</a></h1>
<p>The macro invocation on the <code>BaseAccount</code> struct marks it as actually being used as
an account, and generates some code to copy between the raw account data and the Rust structure. From Solana&#x2019;s point of
view, an account is just a raw buffer of bytes. Anchor has its own <code>AccountSerialize</code> and <code>AccountDeserialize</code> traits,
similar to (but simpler and more specialized than) the Rust <code>serde</code> crate&#x2019;s <code>Serialize</code> and <code>Deserialize</code> traits.</p>
<p>With the <a href="https://github.com/dtolnay/cargo-expand"><code>cargo expand</code></a> command we can take a look at the code generated for the
<code>BaseAccount</code> struct, which looks like this.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[account]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BaseAccount</span></span> {
    <span class="hljs-keyword">pub</span> count: <span class="hljs-built_in">u64</span>,
}
</code></pre>
<p>First, the code to write the Rust <code>BaseAccount</code> structure to a raw account buffer.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[automatically_derived]</span>
<span class="hljs-keyword">impl</span> anchor_lang::AccountSerialize <span class="hljs-keyword">for</span> BaseAccount {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">try_serialize</span></span>&lt;W: std::io::Write&gt;(
        &amp;<span class="hljs-keyword">self</span>,
        writer: &amp;<span class="hljs-keyword">mut</span> W,
    ) -&gt; std::result::<span class="hljs-built_in">Result</span>&lt;(), ProgramError&gt; {
        writer
            .write_all(&amp;[<span class="hljs-number">16</span>, <span class="hljs-number">90</span>, <span class="hljs-number">130</span>, <span class="hljs-number">242</span>, <span class="hljs-number">159</span>, <span class="hljs-number">10</span>, <span class="hljs-number">232</span>, <span class="hljs-number">133</span>])
            .map_err(|_| anchor_lang::__private::ErrorCode::AccountDidNotSerialize)?;
        AnchorSerialize::serialize(<span class="hljs-keyword">self</span>, writer)
            .map_err(|_| anchor_lang::__private::ErrorCode::AccountDidNotSerialize)?;
        <span class="hljs-literal">Ok</span>(())
    }
}
</code></pre>
<p>It first writes a discriminator, 8 bytes taken from a SHA256 hash of the name of the struct (&#x201c;BaseAccount&#x201d; in this case).
This adds a check that the data you&#x2019;re about to read is actually a <code>BaseAccount</code>. I imagine it doesn&#x2019;t do anything from a
security standpoint since it&#x2019;s easy to copy, but it at least catches mistakes in sending the wrong type of Account to the program.</p>
<p>You can pass a namespace string value into the account macro, which will be prefixed to the struct&#x2019;s name when generating the
discriminator to reduce the chances of your struct having the same discriminator as a struct from someone else&#x2019;s program.
This is in the source code but doesn&#x2019;t appear to be documented, so I&#x2019;m not sure if it&#x2019;s a good idea to use this namespace feature right now.</p>
<p>Next, some code to actually write the data in the call to <code>AnchorSerialize::serialize</code>. The generated <code>BorshSerialize</code> trait
implementation handles this. <a href="https://borsh.io/">Borsh</a> is a binary data serialization framework with an extra focus on security.</p>
<pre><code class="language-rust"><span class="hljs-keyword">impl</span> borsh::ser::BorshSerialize <span class="hljs-keyword">for</span> BaseAccount
<span class="hljs-keyword">where</span>
    <span class="hljs-built_in">u64</span>: borsh::ser::BorshSerialize,
{
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">serialize</span></span>&lt;W: borsh::maybestd::io::Write&gt;(
        &amp;<span class="hljs-keyword">self</span>,
        writer: &amp;<span class="hljs-keyword">mut</span> W,
    ) -&gt; ::core::result::<span class="hljs-built_in">Result</span>&lt;(), borsh::maybestd::io::Error&gt; {
        borsh::BorshSerialize::serialize(&amp;<span class="hljs-keyword">self</span>.count, writer)?;
        <span class="hljs-literal">Ok</span>(())
    }
}
</code></pre>
<p>Since the structure has just one field, you can see it&#x2019;s just writing self.count to the passed in writer.</p>
<p>Deserializing the struct from the raw account buffer is similar. It first checks that the discriminator value matches, then
calls <code>AnchorDeserialize::deserialize</code> to read in the actual data.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[automatically_derived]</span>
<span class="hljs-keyword">impl</span> anchor_lang::AccountDeserialize <span class="hljs-keyword">for</span> BaseAccount {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">try_deserialize</span></span>(buf: &amp;<span class="hljs-keyword">mut</span> &amp;[<span class="hljs-built_in">u8</span>]) -&gt; std::result::<span class="hljs-built_in">Result</span>&lt;<span class="hljs-keyword">Self</span>, ProgramError&gt; {
        <span class="hljs-keyword">if</span> buf.len() &lt; [<span class="hljs-number">16</span>, <span class="hljs-number">90</span>, <span class="hljs-number">130</span>, <span class="hljs-number">242</span>, <span class="hljs-number">159</span>, <span class="hljs-number">10</span>, <span class="hljs-number">232</span>, <span class="hljs-number">133</span>].len() {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(anchor_lang::__private::ErrorCode::AccountDiscriminatorNotFound.into());
        }
        <span class="hljs-keyword">let</span> given_disc = &amp;buf[..<span class="hljs-number">8</span>];
        <span class="hljs-keyword">if</span> &amp;[<span class="hljs-number">16</span>, <span class="hljs-number">90</span>, <span class="hljs-number">130</span>, <span class="hljs-number">242</span>, <span class="hljs-number">159</span>, <span class="hljs-number">10</span>, <span class="hljs-number">232</span>, <span class="hljs-number">133</span>] != given_disc {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(anchor_lang::__private::ErrorCode::AccountDiscriminatorMismatch.into());
        }
        Self::try_deserialize_unchecked(buf)
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">try_deserialize_unchecked</span></span>(buf: &amp;<span class="hljs-keyword">mut</span> &amp;[<span class="hljs-built_in">u8</span>]) -&gt; std::result::<span class="hljs-built_in">Result</span>&lt;<span class="hljs-keyword">Self</span>, ProgramError&gt; {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> data: &amp;[<span class="hljs-built_in">u8</span>] = &amp;buf[<span class="hljs-number">8</span>..];
        AnchorDeserialize::deserialize(&amp;<span class="hljs-keyword">mut</span> data)
            .map_err(|_| anchor_lang::__private::ErrorCode::AccountDidNotDeserialize.into())
    }
}

<span class="hljs-keyword">impl</span> borsh::de::BorshDeserialize <span class="hljs-keyword">for</span> BaseAccount
<span class="hljs-keyword">where</span>
    <span class="hljs-built_in">u64</span>: borsh::BorshDeserialize,
{
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">deserialize</span></span>(buf: &amp;<span class="hljs-keyword">mut</span> &amp;[<span class="hljs-built_in">u8</span>]) -&gt; ::core::result::<span class="hljs-built_in">Result</span>&lt;<span class="hljs-keyword">Self</span>, borsh::maybestd::io::Error&gt; {
        <span class="hljs-literal">Ok</span>(<span class="hljs-keyword">Self</span> {
            count: borsh::BorshDeserialize::deserialize(buf)?,
        })
    }
}
</code></pre>
<h1 id="deriving-the-accounts-trait">Deriving the <code>Accounts</code> trait <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part02#deriving-the-accounts-trait">&#x1f517;</a></h1>
<p>A Solana program&#x2019;s input is just a raw buffer of bytes containing account public keys and various information for the program,
and the <a href="https://docs.rs/solana-sdk/1.8.1/solana_sdk/index.html">official Solana SDK</a> provides a function to extract <a href="https://docs.solana.com/developing/on-chain-programs/developing-rust#data-types">some
basic information</a> from that buffer.</p>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">unsafe</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">deserialize</span></span>&lt;<span class="hljs-symbol">&apos;a</span>&gt;(
    input: *<span class="hljs-keyword">mut</span> <span class="hljs-built_in">u8</span>
) -&gt; (&amp;<span class="hljs-symbol">&apos;a</span> Pubkey, <span class="hljs-built_in">Vec</span>&lt;AccountInfo&lt;<span class="hljs-symbol">&apos;a</span>&gt;, Global&gt;, &amp;<span class="hljs-symbol">&apos;a</span> [<span class="hljs-built_in">u8</span>])
</code></pre>
<p>Anchor automatically calls this function and then goes a step further. Each instruction in an Anchor program has a related
structure which defines the format of all the information, and
the <code>Accounts</code> trait determines how this structure can be created from the result of the <code>deserialize</code> function.
The derivation macro for this trait does a lot of heavy lifting, so we&#x2019;ll skip some of the details for now.</p>
<p>The structure for the <code>create</code> instruction in the tutorial looks like this.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Create</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(init, payer = user, space = 8 + 8)]</span>
    <span class="hljs-keyword">pub</span> base_account: Account&lt;<span class="hljs-symbol">&apos;info</span>, BaseAccount&gt;,
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> system_program: Program &lt;<span class="hljs-symbol">&apos;info</span>, System&gt;,
}
</code></pre>
<p>Anchor&#x2019;s <code>Accounts</code> trait requires one function: <code>try_accounts</code>.</p>
<pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Accounts</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt;: ToAccountMetas + ToAccountInfos&lt;<span class="hljs-symbol">&apos;info</span>&gt; + <span class="hljs-built_in">Sized</span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">try_accounts</span></span>(
        program_id: &amp;Pubkey,
        accounts: &amp;<span class="hljs-keyword">mut</span> &amp;[AccountInfo&lt;<span class="hljs-symbol">&apos;info</span>&gt;],
        ix_data: &amp;[<span class="hljs-built_in">u8</span>]
    ) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-keyword">Self</span>, ProgramError&gt;;
}
</code></pre>
<p><code>try_accounts</code> takes an array of expected <code>AccountInfo</code> structures, and expects the implementor (almost always
automatically done through the macro) to take the expected number of accounts from the front of the list and then
change the reference to point to the remaining slice of the list. This feels a lot more like C than Rust, but
given the Solana VM&#x2019;s <a href="https://docs.solana.com/developing/programming-model/runtime#compute-budget">strict execution limits</a> it makes sense,
and everything using Anchor is autogenerating it anyway so the bug risk is fairly low. Both structures such as <code>Create</code>
and the Account structures such as <code>Account</code> and <code>Signer</code> implement this trait and try_accounts.</p>
<p>In <code>Create</code>, <code>base_account</code> is the structure we looked at above, which holds the actual counter value. The <code>Accounts</code> derive macro
provides its own version of an <code>account</code> macro that can specify information on each field of the structure, and the
invocation on <code>base_account</code> has three arguments.</p>
<ul>
<li><code>init</code> tells Anchor that calling this instruction should create an account corresponding to the <code>BaseAccount</code> structure. The account is
initialized with the 8-byte discriminator and the rest of the buffer is zeroed out.</li>
<li><code>payer</code> indicates which account provides the tokens (called lamports) to pay for the newly-created account&#x2019;s rent. Here, it&#x2019;s the <code>user</code> account listed
next in the structure. Anchor will transfer two year&#x2019;s worth of lamports from the payer into the account so that it can be rent-exempt.</li>
<li><code>space</code> is the number of bytes required to store the account&#x2019;s data. This is specified when the account is created and can never be changed.
Again, Anchor needs 8 bytes and then the rest is the space taken up by the serialized structure. You can omit this and Anchor will automatically
calculate the needed space, but if your structure includes dynamically sized values such as Strings or Vecs then this won&#x2019;t work right.</li>
</ul>
<p>Next, the <code>user</code> account is a <code>Signer</code> type. In Solana, a <a href="https://docs.solana.com/developing/programming-model/accounts#signers">Signer</a>
is an account accompanied by a digital signature indicating that the account&#x2019;s owner has authorized the transaction. (As opposed to someone
else passing that account&#x2019;s address into the program.) Signer&#x2019;s implementation of <code>try_accounts</code> verifies that the referenced account
also signed the transaction.</p>
<p>Finally, there is a reference to the system program. Solana&#x2019;s system program <a href="https://docs.rs/solana-sdk/1.8.1/solana_sdk/system_instruction/enum.SystemInstruction.html">provides various services</a>
such as creating accounts, transferring lamports between accounts, and more.</p>
<p>The <code>account</code> macro <a href="https://docs.rs/anchor-lang/0.18.0/anchor_lang/derive.Accounts.html">has many other useful attributes</a>, and some common ones are:</p>
<ul>
<li><code>#[account(mut)]</code> tells Anchor that your instruction may alter the account, so it should serialize the account structure
back to the input buffer, where Solana will update its data if allowed.</li>
<li><code>#[account(signer)]</code> verifies that an account is also the signer. The <code>Signer</code> structure type we used above
also does this, but it doesn&#x2019;t actually deserialize the account contents from the buffer, so this can be used
if you need to use a type other than <code>Signer</code>.</li>
<li><code>#[account(close=target)]</code> tells the program to close the account when the instruction finishes, and transfer
its lamports to the account specified by <code>target</code>.</li>
<li><code>#[acccount(has_one=target)]</code> enforces that the field name inside the account matches the account given with the same name
in the <code>Accounts structure</code>. So in the above example, we could add a <code>user</code> field to <code>BaseAccount</code>, and then
<code>#[account(has_one=user)]</code> on the <code>base_account</code> field would add a check
that <code>base_account.user == user</code>.</li>
<li><code>#[account(owner=target)]</code> is similar to <code>has_one</code>, but it checks that the account&#x2019;s owner is equal to the account
given in the field.</li>
</ul>
<p>There are some more but these seem to be the most useful ones.</p>
<p>That&#x2019;s it for this part. Next up, we&#x2019;ll go back to implementing and testing the tutorial program.</p>
<p><a href="https://imfeld.dev/writing/starting_with_solana_part03">Part 3</a> is up now!</p>
]]></description><link>https://imfeld.dev/writing/starting_with_solana_part02</link><guid isPermaLink="false">285e3627847871bebf0b3d07c25f67b0294283f5a48e8618f40dc88b0151b398</guid><category><![CDATA[Solana]]></category><category><![CDATA[web3]]></category><pubDate>Tue, 26 Oct 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Starting with Solana, Part 1]]></title><description><![CDATA[<p>Tags: Solana, web3</p><p>My involvement in the cryptocurrency space has been minimal, aside from mining some Ethereum back in 2015 and following trends from afar. As &#x201c;web3&#x201d; has gained more mindshare in the developer community,
it feels like a good time to dip my toe in, so here&#x2019;s an exploration of writing applications for the Solana blockchain. The format will be more stream-of-consciousness than my usual articles here,
just writing things down as I discover them.</p>
<p>This article series will start out following <a href="https://dev.to/dabit3/the-complete-guide-to-full-stack-solana-development-with-react-anchor-rust-and-phantom-3291">Nader Dabit&#x2019;s introduction</a> and we&#x2019;ll see where it goes from there.</p>
<h1 id="setup">Setup <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#setup">&#x1f517;</a></h1>
<p>You don&#x2019;t need a wallet right away, but it&#x2019;s an important part of interacting with any blockchain, so it&#x2019;s a good place to start. I chose <a href="https://phantom.app/">https://phantom.app/</a> which is a popular wallet browser extension for Solana.
I have some Solana on the FTX exchange already and Phantom makes it really easy to transfer from FTX into your own account, so that&#x2019;s nice.</p>
<p>The wallet gives you a recovery passphrase so that&#x2019;s nice. Apparently this is standard nowadays, but when I first started playing with crypto you just had to make sure you didn&#x2019;t lose your private key files
so this is a nice change.</p>
<p>Next I installed the Solana CLI tools and the Anchor tools as linked from the article above.</p>
<p>Anchor is a Rust framework that provides some abstractions over the Solana VM.</p>
<p>Looks like there are three Solana cluster options:</p>
<ul>
<li>
<p><code>localhost</code> which just runs on your computer</p>
</li>
<li>
<p><code>devnet</code> which is an actual Solana network, but for testing applications and where can give your wallet as many tokens as you want (devnet tokens aren&#x2019;t real or worth anything)</p>
</li>
<li>
<p><code>mainnet beta</code>, which is the current &#x201c;real&#x201d; network where real transactions happen</p>
<p>Once you have the Solana CLI tools installed, you can run <code>solana-test-validator</code> to start a single-node <code>localhost</code> cluster on your computer.</p>
<p>To start out with the testing code you&#x2019;ll need to create a &#x201c;paper wallet&#x201d; as well. This isn&#x2019;t really suitable from a security standpoint for real use but is fine for just testing.
You can run <code>solana address</code> to get instructions on how to create that wallet if you don&#x2019;t have it yet.</p>
<p>Nader&#x2019;s article has a quick overview of other <code>solana</code> CLI commands that come in handy at the start. There are about 75 commands overall but it looks like most of them aren&#x2019;t used too often.</p>
</li>
</ul>
<h1 id="the-anchor-project-template">The Anchor Project Template <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#the-anchor-project-template">&#x1f517;</a></h1>
<p>Ok, so on to creating an Anchor project. <code>anchor init p0001</code> is what I used. I initially called it just <code>0001</code> which Anchor will do, but Rust doesn&#x2019;t let crate names start with numbers, so don&#x2019;t do that.</p>
<p>So this gives you a scaffolding of a Rust Solana program, a test file in JavaScript, and some miscellaneous stuff.</p>
<h2 id="the-program">The Program <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#the-program">&#x1f517;</a></h2>
<p>Opening the Rust file <code>programs/p0001/src/lib.rs</code> gives us this:</p>
<pre><code class="language-rust"><span class="hljs-keyword">use</span> anchor_lang::prelude::*;

 declare_id!(<span class="hljs-string">&quot;Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS&quot;</span>);

 <span class="hljs-meta">#[program]</span>
 <span class="hljs-keyword">pub</span> <span class="hljs-keyword">mod</span> p0001 {
     <span class="hljs-keyword">use</span> super::*;
     <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">initialize</span></span>(ctx: Context&lt;Initialize&gt;) -&gt; ProgramResult {
         <span class="hljs-literal">Ok</span>(())
     }
 }

 <span class="hljs-meta">#[derive(Accounts)]</span>
 <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Initialize</span></span> {}
</code></pre>
<p>So the program itself is a module inside the file, and each function in the module becomes an entrypoint into the contract. Solana calls each of these functions an &#x201c;instruction.&#x201d; The #[program] line is a macro that processes the module into a Solana program.
You can build the project with <code>anchor build</code>.</p>
<p>It looks like Solana programs compile to a variation of the <a href="https://ebpf.io/">eBPF format</a>. This is interesting since that&#x2019;s a bytecode originally designed for high-performance packet filtering inside the kernel.
I&#x2019;ve been hearing of it used for other stuff here and there so I guess this is one example.</p>
<h2 id="the-idl-file">The IDL File <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#the-idl-file">&#x1f517;</a></h2>
<p>The build command generates the compiled program, a keypair that can be used as a wallet to deploy the contract with, and an IDL file that describes the instructions exposed by the contract.</p>
<pre><code>~/projects/solana/p0001 &#x276f; cat target/idl/p0001.json
{
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;name&quot;: &quot;p0001&quot;,
  &quot;instructions&quot;: [
    {
      &quot;name&quot;: &quot;initialize&quot;,
      &quot;accounts&quot;: [],
      &quot;args&quot;: []
    }
  ]
}
</code></pre>
<p>So as you see in the file above, this IDL file describes the initialize instruction generated by Anchor, which has no arguments or other associated data.</p>
<p>Let&#x2019;s also take a look at the default test, at <code>tests/p0001.js</code>.</p>
<h2 id="testing">Testing <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#testing">&#x1f517;</a></h2>
<pre><code class="language-js"><span class="hljs-keyword">const</span> anchor = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;@project-serum/anchor&apos;</span>);

describe(<span class="hljs-string">&apos;p0001&apos;</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Configure the client to use the local cluster.</span>
  anchor.setProvider(anchor.Provider.env());

  it(<span class="hljs-string">&apos;Is initialized!&apos;</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-comment">// Add your test here.</span>
    <span class="hljs-keyword">const</span> program = anchor.workspace.P0001;
    <span class="hljs-keyword">const</span> tx = <span class="hljs-keyword">await</span> program.rpc.initialize();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;Your transaction signature&apos;</span>, tx);
  });
});
</code></pre>
<p>The Provider is an abstraction that rolls up the Solana network connection, the wallet, and a <a href="https://solana-labs.github.io/solana-web3.js/modules.html#Commitment">commitment</a>, which basically defines how much confirmation you want on a block before your program can see it.</p>
<p>The test just gets the default Provider from the wallet and cluster that you set up with the anchor command. Real programs would get the user&#x2019;s wallet details and use that.</p>
<p>So then the test makes gets a reference the to program, calls the program&#x2019;s initialize instruction, and returns the signature of the transaction for that call. Apparently Solana is able to wrap up multiple instruction calls into a single transaction, even to different programs,
which is interesting.</p>
<h1 id="building-an-actual-project">Building an Actual Project <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#building-an-actual-project">&#x1f517;</a></h1>
<p>The next step in Nader&#x2019;s article is to build a very simple program with just a single counter. It has two instructions, <code>create</code> and <code>increment</code>. Each one gets an <code>Accounts</code> structure that goes along with it.</p>
<pre><code class="language-rust"><span class="hljs-meta">#[program]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-keyword">mod</span> p0001 {
    <span class="hljs-keyword">use</span> super::*;
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">create</span></span>(ctx: Context&lt;Create&gt;) -&gt; ProgramResult {
        <span class="hljs-keyword">let</span> base_account = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.base_account;
        base_account.count = <span class="hljs-number">0</span>;
        <span class="hljs-literal">Ok</span>(())
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">increment</span></span>(ctx: Context&lt;Increment&gt;) -&gt; ProgramResult {
        <span class="hljs-keyword">let</span> base_account = &amp;<span class="hljs-keyword">mut</span> ctx.accounts.base_account;
        base_account.count += <span class="hljs-number">1</span>;
        <span class="hljs-literal">Ok</span>(())
    }
}

<span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Create</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(init, payer=user, space= 8 + 8)]</span>
    <span class="hljs-keyword">pub</span> base_account: Account&lt;<span class="hljs-symbol">&apos;info</span>, BaseAccount&gt;,
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> user: Signer&lt;<span class="hljs-symbol">&apos;info</span>&gt;,
    <span class="hljs-keyword">pub</span> system_program: Program&lt;<span class="hljs-symbol">&apos;info</span>, System&gt;,
}

<span class="hljs-meta">#[derive(Accounts)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Increment</span></span>&lt;<span class="hljs-symbol">&apos;info</span>&gt; {
    <span class="hljs-meta">#[account(mut)]</span>
    <span class="hljs-keyword">pub</span> base_account: Account&lt;<span class="hljs-symbol">&apos;info</span>, BaseAccount&gt;,
}

<span class="hljs-meta">#[account]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BaseAccount</span></span> {
    <span class="hljs-keyword">pub</span> count: <span class="hljs-built_in">u64</span>,
}
</code></pre>
<h1 id="accounts">Accounts <a class="header-anchor" href="https://imfeld.dev/writing/starting_with_solana_part01#accounts">&#x1f517;</a></h1>
<p>Before we finish this, lets look at Accounts a bit more. The <a href="https://docs.solana.com/developing/programming-model/accounts">Solana Account documentation</a> tells us that an account is not actually a wallet. Instead,
it&#x2019;s a way for the contract to persist data between calls. This includes information such as the count in <code>BaseAccount</code>, and also information about permissions on the account.
It also has some lifetime information &#x201c;expressed by a number of fractional native tokens called lamports.&#x201d;</p>
<p>Accounts pay rent in the form of lamports, and if it runs out, then the account is purged from the blockchain. Accounts with two years worth of rent attached are &#x201c;rent-exempt&#x201d; and can stay on the chain forever. The current rent cost is designed to work out
to 0.01 SOL per MB of data per day, or 3.65 SOL per MB per year. Since most accounts will hold far less than 1MB of data, the actual cost should usually be quite small.</p>
<p>That&#x2019;s it for now. Next time, more on accounts, digging into the <code>#[account]</code> macro and the arguments to the <code>create</code> instruction, and actually implementing it.</p>
<p>Check out <a href="https://imfeld.dev/writing/starting_with_solana_part02">part 2</a> now!</p>
]]></description><link>https://imfeld.dev/writing/starting_with_solana_part01</link><guid isPermaLink="false">1febe532a623acd4911efa144d8a87c35fbafd5c4eeee506435c335449a37216</guid><category><![CDATA[Solana]]></category><category><![CDATA[web3]]></category><pubDate>Fri, 22 Oct 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Setting up SvelteKit with Storybook]]></title><description><![CDATA[<p>Tags: Svelte</p><aside class="note"><p>2023 Update: Storybook 7 is in beta and works great with SvelteKit 1.0 out of the box! No need for the workarounds below, just follow the <a href="https://github.com/storybookjs/storybook/blob/next/code/frameworks/sveltekit/README.md">official instructions</a>.</p>
</aside><p>I&#x2019;ve become a big fan of using Storybook to develop components in an isolated context,
and so it was a natural choice to use it for <a href="https://github.com/dimfeld/ergo">Ergo</a>.
In the process I found that some workarounds are needed to get things to work with SvelteKit,
so this sums up everything I learned about getting it to actually work.</p>
<p>If you don&#x2019;t want to read the whole process, feel free to <a href="https://imfeld.dev/writing/sveltekit_with_storybook#summing-it-up">skip to the end</a>, where I sum it up
and provide a sample Github repository with all the fixes.</p>
<p>Once you have <a href="https://kit.svelte.dev/docs#introduction-getting-started">set up a SvelteKit project</a>, the easiest way to add Storybook is with the <code>npx sb init</code> command.
This installer will detect the project type and install all the necessary dependencies and configuration files.</p>
<h1 id="first-run">First Run <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#first-run">&#x1f517;</a></h1>
<p>Ok, let&#x2019;s try it!</p>
<pre><code class="language-sh">&#x24; npm run storybook

&gt; sveltekit-storybook@0.0.1 storybook sveltekit-storybook
&gt; start-storybook -p 6006

info @storybook/svelte v6.3.4
info
ERR! Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: sveltekit-storybook/.storybook/main.js
ERR! require() of ES modules is not supported.

And more errors...
</code></pre>
<h1 id="the-cjs-file-extension">The .cjs File Extension <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#the-cjs-file-extension">&#x1f517;</a></h1>
<p>This is a common issue when using development tools with projects that set <code>&quot;type&quot;: &quot;module&quot;</code> in the package.json file, as SvelteKit does. Storybook uses <code>require</code> to include <code>.storybook/main.js</code>, but that file is an ES Module due to the project settings, so it <a href="https://nodejs.org/api/esm.html#esm_require">can not be loaded via <code>require</code></a>.</p>
<p>Fortunately, there&#x2019;s a solution. Rename the file to <code>.storybook/main.cjs</code>, and Node.js will force it to be treated as a traditional &#x201c;CommonJS&#x201d;
style module, that can be loaded with <code>require</code>. Storybook is set up to look for this extension, so it all works.</p>
<p>Trying again&#x2026;</p>
<pre><code class="language-sh">&#x24; mv .storybook/main.js .storybook/main.cjs
&#x24; npm run storybook
~/projects/sveltekit-storybook &#x276f; npm run storybook

&gt; svelte-storybook@0.0.1 storybook sveltekit-storybook
&gt; start-storybook -p 6006

info @storybook/svelte v6.3.4
info
ERR! Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: sveltekit-storybook/svelte.config.js
ERR! require() of ES modules is not supported.
</code></pre>
<p>Same issue, but slightly trickier. Storybook tries to be helpful and load the Svelte preprocessor configuration from your <code>svelte.config.js</code>
file, but since we converted <code>.storybook/main.js</code> to be a CommonJS module, now it can&#x2019;t <code>require</code> an ES module like <code>svelte.config.js</code>.</p>
<h1 id="duplicate-svelte-preprocess-configuration">Duplicate svelte-preprocess Configuration <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#duplicate-svelte-preprocess-configuration">&#x1f517;</a></h1>
<p>In this case we can&#x2019;t just rename the file since SvelteKit complains loudly if the file is named <code>svelte.config.cjs</code>. The easiest solution I&#x2019;ve found
here is to just make the Storybook <code>main.cjs</code> file recreate the preprocessor configuration instead of pulling it in from <code>svelte.config.js</code>. Not
ideal, but it&#x2019;s a pretty small bit of configuration to duplicate, so not that big a deal.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> preprocess = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;svelte-preprocess&apos;</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-comment">// The rest of the config here...</span>
  <span class="hljs-attr">svelteOptions</span>: {
    <span class="hljs-comment">// Same options that you pass to preprocess in svelte.config.js</span>
    <span class="hljs-attr">preprocess</span>: preprocess(),
  },
};
</code></pre>
<p>Ok, let&#x2019;s try again.</p>
<pre><code class="language-sh">&#x24; pnpm storybook

&gt; svelte-storybook@0.0.1 storybook sveltekit-storybook
&gt; start-storybook -p 6006

info @storybook/svelte v6.3.4
info
info =&gt; Loading presets
WARN Unable to find main.js: sveltekit-storybook/.storybook/main
info =&gt; Loading 1 config file <span class="hljs-keyword">in</span> <span class="hljs-string">&quot;sveltekit-storybook/.storybook&quot;</span>
info =&gt; Loading 9 other files <span class="hljs-keyword">in</span> <span class="hljs-string">&quot;sveltekit-storybook/.storybook&quot;</span>
info =&gt; Adding stories defined <span class="hljs-keyword">in</span> <span class="hljs-string">&quot;sveltekit-storybook/.storybook/main.js&quot;</span>
WARN Unable to find main.js: sveltekit-storybook/.storybook/main
info =&gt; Using implicit CSS loaders
info =&gt; Using default Webpack4 setup

And more output...
</code></pre>
<p>Despite the &#x201c;Unable to find main.js&#x201d; warning, it works!</p>
<h1 id="modern-js-syntax-problems">Modern JS Syntax Problems <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#modern-js-syntax-problems">&#x1f517;</a></h1>
<p>Well, mostly. You can develop just fine for a while this way, but as soon as you use optional chaining or nullish coalescing, it falls apart. (That is, the <code>.?</code> or <code>??</code> operators.)</p>
<p>You can sort of get away with it by using Typescript to convert these features into older equivalents, but
Svelte&#x2019;s TypeScript support doesn&#x2019;t currently process the template, so a component like this one will still have trouble.</p>
<pre><code class="language-svelte"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">&quot;ts&quot;</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> value;
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> defaultValue = <span class="hljs-string">&apos;N/A&apos;</span>;
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

</span><span class="javascript">{value ?? defaultValue}</span><span class="xml">
</span></code></pre>
<p>Storybook uses Webpack 4 by default, which doesn&#x2019;t support these newer JavaScript syntax features. A common solution here is to force
Webpack to use a newer version of the <code>acorn</code> dependency, which it uses for parsing JavaScript. For Storybook, this causes very strange
issues that mostly prevent Storybook from working at all.</p>
<p>A better solution is to use Webpack 5. Storybook recently gained full support for Webpack 5, so this can be enabled with just a few commands.</p>
<pre><code class="language-sh">&#x24; npm install --save-dev \
  @storybook/builder-webpack5 @storybook/manager-webpack5
</code></pre>
<p>Once the dependencies are installed, a small update to our <code>main.cjs</code> will enable it.</p>
<pre><code class="language-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">core</span>: {
    <span class="hljs-attr">builder</span>: <span class="hljs-string">&apos;webpack5&apos;</span>,
  },
  <span class="hljs-attr">svelteOptions</span>: {
    <span class="hljs-attr">preprocess</span>: preprocess(),
  },
  <span class="hljs-comment">// Rest of the configuration here</span>
};
</code></pre>
<h1 id="updating-the-webpack-configuration">Updating the Webpack Configuration <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#updating-the-webpack-configuration">&#x1f517;</a></h1>
<p>This doesn&#x2019;t quite work though. I&#x2019;ll skip all the errors but there are two things in the Webpack 5 configuration that need fixing:</p>
<ol>
<li>All files must reference the same copy of the <code>svelte</code> library to avoid the dreaded &#x201c;function called outside component initialization&#x201d; error.</li>
<li>With <code>&quot;type&quot;: &quot;module&quot;</code>, the Webpack resolver must be set to <code>fullySpecified: false</code>, so that <code>import</code> calls don&#x2019;t need to have the full file extension to work properly.</li>
</ol>
<p>Storybook allows us to add a <code>webpackFinal</code> function to our configuration to make these changes.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;path&apos;</span>);
<span class="hljs-keyword">const</span> preprocess = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;svelte-preprocess&apos;</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">core</span>: {
    <span class="hljs-attr">builder</span>: <span class="hljs-string">&apos;webpack5&apos;</span>,
  },
  <span class="hljs-attr">svelteOptions</span>: {
    <span class="hljs-attr">preprocess</span>: preprocess(),
  },
  <span class="hljs-attr">webpackFinal</span>: <span class="hljs-keyword">async</span> (config) =&gt; {
    config.resolve = {
      ...config.resolve,
      <span class="hljs-attr">alias</span>: {
        ...config.resolve.alias,
        <span class="hljs-attr">svelte</span>: path.resolve(__dirname, <span class="hljs-string">&apos;..&apos;</span>, <span class="hljs-string">&apos;node_modules&apos;</span>, <span class="hljs-string">&apos;svelte&apos;</span>),
      },
      <span class="hljs-attr">mainFields</span>: [<span class="hljs-string">&apos;svelte&apos;</span>, <span class="hljs-string">&apos;browser&apos;</span>, <span class="hljs-string">&apos;module&apos;</span>, <span class="hljs-string">&apos;main&apos;</span>],
    };

    config.module.rules.push({
      <span class="hljs-attr">resolve</span>: {
        <span class="hljs-attr">fullySpecified</span>: <span class="hljs-literal">false</span>,
        <span class="hljs-attr">extensions</span>: [<span class="hljs-string">&apos;.js&apos;</span>, <span class="hljs-string">&apos;.ts&apos;</span>],
      },
    });

    <span class="hljs-keyword">return</span> config;
  },
  <span class="hljs-comment">// Rest of the config...</span>
};
</code></pre>
<h1 id="one-last-error">One Last Error <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#one-last-error">&#x1f517;</a></h1>
<p>With all these changes, our Storybook compiles once again! But there&#x2019;s one last error that shows up when loading Storybook
in the browser. The devtools reveal the problem:</p>
<pre><code>Uncaught ReferenceError: require is not defined
    at Object../.storybook/generated-stories-entry.js (generated-stories-entry.js:3)
    at __webpack_require__ (bootstrap:24)
    at __webpack_exec__ (main.iframe.bundle.js:221)
    at main.iframe.bundle.js:222
    at Function.__webpack_require__.O (chunk loaded:23)
    at main.iframe.bundle.js:223
    at webpackJsonpCallback (jsonp chunk loading:557)
    at main.iframe.bundle.js:1
</code></pre>
<p>Some code inside Storybook&#x2019;s client also uses <code>require</code> and <code>module</code>, but when Webpack 5 sees a &#x201c;module&#x201d; type package it doesn&#x2019;t provide all that CommonJS functionality. Fortunately, we can trick Webpack a bit here.</p>
<p>By adding the file <code>.storybook/package.json</code> with just the contents <code>{}</code> (yes, an empty object), Webpack 5 won&#x2019;t see <code>&quot;type&quot;: &quot;module&quot;</code> in the <code>package.json</code> at the root of your
project, and will instead run in a module-agnostic mode. This allows files to use ES Module style <code>import</code> and <code>export</code>, but also provides <code>require</code>, <code>module</code>, and so on for CommonJS code that might need it.</p>
<h1 id="summing-it-up">Summing It Up <a class="header-anchor" href="https://imfeld.dev/writing/sveltekit_with_storybook#summing-it-up">&#x1f517;</a></h1>
<p>Finally, we have a Storybook configuration where everything works. I&#x2019;m sure that a lot of these workarounds will no longer be needed as time goes on,
but for now I hope this helps you get a working setup.</p>
<p>To recap:</p>
<ul>
<li>Rename <code>.storybook/main.js</code> to <code>.storybook/main.cjs</code>.</li>
<li>Remove references in <code>main.cjs</code> to <code>svelte.config.js</code>.</li>
<li>Use Storybook&#x2019;s webpack 5 builder.</li>
<li>Update the webpack configuration for Svelte.</li>
<li>Set <code>fullySpecified: false</code> in the resolver configuration.</li>
<li>Create <code>.storybook/package.json</code> just containing an empty object.</li>
</ul>
<p>I&#x2019;ve created <a href="https://github.com/dimfeld/svelte-storybook-workarounds">a GitHub repository with all these changes</a> so that you can pull them into your own project.</p>
]]></description><link>https://imfeld.dev/writing/sveltekit_with_storybook</link><guid isPermaLink="false">abc7a809ffcbdbf9474849d097251ab5ae87d4bf937ffa114f6a724b285f0737</guid><category><![CDATA[Svelte]]></category><pubDate>Mon, 19 Jul 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Synchronizing Rust Types with Typescript]]></title><description><![CDATA[<p>Tags: Rust, Typescript</p><p>For <a href="https://github.com/dimfeld/ergo">Ergo</a> I&#x2019;m writing the server in Rust with a front-end in Svelte and Typescript. Since Rust is a strongly-typed language, I already have accurate type definitions for each of the server&#x2019;s endpoints, and since Typescript is a mostly-strongly-typed language, I naturally would like to use those types in the front-end as well.</p>
<p>Of course, Rust and Typescript have very different syntax, so translating types between them isn&#x2019;t necessarily easy. What to do? It would work to manually update types on both ends, but this gets old fast and runs the risk of them getting out of sync.
An automatic solution is much better, and we can accomplish this using the JSON Schema format.</p>
<p>JSON Schema is a format for defining the structure of a JSON object. A schema can define the fields of an object, which are optional, the types of those fields, and more. There is a lot of tooling around JSON Schema, and so we can use it as an intermediate format between the Rust types and the Typescript types.</p>
<p>In Rust, we first start with the <a href="https://docs.rs/schemars"><code>schemars</code></a> crate, which provides a <code>JsonSchema</code> trait and a macro to derive it. Let&#x2019;s say we have a few types which
reference each other, and we want to create their analogs in the front-end Typescript code.</p>
<pre><code class="language-rust"><span class="hljs-keyword">use</span> schemars::JsonSchema;
<span class="hljs-keyword">use</span> chrono::{DateTime, Utc};

<span class="hljs-meta">#[derive(Serialize, Deserialize, JsonSchema)]</span>
<span class="hljs-meta">#[serde(rename_all = <span class="hljs-meta-string">&quot;lowercase&quot;</span>)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span></span> {
    Processing,
    Success,
    Failure,
}

<span class="hljs-meta">#[derive(JsonSchema)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ActionLog</span></span> {
    action: <span class="hljs-built_in">String</span>,
    status: Status,
    timestamp: DateTime&lt;Utc&gt;,
}

<span class="hljs-meta">#[derive(JsonSchema)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">InputLog</span></span> {
    input: <span class="hljs-built_in">String</span>,
    status: Status,
    timestamp: DateTime&lt;Utc&gt;,
    actions: <span class="hljs-built_in">Vec</span>&lt;ActionLog&gt;,
}
</code></pre>
<p><code>schemars</code> automatically detects <code>serde</code> renaming, so just as the <code>Status</code> enum&#x2019;s values will be lowercased when converting to and from JSON,
the generated JSON schema will also use lowercase values. This is almost always what you want, but <code>schemars</code> does allow you to customize renaming
in the schema if you have an unusual case.</p>
<p>The crate also provides <code>JsonSchema</code> trait implementations for some common utility packages like <code>chrono</code> and <code>smallvec</code>, so in this example the <code>DateTime</code>
type works properly.</p>
<p>Once we have our types defined, we can generate the schemas using the <code>schema_for!</code> macro.</p>
<pre><code class="language-rust"><span class="hljs-keyword">use</span> schemars::schema_for;

<span class="hljs-keyword">let</span> schema = schema_for!(ActionLog);
<span class="hljs-keyword">let</span> output = serde_json::to_string_pretty(schema).unwrap();
std::fs::write(<span class="hljs-string">&quot;action_log.json&quot;</span>, output)?;

<span class="hljs-keyword">let</span> schema = schema_for!(InputLog);
<span class="hljs-keyword">let</span> output = serde_json::to_string_pretty(schema).unwrap();
std::fs::write(<span class="hljs-string">&quot;input_log.json&quot;</span>, output)?;
</code></pre>
<p>This code can be in a subcommand of the main Rust application, or implemented as a separate binary. I also recommend writing the files
to a separate subdirectory, and the <a href="https://github.com/dimfeld/rust-types-to-typescript-example">example repository</a> does this.</p>
<p>This is the schema generated for the <code>ActionLog</code> type. Each schema file contains both the root type and any types that it references.</p>
<pre><code class="language-json">{
  <span class="hljs-attr">&quot;&#x24;schema&quot;</span>: <span class="hljs-string">&quot;http://json-schema.org/draft-07/schema#&quot;</span>,
  <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;ActionLog&quot;</span>,
  <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;object&quot;</span>,
  <span class="hljs-attr">&quot;required&quot;</span>: [
    <span class="hljs-string">&quot;action&quot;</span>,
    <span class="hljs-string">&quot;status&quot;</span>,
    <span class="hljs-string">&quot;timestamp&quot;</span>
  ],
  <span class="hljs-attr">&quot;properties&quot;</span>: {
    <span class="hljs-attr">&quot;action&quot;</span>: {
      <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;string&quot;</span>
    },
    <span class="hljs-attr">&quot;status&quot;</span>: {
      <span class="hljs-attr">&quot;&#x24;ref&quot;</span>: <span class="hljs-string">&quot;#/definitions/Status&quot;</span>
    },
    <span class="hljs-attr">&quot;timestamp&quot;</span>: {
      <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;string&quot;</span>,
      <span class="hljs-attr">&quot;format&quot;</span>: <span class="hljs-string">&quot;date-time&quot;</span>
    }
  },
  <span class="hljs-attr">&quot;definitions&quot;</span>: {
    <span class="hljs-attr">&quot;Status&quot;</span>: {
      <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;string&quot;</span>,
      <span class="hljs-attr">&quot;enum&quot;</span>: [
        <span class="hljs-string">&quot;processing&quot;</span>,
        <span class="hljs-string">&quot;success&quot;</span>,
        <span class="hljs-string">&quot;failure&quot;</span>
      ]
    }
  }
}
</code></pre>
<p>Now that we have the JSON schema files, it&#x2019;s time to generate Typescript definitions from them. The aptly-named <a href="https://github.com/bcherny/json-schema-to-typescript"><code>json-schema-to-typescript</code></a> package does the heavy lifting here.</p>
<p>While this package contains some helper functions to make it really easy to convert a JSON Schema file to Typescript, we can run into problems as we add more types. In the example above, both <code>InputLog</code> and <code>ActionLog</code> reference <code>Status</code>, and <code>InputLog</code> also references <code>ActionLog</code>.</p>
<p>These references mean that we&#x2019;ll end up writing Typescript definitions for <code>Status</code> and <code>ActionLog</code> twice, which Typescript does not like.
But with a bit of extra processing, we can avoid this problem, as demonstrated here.</p>
<div class="side-by-side">
<div class="left"><p>

First, read in all the schemas and generate type definitions for each one.
</p>
</div>
<div class="right"><pre><code class="language-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;fs/promises&apos;</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;path&apos;</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;url&apos;</span>;
<span class="hljs-keyword">import</span> { compile } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;json-schema-to-typescript&apos;</span>;

<span class="hljs-comment">// or just __dirname if running non-ES-Module Node</span>
<span class="hljs-keyword">const</span> dirname = path.dirname(url.fileURLToPath(<span class="hljs-keyword">import</span>.meta.url));

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> schemasPath = path.join(dirname, <span class="hljs-string">&apos;..&apos;</span>, <span class="hljs-string">&apos;schemas&apos;</span>);
  <span class="hljs-keyword">let</span> schemaFiles = (<span class="hljs-keyword">await</span> fs.readdir(schemasPath)).filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x.endsWith(<span class="hljs-string">&apos;.json&apos;</span>));

  <span class="hljs-keyword">let</span> compiledTypes = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> filename <span class="hljs-keyword">of</span> schemaFiles) {
    <span class="hljs-keyword">let</span> filePath = path.join(schemasPath, filename);
    <span class="hljs-keyword">let</span> schema = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-keyword">await</span> fs.readFile(filePath));
    <span class="hljs-keyword">let</span> compiled = <span class="hljs-keyword">await</span> compile(schema, schema.title, { <span class="hljs-attr">bannerComment</span>: <span class="hljs-string">&apos;&apos;</span> });
</code></pre>
</div>
<div class="left"><p>

Next, split on the word &#x201c;export&#x201d; to get each individual type on its own. This is kind of a hack but it&#x2019;s the easiest way to go about it without modifying the generator package itself or doing actual parsing. We add each type definition to a <code>Set</code> to ensure that each type will only be written once.
</p>
</div>
<div class="right"><pre><code class="language-javascript">    <span class="hljs-keyword">let</span> eachType = compiled.split(<span class="hljs-string">&apos;export&apos;</span>);
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> type <span class="hljs-keyword">of</span> eachType) {
      <span class="hljs-keyword">if</span> (!type) {
        <span class="hljs-keyword">continue</span>;
      }
      compiledTypes.add(<span class="hljs-string">&apos;export &apos;</span> + type.trim());
    }
  }
</code></pre>
</div>
<div class="left"><p>

Finally, we write the contents of the <code>Set</code> out to a file. I&#x2019;ve added an extra check to skip the write if the output matches the existing file to prevent web bundles from thinking something changed if it didn&#x2019;t actually change. This is an inefficient way to implement such a check but with the number of types I&#x2019;m working with the performance impact is negligible.
</p>
</div>
<div class="right"><pre><code class="language-javascript">  <span class="hljs-keyword">let</span> output = <span class="hljs-built_in">Array</span>.from(compiledTypes).join(<span class="hljs-string">&apos;\n\n&apos;</span>);
  <span class="hljs-keyword">let</span> outputPath = path.join(dirname, <span class="hljs-string">&apos;src&apos;</span>, <span class="hljs-string">&apos;api_types.ts&apos;</span>);

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> existing = <span class="hljs-keyword">await</span> fs.readFile(outputPath);
    <span class="hljs-keyword">if</span> (existing == output) {
      <span class="hljs-comment">// Skip writing if it hasn&apos;t changed, so that we don&apos;t confuse any sort</span>
      <span class="hljs-comment">// of incremental builds. This check isn&apos;t ideal but the script runs</span>
      <span class="hljs-comment">// quickly enough and rarely enough that it doesn&apos;t matter.</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;Schemas are up to date&apos;</span>);
      <span class="hljs-keyword">return</span>;
    }
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-comment">// It&apos;s fine if there&apos;s no output from a previous run.</span>
    <span class="hljs-keyword">if</span> (e.code !== <span class="hljs-string">&apos;ENOENT&apos;</span>) {
      <span class="hljs-keyword">throw</span> e;
    }
  }

  <span class="hljs-keyword">await</span> fs.writeFile(outputPath, output);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Wrote Typescript types to <span class="hljs-subst">&#x24;{outputPath}</span>`</span>);
}

main().catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(e);
  process.exit(<span class="hljs-number">1</span>);
});
</code></pre>
</div></div>
<p>So far I&#x2019;ve just been writing all the types into a single file named <code>api_types.ts</code>. This keeps things simple since it avoids any need to ensure that files properly reference each other&#x2019;s types, but a larger application may need a smarter solution.</p>
<p>The output looks like any other Typescript type definitions, except for the additional <code>[k: string]: unknown</code> which ensures that the object doesn&#x2019;t have any extra keys. I don&#x2019;t think the <code>json-schema-to-typescript</code> package
offers a way to omit this right now, but it could be filtered out when processing the text in the script above if you want.</p>
<pre><code class="language-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> Status = <span class="hljs-string">&quot;processing&quot;</span> | <span class="hljs-string">&quot;success&quot;</span> | <span class="hljs-string">&quot;failure&quot;</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> ActionLog {
  <span class="hljs-attr">action</span>: <span class="hljs-built_in">string</span>;
  status: Status;
  timestamp: <span class="hljs-built_in">string</span>;
  [k: <span class="hljs-built_in">string</span>]: unknown;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> InputLog {
  <span class="hljs-attr">actions</span>: ActionLog[];
  input: <span class="hljs-built_in">string</span>;
  status: Status;
  timestamp: <span class="hljs-built_in">string</span>;
  [k: <span class="hljs-built_in">string</span>]: unknown;
}
</code></pre>
<p>And one last step: automate it. We can put these commands into our package.json and then use the cargo watch command to rerun the entire process any time a Rust file changes. If you don&#x2019;t have the <code>cargo watch</code> command, you can get it via <code>cargo install cargo-watch</code>.</p>
<pre><code class="language-json"><span class="hljs-comment">// front-end package.json</span>
{
  <span class="hljs-attr">&quot;name&quot;</span>: <span class="hljs-string">&quot;web&quot;</span>,
  <span class="hljs-attr">&quot;...&quot;</span>: <span class="hljs-string">&quot;other values...&quot;</span>,
  <span class="hljs-attr">&quot;scripts&quot;</span>: {
    <span class="hljs-attr">&quot;dev&quot;</span>: <span class="hljs-string">&quot;run-p dev:server dev:web&quot;</span>,
    <span class="hljs-attr">&quot;dev:web&quot;</span>: <span class="hljs-string">&quot;a command that would run Vite, Snowpack, Webpack, etc.&quot;</span>,
    <span class="hljs-attr">&quot;dev:server&quot;</span>: <span class="hljs-string">&quot;cargo watch --ignore web -s &apos;cd web &amp;&amp; npm run generate-api-types&apos;&quot;</span>,
    <span class="hljs-attr">&quot;generate-api-types&quot;</span>: <span class="hljs-string">&quot;cargo run --release &amp;&amp; node generate_api_types.js&quot;</span>
  },
  <span class="hljs-attr">&quot;devDependencies&quot;</span>: {
    <span class="hljs-attr">&quot;json-schema-to-typescript&quot;</span>: <span class="hljs-string">&quot;~10.1.4&quot;</span>,
    <span class="hljs-attr">&quot;npm-run-all&quot;</span>: <span class="hljs-string">&quot;~4.1.5&quot;</span>,
    <span class="hljs-attr">&quot;typescript&quot;</span>: <span class="hljs-string">&quot;~4.3.5&quot;</span>
  } 
}
</code></pre>
<p>I have an example Git repository that does this type generation at <a href="https://github.com/dimfeld/rust-types-to-typescript-example">https://github.com/dimfeld/rust-types-to-typescript-example</a>.</p>
]]></description><link>https://imfeld.dev/writing/generating_typescript_types_from_rust</link><guid isPermaLink="false">73776593696fb300fd50e2d7de968db763b1cb71a280e02761d629bddf65c59d</guid><category><![CDATA[Rust]]></category><category><![CDATA[Typescript]]></category><pubDate>Mon, 12 Jul 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Streaming S3 Uploads in Rust]]></title><description><![CDATA[<p>Tags: Rust</p><aside class="note"><p>Since I wrote this, InfluxDB has created the <a href="https://docs.rs/object_store/latest/object_store/">object_store</a> crate and donated it to the Apache Arrow project. It does
everything mentioned here and more, so I would recommend just using that for your future projects.</p>
</aside><p>Amazon&#x2019;s S3 API makes it easy to upload large files, but it gets harder with dynamically generated data since S3 wants to know up front how much data you&#x2019;re going to upload, and you might not know that until you&#x2019;re done generating it. This might occur when streaming data from some other source or recording live media, for example.</p>
<p>The multipart upload API fixes this somewhat &#x2013; you still have to know the size of each part as you upload it, but you can have up to 10,000 parts and you don&#x2019;t have to know in advance how many parts you will upload. The one complication with the multipart API is that each part must be at least 5MB.</p>
<p>With this in mind, streaming data to the multipart upload API involves gathering data buffers as they are generated and periodically uploading the accumulated data as a new S3 part when it reaches a certain threshold size, while also making sure to honor the minimum part size.</p>
<p>Let&#x2019;s look at some scenarios with a threshold size of 50MB. In all these cases, the uploader receives a stream of byte chunks, which it groups into S3 parts of approximately the threshold size.</p>
<ul>
<li>The total amount of data is 75MB. The first 50MB gets uploaded as a part and the last 25MB is uploaded as the second part.</li>
<li>The total amount of data is 120 MB. Similar, with two 50MB parts and one 20MB part.</li>
<li>The total amount of data is 30MB. In this case we don&#x2019;t hit the threshold, so the easiest thing to do is just skip the multipart upload process and do a single put operation instead.</li>
<li>The total amount of data is 3MB. As in the above case, the stream ends and we haven&#x2019;t yet uploaded any parts, so we just do a standard &#x201c;put object&#x201d; request, which doesn&#x2019;t have the 5MB minimum size that multipart uploads enforce.</li>
<li>The total amount of data is 102MB, so we have two 50MB parts and one 2MB part. But parts must be at least 5 MB. Uh oh&#x2026;</li>
</ul>
<aside class="note"><p>A couple readers pointed out that the S3 multipart upload API does allow the <em>final</em> part to be less than 5 MB, and <a href="https://twitter.com/0x138">Ian O&#x2019;Connell</a> on Twitter was kind
enough to put together a working example of successfully uploading multipart objects with with a small final part. I suspect my initial attempt at writing this code had
some other sort of bug that also disappeared when I refactored it to account for small part sizes.</p>
<p>This means that the extra work to check for minimum part size is not needed in this code. I&#x2019;ve left the code itself unchanged in case you find the buffer splitting techniques
useful for some other context.</p>
</aside><p>We can&#x2019;t predict that the last part will be only 2MB, so we have to maintain some reserve to make sure that we&#x2019;ll always have 5MB of data waiting to upload. The algorithm looks roughly like this:</p>
<ol>
<li>Receive data buffers from the stream and save them into a list.</li>
<li>If the amount of data accumulated is less than 50MB, go back to step 1.</li>
<li>Remove buffers from the list, keeping just enough buffers so that there is at least 5MB (the minimum part size) remaining.</li>
<li>Start a new multipart upload if it hasn&#x2019;t been started yet.</li>
<li>Upload the removed buffers to S3 as a new part.</li>
</ol>
<p>When the stream ends, you send all the remaining buffers to S3 as another part, and since you made sure to always keep 5MB of data in reserve, the last part will always be at least that large, regardless of how much data actually came in.</p>
<p>So in our 122MB example, the first two parts will be the threshold size (50MB) minus 5MB, and the final part will contain the remaining data. This comes out to approximately 45MB, 45MB, and 12MB.</p>
<p>This mostly works, but can still fall apart if an especially large buffer arrives, such as if the stream includes a 52MB buffer. This one buffer is above the threshold size, so it&#x2019;s enough to trigger an upload, but removing it from the list could leave less than 5MB reserved.</p>
<p>The solution is to split the buffer. We send 47MB to S3 while leaving 5MB left in our buffer list to maintain the minimum reserve requirement. Fortunately, the Rust <code>bytes</code> crate allows splitting buffers like this via an internally-maintained reference count, so we don&#x2019;t have to copy all that data around more than necessary. (As noted in the callout above, this turns out to not be necessary.)</p>
<p>With the algorithm figured out, let&#x2019;s take a look at the code.</p>
<div class="side-by-side">
<div class="left"></div>
<div class="right"><pre><code class="language-rust"><span class="hljs-keyword">use</span> crate::Error; <span class="hljs-comment">// An error defined elsewhere with `thiserror`</span>
<span class="hljs-keyword">use</span> anyhow::anyhow;
<span class="hljs-keyword">use</span> bytes::Bytes;
<span class="hljs-keyword">use</span> std::collections::VecDeque;
<span class="hljs-keyword">use</span> tokio::task::JoinHandle;

<span class="hljs-comment">/// Buffer 50MB per upload part. S3 allows up to 10000 parts which gives us a total</span>
<span class="hljs-comment">/// limit of 500GB per file.</span>
<span class="hljs-keyword">const</span> BUFFER_LIMIT: <span class="hljs-built_in">usize</span> = <span class="hljs-number">50</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
<span class="hljs-keyword">const</span> MIN_PART_SIZE: <span class="hljs-built_in">usize</span> = <span class="hljs-number">5</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">run_upload</span></span>(
    client: rusoto_s3::S3Client,
    bucket: <span class="hljs-built_in">String</span>,
    key: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">mut</span> source: <span class="hljs-keyword">impl</span> Stream&lt;Item=<span class="hljs-built_in">Result</span>&lt;Bytes, Error&gt;&gt;,
) -&gt; <span class="hljs-built_in">Result</span>&lt;(), (<span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;, Error)&gt; {
    <span class="hljs-comment">// The ID of the multipart upload, once we start it.</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> upload_id: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt; = <span class="hljs-literal">None</span>;
    <span class="hljs-comment">// A list of uploaded parts, needed when we complete the upload</span>
    <span class="hljs-comment">// at the end.</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> uploaded_parts = <span class="hljs-built_in">Vec</span>::new();
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> part_number = <span class="hljs-number">1</span>;
    <span class="hljs-comment">// Buffers waiting to be uploaded.</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> buffers = VecDeque::new();
    <span class="hljs-comment">// The total number of bytes stored in `buffers`.</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> outstanding_data = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">loop</span> {
</code></pre>
</div>
<div class="left"><p>

Pull buffers out of the stream until we&#x2019;ve accumulated at least <code>BUFFER_LIMIT</code> bytes.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">while</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(data) = source.recv().<span class="hljs-keyword">await</span> {
            <span class="hljs-keyword">let</span> data = data.map_err(|e| (upload_id.clone(), e))?;
            outstanding_data += data.len();
            buffers.push_back(data);

            <span class="hljs-keyword">if</span> outstanding_data &gt;= BUFFER_LIMIT {
                <span class="hljs-keyword">break</span>;
            }
        }

</code></pre>
</div>
<div class="left"><p>

If the stream ended and we also have no more buffers waiting, then we&#x2019;re done.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">if</span> buffers.len() == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// No more data.</span>
            <span class="hljs-keyword">break</span>;
        }

</code></pre>
</div>
<div class="left"><p>

To upload a part, we first need to get the ID for the multipart upload, or start the
multipart upload if we haven&#x2019;t done so yet.
</p>

<p>

If the stream ended before we could start the multipart upload, then we call <code>simple_upload</code> (see below)
to just upload our data with the normal S3 &#x201c;put object&#x201d; API.
</p>

<p>

If not, then we call the S3 API to create a new multipart upload.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">let</span> stream_ended = outstanding_data &lt; BUFFER_LIMIT;

        <span class="hljs-keyword">let</span> current_upload_id = <span class="hljs-keyword">match</span> &amp;upload_id {
            <span class="hljs-literal">Some</span>(u) =&gt; u.clone(),
            <span class="hljs-literal">None</span> =&gt; {
                <span class="hljs-keyword">if</span> stream_ended {
                    <span class="hljs-comment">// The stream ended before we started the</span>
                    <span class="hljs-comment">// multipart upload so just do a simple upload.</span>
                    <span class="hljs-keyword">return</span> simple_upload(client, bucket, object,
                            buffers, outstanding_data)
                        .<span class="hljs-keyword">await</span>
                        .map_err(|e| (<span class="hljs-literal">None</span>, e));
                }

                <span class="hljs-keyword">let</span> create_request = rusoto_s3::CreateMultipartUploadRequest {
                    bucket: bucket.clone(),
                    key: key.clone(),
                    ..<span class="hljs-built_in">Default</span>::default()
                };
                <span class="hljs-keyword">let</span> upload = client
                    .create_multipart_upload(create_request)
                    .<span class="hljs-keyword">await</span>
                    .map_err(|e| {
                        (
                            <span class="hljs-literal">None</span>,
                            Error::WriteError {
                                bucket: bucket.clone(),
                                key: key.clone(),
                                source: e.into(),
                            },
                        )
                    })?;
                <span class="hljs-keyword">let</span> id = upload.upload_id.unwrap();
                upload_id = <span class="hljs-literal">Some</span>(id.clone());
                id
            }
        };

</code></pre>
</div>
<div class="left"><p>

Next, we put together a list of buffers to send in this part.
</p>

<p>

If the stream has ended, then this is all the buffers we have.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">let</span> (this_part_buffers, this_part_size) = <span class="hljs-keyword">if</span> stream_ended {
            <span class="hljs-comment">// Just move everything into the buffer</span>
            <span class="hljs-keyword">let</span> bufs = buffers.drain(..).collect::&lt;<span class="hljs-built_in">Vec</span>&lt;_&gt;&gt;();
            <span class="hljs-keyword">let</span> this_part_size = outstanding_data;
            outstanding_data = <span class="hljs-number">0</span>;
            (bufs, this_part_size)
        } <span class="hljs-keyword">else</span> {
</code></pre>
</div>
<div class="left"><p>

If the stream hasn&#x2019;t ended, then this isn&#x2019;t the final part.
</p>

<p>

Get buffers from the list, making sure to leave at least 5MB worth so that we are guaranteed to have
enough data to upload the final part.
</p>
</div>
<div class="right"><pre><code class="language-rust">            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> this_part_buffers = <span class="hljs-built_in">Vec</span>::new();
            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> this_part_size = <span class="hljs-number">0</span>;
            <span class="hljs-keyword">while</span> outstanding_data - buffers.front().map(|b| b.len()).unwrap_or(<span class="hljs-number">0</span>) &gt; MIN_PART_SIZE {
                <span class="hljs-keyword">let</span> buffer = buffers.pop_front().unwrap();
                this_part_size += buffer.len();
                outstanding_data -= buffer.len();
                this_part_buffers.push(buffer);
            }

</code></pre>
</div>
<div class="left"><p>

Handle the buffer-splitting case. This happens if the next buffer in the list is large enough that pulling it off would leave
less than 5MB reserved, but we also haven&#x2019;t
read enough data for the current part to be large enough.
</p>

<p>

As mentioned above, this turns out to not be necessary, but I&#x2019;ve left it here
for reference in case you find the technique useful elsewhere.
</p>
</div>
<div class="right"><pre><code class="language-rust">            <span class="hljs-keyword">if</span> this_part_size &lt; MIN_PART_SIZE {
                <span class="hljs-keyword">let</span> buffer = buffers.front_mut().unwrap();
                <span class="hljs-keyword">let</span> write_buffer = buffer.split_to(MIN_PART_SIZE - this_part_size);
                this_part_size += write_buffer.len();
                outstanding_data -= write_buffer.len();
                this_part_buffers.push(write_buffer);
            }

            (this_part_buffers, this_part_size)
        };

</code></pre>
</div>
<div class="left"><p>

A quick consistency check to make sure that we did things right.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">let</span> actual_part_sizes = this_part_buffers
            .iter()
            .map(|b| b.len())
            .sum::&lt;<span class="hljs-built_in">usize</span>&gt;();

        <span class="hljs-keyword">if</span> actual_part_sizes != this_part_size {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>((
                upload_id.clone(),
                Error::WriteError {
                    bucket: bucket.clone(),
                    key: key.clone(),
                    source: anyhow!(
                        <span class="hljs-string">&quot;Had size {} but calculated size {}&quot;</span>,
                        actual_part_sizes,
                        this_part_size
                    ),
                },
            ));
        }
</code></pre>
</div>
<div class="left"><p>

And now we&#x2019;re ready to upload a part. This is done with a retry function since S3
will occasionally return a transient error during an upload.
</p>
</div>
<div class="right"><pre><code class="language-rust">        <span class="hljs-keyword">let</span> uploaded_part = retry_with_data(
                this_part_buffers, |buffers| {

            <span class="hljs-keyword">let</span> client = client.clone();
            <span class="hljs-keyword">let</span> bucket = bucket.clone();
            <span class="hljs-keyword">let</span> key = key.clone();
            <span class="hljs-keyword">let</span> current_upload_id = current_upload_id.clone();
            <span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">let</span> bytes_stream = futures::stream::iter(buffers);
                <span class="hljs-keyword">let</span> req = rusoto_s3::UploadPartRequest {
                    bucket,
                    key,
                    upload_id: current_upload_id,
                    content_length: <span class="hljs-literal">Some</span>(this_part_size <span class="hljs-keyword">as</span> <span class="hljs-built_in">i64</span>),
                    part_number,
                    body: <span class="hljs-literal">Some</span>(rusoto_core::ByteStream::new(bytes_stream)),
                    ..<span class="hljs-built_in">Default</span>::default()
                };
                client.upload_part(req).<span class="hljs-keyword">await</span>
            }
        })
        .<span class="hljs-keyword">await</span>
        .map_err(|e| {
            (
                upload_id.clone(),
                Error::WriteError {
                    bucket: bucket.clone(),
                    key: key.clone(),
                    source: e.into(),
                },
            )
        })?;

</code></pre>
</div>
<div class="left"><p>

S3 returns an <code>e_tag</code> for the part, which we&#x2019;ll need later.
</p>
</div>
<div class="right"><pre><code class="language-rust">        uploaded_parts.push(rusoto_s3::CompletedPart {
            part_number: <span class="hljs-literal">Some</span>(part_number),
            e_tag: uploaded_part.e_tag,
        });

        part_number += <span class="hljs-number">1</span>;
    }

</code></pre>
</div>
<div class="left"><p>

Here we&#x2019;re done with our loop, so we just send a &#x201c;complete upload&#x201d; request to finish things off.
</p>
</div>
<div class="right"><pre><code class="language-rust">    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(upload_id) = upload_id {
        <span class="hljs-keyword">let</span> upload_summary = rusoto_s3::CompletedMultipartUpload {
            parts: <span class="hljs-literal">Some</span>(uploaded_parts),
        };

        <span class="hljs-keyword">let</span> complete_request = rusoto_s3::CompleteMultipartUploadRequest {
            upload_id: upload_id.clone(),
            bucket: bucket.clone(),
            key: key.clone(),
            multipart_upload: <span class="hljs-literal">Some</span>(upload_summary),
            ..<span class="hljs-built_in">Default</span>::default()
        };

        client
            .complete_multipart_upload(complete_request)
            .<span class="hljs-keyword">await</span>
            .map_err(|e| {
                (
                    <span class="hljs-literal">Some</span>(upload_id),
                    Error::WriteError {
                        bucket,
                        key,
                        source: e.into(),
                    },
                )
            })?;
    }

    <span class="hljs-literal">Ok</span>(())
}

</code></pre>
</div>
<div class="left"><p>

And here is the other function used when we ended up with just a small amount of data. It does a single
&#x201c;put object&#x201d; call to upload the data all at once.
</p>
</div>
<div class="right"><pre><code class="language-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">simple_upload</span></span>(
    client: S3Client,
    bucket: <span class="hljs-built_in">String</span>,
    key: <span class="hljs-built_in">String</span>,
    buffers: VecDeque&lt;Bytes&gt;,
    total_length: <span class="hljs-built_in">usize</span>,
) -&gt; <span class="hljs-built_in">Result</span>&lt;()&gt; {
    <span class="hljs-keyword">let</span> buffers = buffers.into_iter().collect::&lt;<span class="hljs-built_in">Vec</span>&lt;_&gt;&gt;();
    retry_with_data(buffers, |data| {
        <span class="hljs-keyword">let</span> client = client.clone();
        <span class="hljs-keyword">let</span> bucket = bucket.clone();
        <span class="hljs-keyword">let</span> key = key.clone();
        <span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
            <span class="hljs-keyword">let</span> request = rusoto_s3::PutObjectRequest {
                bucket,
                key,
                body: <span class="hljs-literal">Some</span>(rusoto_core::ByteStream::new(futures::stream::iter(data))),
                content_length: <span class="hljs-literal">Some</span>(total_length <span class="hljs-keyword">as</span> <span class="hljs-built_in">i64</span>),
                ..<span class="hljs-built_in">Default</span>::default()
            };

            client.put_object(request).<span class="hljs-keyword">await</span>
        }
    })
    .<span class="hljs-keyword">await</span>
    .map_err(|e| Error::WriteError {
        bucket,
        key,
        source: e.into(),
    })?;

    <span class="hljs-literal">Ok</span>(())
}

</code></pre>
</div>
<div class="left"><p>

Finally, the function that runs the upload. This both starts a new task in the Tokio runtime to handle the
upload, and handles aborting the upload in case of an error.
</p>
</div>
<div class="right"><pre><code class="language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">start_upload_task</span></span>(
        client: rusoto_s3::Client,
        bucket: <span class="hljs-built_in">String</span>,
        key: <span class="hljs-built_in">String</span>,
        source: <span class="hljs-keyword">impl</span> Stream&lt;Item=<span class="hljs-built_in">Result</span>&lt;Bytes, std::io::Error&gt;&gt;
    ) -&gt; JoinHandle&lt;anyhow::<span class="hljs-built_in">Result</span>&lt;()&gt;&gt; {

    tokio::task::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
        <span class="hljs-keyword">let</span> result = run_upload(client.clone(), bucket, key, source).<span class="hljs-keyword">await</span>;
        <span class="hljs-keyword">match</span> result {
            <span class="hljs-literal">Ok</span>(_) =&gt; <span class="hljs-literal">Ok</span>(()),
            <span class="hljs-literal">Err</span>((upload_id, e)) =&gt; {
                <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(upload_id) = upload_id {
                    <span class="hljs-keyword">let</span> cancel_request = rusoto_s3::AbortMultipartUploadRequest {
                        bucket: bucket.clone(),
                        key: key.clone(),
                        upload_id,
                        ..<span class="hljs-built_in">Default</span>::default()
                    };

                    client.abort_multipart_upload(cancel_request).<span class="hljs-keyword">await</span>.ok();
                }
                <span class="hljs-literal">Err</span>(e)
            }
        }
    })
}
</code></pre>
</div></div>
<p>S3 will keep uploaded parts from an unfinished multipart upload around forever if it is not explicitly aborted and the S3 bucket, so it&#x2019;s important to handle that.</p>
<p>Buckets can also have lifecycle rules to purge unfinished uploads after a certain amount of time. This is also advisable in case the abort request doesn&#x2019;t reach S3 for some reason.</p>
]]></description><link>https://imfeld.dev/writing/rust_s3_streaming_upload</link><guid isPermaLink="false">837b1a420920ae0eaef338e19450914b4ef4effff9a6c44bc3e960d8c2062df9</guid><category><![CDATA[Rust]]></category><pubDate>Mon, 28 Jun 2021 00:00:00 GMT</pubDate></item><item><title><![CDATA[Reducing Big Data Shuffle by Substituting Integers for Strings]]></title><description><![CDATA[<p>Tags: SQL</p><p>Recently I was working on a BigQuery job that reads in 2.6 billion rows, finds relationships between them, runs some <code>GROUP BY</code> statements, and generates 20 billion rows from that. This was too much for BigQuery, which cancelled the job with this error:</p>
<pre><code>Resources exceeded during query execution: Your project or organization exceeded the maximum disk and memory limit available for shuffle operations. Consider provisioning more slots, reducing query concurrency, or using more efficient logic in this job.
</code></pre>
<p>The really painful part of trying to work around this is that it took about 20 minutes for the query to fail each time. And &#x201c;provisioning more slots&#x201d; is shorthand for paying Google a bunch of money. After various attempts to massage the query into a form that BigQuery would run, I finally came upon the solution.</p>
<p>Two of the columns in this data are extremely long strings, 64 and 128 characters respectively, and I had to use both of them as <code>GROUP BY</code> keys at different points in the query. Behind the scenes, a distributed <code>GROUP BY</code> requires moving all the data for a set of grouping keys to the same set of processing nodes. This is called a &#x201c;shuffle&#x201d; or a &#x201c;repartition,&#x201d; and with this much data we&#x2019;re talking multiple TB of data moving around the system.</p>
<p><img src="https://imfeld.dev/images/bq-shuffle-bytes.png" alt="Lots of bytes shuffled"></p>
<p>Of course (in retrospect), the best way to reduce the data to be shuffled around is not to rearrange the queries, but to reduce the amount of data there is. And while a string takes up one byte per ASCII character plus two bytes to track the length, a 64-bit integer is always just 64 bits.</p>
<p>Using integers instead of strings saves 58 and 122 bytes per column for the two fields, a huge reduction. And indeed this was the solution to getting the query to run. The conversion looks something like this.</p>
<pre><code class="language-sql"><span class="hljs-keyword">WITH</span>
claim_numbers <span class="hljs-keyword">AS</span> (
  <span class="hljs-comment">-- Assign a number to each claim.</span>
  <span class="hljs-keyword">SELECT</span> ROW_NUMBER() <span class="hljs-keyword">OVER</span> () <span class="hljs-keyword">AS</span> <span class="hljs-keyword">id</span>, claim_id
  <span class="hljs-keyword">FROM</span> claims_table
  <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> claim_id
),
patient_numbers <span class="hljs-keyword">AS</span> (
  <span class="hljs-comment">-- Assign a number to each patient.</span>
  <span class="hljs-keyword">SELECT</span> ROW_NUMBER() <span class="hljs-keyword">OVER</span> () <span class="hljs-keyword">AS</span> <span class="hljs-keyword">id</span>, patient_id
  <span class="hljs-keyword">FROM</span> claims_table
  <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> patient_id
),
claims <span class="hljs-keyword">AS</span> (
  <span class="hljs-comment">-- Substitutes the integers</span>
  <span class="hljs-keyword">SELECT</span> cn.id <span class="hljs-keyword">AS</span> claim_id, pn.id <span class="hljs-keyword">AS</span> patient_id, other_columns
  <span class="hljs-keyword">FROM</span> claims_table
  <span class="hljs-keyword">JOIN</span> claim_numbers cn <span class="hljs-keyword">USING</span>(claim_id)
  <span class="hljs-keyword">JOIN</span> patient_numbers pn <span class="hljs-keyword">USING</span>(patient_id)
),
other_ctes <span class="hljs-keyword">AS</span> (...)
<span class="hljs-comment">-- And then you can join on claim_numbers and patient_numbers again</span>
<span class="hljs-comment">-- if you need to restore the strings.</span>
</code></pre>
<p>Not only does this technique work well for reducing shuffling, but it also speeds up large queries a lot too.</p>
<p>Sometimes, though, this doesn&#x2019;t quite work. Depending on how the data is read, Bigquery may fail in the <code>ROW_NUMBER</code> calculation with an error like this:</p>
<pre><code>Resources exceeded during query execution:
The query could not be executed in the allotted memory.
Peak usage: 158% of limit.
Top memory consumer(s): analytic OVER() clauses: 100%
</code></pre>
<p>The <code>OVER</code> clause requires Bigquery to run the entire dataset through a single processing node, which can require more RAM than the node has. But there&#x2019;s another trick we can use.</p>
<p>If we partition the dataset by some other key that correlates with the ID, then each of those partitions can run through a different node and we can avoid RAM issues. In my case, there was a <code>patient_geo</code> column which represents roughly where each patient is from.</p>
<pre><code class="language-sql"><span class="hljs-keyword">SELECT</span> patient_id,
  ROW_NUMBER() <span class="hljs-keyword">OVER</span>(<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">MAX</span>(patient_geo)) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">id</span>
<span class="hljs-keyword">FROM</span> claims
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> patient_id
</code></pre>
<p>This works, but now we have duplicate IDs! Each partition ends up with its own set of IDs, and they overlap with each other. So we need one last adjustment.</p>
<p>Since each partition is based on the <code>patient_geo</code> column, we can integrate that into our id as well to avoid overlap. The output is a 64-bit integer, which gives us plenty of space. We know there will never be more than 100 billion patients, and so for each column, we multiply <code>patient_geo</code> by 100 billion and add it to the <code>ROW_NUMBER</code> for each row. A bit shift would work here too, but it doesn&#x2019;t really matter.</p>
<pre><code class="language-sql"> <span class="hljs-keyword">SELECT</span> patient_id,
	<span class="hljs-comment">-- We know there will never be more than 100 billion patients,</span>
    <span class="hljs-comment">-- so shift the partition key up by that much.</span>
	(<span class="hljs-keyword">MAX</span>(patient_geo) * <span class="hljs-number">100000000000</span>)
    	+ ROW_NUMBER()
          <span class="hljs-keyword">OVER</span>(<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">MAX</span>(patient_geo)) <span class="hljs-keyword">AS</span> <span class="hljs-keyword">id</span>
  <span class="hljs-keyword">FROM</span> claims
  <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> patient_id
</code></pre>
<p>And there we go! As before, at the end of the query you can join on these results again to convert the numeric IDs back into real IDs, if necessary.</p>
<p>I don&#x2019;t recommend doing this if you don&#x2019;t have to. It does add some amount of complexity to the query, but it can be a lifesaver in cases where your SQL engine is running into issues.</p>
]]></description><link>https://imfeld.dev/writing/big_data_shuffle</link><guid isPermaLink="false">7368d72f2b268fcecb18c33425248ea46604e11897690ab7c6be0cecdfdc3063</guid><category><![CDATA[SQL]]></category><pubDate>Mon, 21 Jun 2021 00:00:00 GMT</pubDate></item></channel></rss>