{"version":"https:\/\/jsonfeed.org\/version\/1.1","title":"Will Richardson","home_page_url":"https:\/\/willhbr.net\/","feed_url":"https:\/\/willhbr.net\/feed.json","description":"Computers, photography, and related matters.","icon":"https:\/\/willhbr.net\/apple-touch-icon.png","favicon":"https:\/\/willhbr.net\/favicon.ico","expired":false,"language":"en","items":[{"id":"https:\/\/willhbr.net\/2026\/11\/23\/so-you-want-to-build-a-homelab\/","title":"So You Want to Build a Homelab","content_html":"<p>Last week I was talking to someone about cancelling my music streaming subscription and instead <a href=\"\/2026\/09\/28\/owning-my-streaming-with-navidrome\/\">hosting my own streaming service<\/a> of music that I\u2019d bought. They wanted to know how it all fit together, and quickly I was explaining how I\u2019d actually just <a href=\"\/2026\/10\/11\/inevitably-nixos\/\">swapped to use NixOS<\/a> and how setting up Navidrome was easy because <a href=\"https:\/\/codeberg.org\/willhbr\/endash\">my container dashboard<\/a> can autoconfigure the reverse proxy, so I don\u2019t have to set that up separately.<\/p>\n\n<p>That is all very well and good for me, but what if you\u2019re a little more normal, and want to run a home server?<sup id=\"fnref:as-normal-as-can-be\"><a href=\"#fn:as-normal-as-can-be\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup><\/p>\n\n<h1 id=\"hardware\">Hardware<\/h1>\n\n<p>The best hardware is whatever you\u2019ve already got. Whether that\u2019s an old laptop or a Raspberry Pi that you were totally going to use for some project, it\u2019s best to reuse instead of going out to buy something.<\/p>\n\n<p>If you don\u2019t have anything at hand, my recommendation is to get a second-hand small form-factor computer. Usually if you search for \u201cmini PC\u201d you\u2019ll find them. It\u2019s basically the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Next_Unit_of_Computing\">Intel NUC<\/a> and derivatives. Typically there is a steady supply of these coming from businesses that are upgrading and looking to get rid of their old stock. In 2026 the typical spec I\u2019d expect to see is 8GB of memory, a 250GB SSD, and a 5-ish-year-old processor, for about $150.<\/p>\n\n<p>I always look for computers that have a CPU with a 15W <a href=\"https:\/\/en.wikipedia.org\/wiki\/Thermal_design_power\">TDP<\/a>, which is basically the CPUs with the lowest power consumption, typically reserved for laptops, but often found in these mini PCs. This gives me a little bit of confidence that if the airflow isn\u2019t perfect, it\u2019s unlikely to make enough heat to damage itself, and leaving it running all the time isn\u2019t going to have a huge impact on my energy bill.<\/p>\n\n<p>The important thing to keep in mind here is that almost everything you might do on this machine can be done with a fairly low-end or old CPU.<\/p>\n\n<p>The exception is if you want to transcode video on the fly, either to reduce the data sent over the network or because a device can\u2019t play back a certain format. This will need more CPU (or GPU) power, and some formats rely on specific hardware to be decoded efficiently.<\/p>\n\n<p>My advice here: don\u2019t get into a situation where you need to transcode video. Make sure any media you get is small enough to stream over your network. This usually isn\u2019t a problem as long as all your devices are connected to your home wifi. Additionally, only get media that can be played back natively on your devices, so that the server can act as a simple file server, instead of doing compute-intensive work trying to transcode the video.<\/p>\n\n<p>One limitation that I would put on any hardware I use would be that it must have ethernet. Not for the speed, but for the fact that when the cable is plugged in, the computer will connect with basically no additional config. This makes any debugging so much easier.<\/p>\n\n<p>If you get a mini PC with 250GB of storage, that will probably be enough for music streaming, but if you want to store video, that\u2019ll fill up fast. Most mini PCs don\u2019t have space for extra drives, and replacing the <a href=\"https:\/\/en.wikipedia.org\/wiki\/M.2\">M.2<\/a> SSD with a larger capacity one will probably cost more than the machine did.<\/p>\n\n<p>External hard drive enclosures are a simple way to get more storage for a machine with no other expansion. USB 3 is more than fast enough to not be a bottleneck with an HDD. Even with an SSD, it\u2019s unlikely that you\u2019ll notice a speed difference. I\u2019d try and get a bus powered one (that gets its power over USB, instead of a separate power supply) as it\u2019s less bulk and fewer cables to manage.<\/p>\n\n<h1 id=\"operating-system\">Operating System<\/h1>\n\n<p>Obviously it should be Linux, managing Windows or MacOS on a server would be a pain, and I\u2019m too casual to use BSD.<\/p>\n\n<p>My advice is to go with something that is tried and tested, has stood the test of time, and is well supported. I\u2019d recommend Ubuntu, or plain Debian. Everyone else is using them, and so when there are instructions for \u201cLinux\u201d it usually means \u201cDebian\/Ubuntu\u201d.<\/p>\n\n<p>In general I\u2019d always stick with the \u201croot\u201d distributions that are well established (Debian, Arch, Fedora, etc) and avoid straying too far afield, especially if you want something low maintenance.<\/p>\n\n<p>Whatever you pick, you should look up some information on setting it up as a server. I always make sure that SSH password authentication is off, and the firewall is on. Check if there\u2019s anything else you might need to do with your distribution of choice.<\/p>\n\n<h1 id=\"accessing-the-machine\">Accessing the Machine<\/h1>\n\n<p>In order to reduce the chance of someone gaining access to your server, it\u2019s best to not leave it accessible to the outside world. You can then use a VPN to give yourself secure access from anywhere, without leaving your proverbial front door open.<\/p>\n\n<p>The VPN I use is <a href=\"https:\/\/tailscale.com\">Tailscale<\/a>, but I\u2019ve also used <a href=\"https:\/\/nebula.defined.net\/docs\/\">Nebula<\/a> before\u2014enough that I wrote <a href=\"\/2021\/06\/22\/configure-nebula-vpn-on-ios-android\/\">instructions on how to set it up<\/a>. Nebula now have a hosted option, which should cut out a lot of that fiddly work.<\/p>\n\n<p>In general I like to only run open source software, so that I\u2019m not one business model change away from having to re-think my entire setup. However, Tailscale is convenient enough that I use it instead of configuring <a href=\"https:\/\/www.wireguard.com\">Wireguard<\/a> myself. I do try to make sure I\u2019m not relying on any feature that can\u2019t be easily replaced, I don\u2019t use Tailscale\u2019s web server proxying and similar features for this reason.<\/p>\n\n<h1 id=\"running-software\">Running Software<\/h1>\n\n<p>Obviously <a href=\"\/2026\/01\/15\/why-containers\/\">I think that containers offer a lot of benefits<\/a>, which is why I use them for the software I run. A large part of that is my <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">custom container management tool<\/a> and <a href=\"https:\/\/codeberg.org\/willhbr\/endash\">dashboard<\/a> that make this easy for me, and only me.<\/p>\n\n<p>Whether containers are the right answer for you will really depend on what you\u2019re aiming to run. If it can be installed directly through your system package manager (like <code>apt<\/code> or <code>yum<\/code> or whatever) then that\u2019s probably the easiest thing.<\/p>\n\n<p>For example, the <a href=\"https:\/\/www.navidrome.org\/docs\/installation\/linux\/\">Navidrome installation instructions<\/a> involve downloading a Deb archive, installing it, and starting the program with <code>systemctl<\/code>. None of this is particularly complicated, but it\u2019s a little fiddly. It\u2019s probably fine as a one-off install, but I\u2019m not sure if this method will update when a new version is available.<\/p>\n\n<p>My recommendation here for Navidrome and other software that isn\u2019t currently available via <code>apt<\/code> would be to use <a href=\"https:\/\/docs.podman.io\/en\/latest\/markdown\/podman-quadlet.1.html\">Quadlets<\/a>. They basically wrap your containers in <a href=\"https:\/\/en.wikipedia.org\/wiki\/Systemd\">systemd<\/a> units. Systemd is the way to run managed background processes on many Linux distributions, and so it\u2019ll handle things like starting your application when the machine boots.<\/p>\n\n<p>Mat Duggan <a href=\"https:\/\/matduggan.com\/replace-compose-with-quadlet\/\">has a nice overview<\/a> of what you can do with quadlets. You basically just make a config file like this:<\/p>\n\n<div class=\"language-systemd highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>[Unit]\nDescription=Navidrome\nAfter=network-online.target\n\n[Container]\nImage=docker.io\/deluan\/navidrome:latest\nContainerName=navidrome\nAutoUpdate=registry\nPublishPort=4533:4533\nVolume=\/path\/to\/my\/music:\/music:ro\nVolume=\/path\/to\/data\/storage:\/data\nEnvironment=ND_LOGLEVEL=warn\n\n[Service]\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n<\/code><\/pre><\/div><\/div>\n\n<p class=\"caption\">For illustrative purposes only, I have not tested this.<\/p>\n\n<p>This will auto-update periodically whenever there\u2019s a new image pushed to <code>docker.io\/deluan\/navidrome:latest<\/code>, which is especially nice if you want something a bit more hands-off.<\/p>\n\n<p>For most people, I\u2019d recommend against using <a href=\"https:\/\/caddyserver.com\">Caddy<\/a> as a reverse proxy and setting up a DNS record. It\u2019s easier to just accept remembering a couple of port numbers and creating bookmarks.<\/p>\n\n<h1 id=\"backups\">Backups<\/h1>\n\n<p><a href=\"\/2026\/07\/19\/backups-with-restic\/\">I use Restic<\/a> to back up my servers, which gives me confidence that my self-hosted data won\u2019t just disappear when my USB HDD enclosure dies. At the very least, keep a copy of your data (like, your music library) on your main computer, and <em>presumably<\/em> you back that up. Or at the very least, it\u2019s less likely to fail.<\/p>\n\n<p>Depending on the amount of data you have, you could keep everything on your internal SSD and use an external HDD purely as a backup drive. It doesn\u2019t give you off-site safety, but you\u2019d have a second copy in case you formatted the wrong drive.<\/p>\n\n<hr \/>\n\n<p>Obviously self-hosting isn\u2019t a low-effort solution, and requires a fair amount of enthusiasm or sysadmin experience. The good thing about self-hosting music is that you can just get a client (I use <a href=\"https:\/\/nautiline.app\">Nautiline<\/a>) that has good client-side caching, so if\u2014or more realistically, <em>when<\/em>\u2014your server goes offline, you still have some music available until you get around to fix it.<\/p>\n\n<p>Hosting <a href=\"\/2024\/02\/21\/a-successful-experiment-in-self-hosted-rss-reading\/\">your own RSS aggregator<\/a> is a bit more annoying, as the whole purpose is to show new things that rely on an internet connection. Although I can go a few hours without reading RSS and just catch up later.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:as-normal-as-can-be\">\n      <p>As normal as you can be while still wanting to run a home server.\u00a0<a href=\"#fnref:as-normal-as-can-be\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/11\/23\/so-you-want-to-build-a-homelab\/\">Permalink<\/a>\n&bull; November 23, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20So%20You%20Want%20to%20Build%20a%20Homelab\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/11\/23\/so-you-want-to-build-a-homelab\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-11-23T22:49:00+11:00","date_modified":"2026-11-23T22:49:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/11\/20\/nix-jj-diff\/","title":"Comparing Nix Derivations in a JJ Repo","content_html":"<p>So far with NixOS I\u2019ve been making changes to my <code>configuration.nix<\/code> and then running <code>nixos-rebuild switch<\/code> and seeing what happens. This has worked out so far, but I\u2019ve just swapped my home server over to NixOS, which means breaking it could have consequences.<\/p>\n\n<p>Switching my home server means I now have two separate Nix configs, and I\u2019d really like them to be merged together, so all the common bits aren\u2019t duplicated a bunch of times. I could just try to refactor the Nix code and assume I\u2019d got it right, but I really want to be sure that I haven\u2019t messed something up. Obviously if I mess it up really badly it won\u2019t build, but I\u2019m more worried about accidentally removing all my SSH authorised keys, or something like that.<\/p>\n\n<p>Thankfully there is a simple solution. The easiest thing you can do is build both versions and check if they point to the same path in the Nix store, but that\u2019s a bit of a hassle to do manually. It\u2019s also only good for verifying changes are identical, what do you do if they point to different things?<\/p>\n\n<p><a href=\"https:\/\/github.com\/Gabriella439\/nix-diff\"><code>nix-diff<\/code><\/a> to the rescue! You give it to derivation paths, and it\u2019ll give you a (huge) output showing all the things that have changed. So if you remove an authorised key, that\u2019ll show in the diff.<\/p>\n\n<p>To make this easier to work with, I\u2019ve written <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/commit\/34107b121cd44a91fda89cb97600cefbe43ffbed\/bin\/nix-jj-diff.rb\">a script<\/a> that will get the derivation paths automatically, and pass them to <code>nix-diff<\/code>.<\/p>\n\n<p>There are a few different derivation paths that you might want to compare. The simplest thing is to just build the current config and print the derivation path:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ nix eval --raw '#nixosConfigurations.yak.config.system.build.toplevel.drvPath'\n\/nix\/store\/xipq58d8c3x2ik0l64nv6xncf8ffy8dj-nixos-system-yak-26.11.20261116.e21fec3.drv\n<\/code><\/pre><\/div><\/div>\n\n<p>I could run that, note the path, make some edits, re-run the command, and pass the pair of paths to <code>nix-diff<\/code>. It\u2019s more useful to get the derivation that is currently being used by the live server, and compare against that:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ ssh root@yak \"nix-store -q --deriver \/run\/current-system\"\n\/nix\/store\/xipq58d8c3x2ik0l64nv6xncf8ffy8dj-nixos-system-yak-26.11.20261116.e21fec3.drv\n<\/code><\/pre><\/div><\/div>\n\n<p>Since I build everything locally, everything is guaranteed to be in my local <code>\/nix\/store<\/code>, so I have all the information necessary to <code>nix-diff<\/code> them.<\/p>\n\n<p>Comparing the current config versus the live machine is what you\u2019ll want before you deploy (that\u2019s why I implemented the same thing in <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">Pod<\/a>). However, I wanted to be sure that individual changes that I was making locally weren\u2019t making unintended changes, so I made my script work between JJ revisions.<\/p>\n\n<p>This way I can diff what\u2019s changed between two commits, and make sure that lines up with the edits I made to the <code>.nix<\/code> files. You can build a derivation from a particular Git commit hash like this:<\/p>\n\n<div class=\"language-shell highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>nix eval --raw \\\n  \"git+file:\/\/$REPO_PATH$?rev=$COMMIT$&amp;dir=$SUBDIR#nixosConfigurations.$HOST.config.system.build.toplevel.drvPath\"\n<\/code><\/pre><\/div><\/div>\n\n<p>It\u2019s a bit of a mouthful, which is why I wrote the script. Instead, I can just run:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ jj nix-diff yak\n<\/code><\/pre><\/div><\/div>\n\n<p>Which will show me what\u2019s changed between <code>@<\/code> and <code>@-<\/code>. I can also pass a custom revset to compare a chain of commits.<\/p>\n\n<p>A nice improvement here could be for <code>nix-diff<\/code> to highlight some diffs (systemd services, open ports, users, etc) with special formatting, instead of the current generic diff, which can get very large and hard to follow.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/11\/20\/nix-jj-diff\/\">Permalink<\/a>\n&bull; November 20, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Comparing%20Nix%20Derivations%20in%20a%20JJ%20Repo\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/11\/20\/nix-jj-diff\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["homelab","jujutsu"],"date_published":"2026-11-20T00:00:00+11:00","date_modified":"2026-11-20T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/11\/13\/photo-archiving-with-jpeg-xl\/","title":"Photo Archiving With JPEG-XL","content_html":"<p>After I wrote <a href=\"\/2026\/11\/08\/image-formats-for-photo-archiving\/\">my last post<\/a> comparing the quality and size of different image formats to replace Sony ARW files, a friend asked \u201cwhy didn\u2019t you compare JPEG-XL?\u201d<\/p>\n\n<p>The reason I didn\u2019t include it was because I didn\u2019t think I had a good way of batch converting raw photos to JXL. This made it too esoteric and not a practical option for my archival purposes. However, I then realised that I could have just used <a href=\"https:\/\/www.darktable.org\/\">Darktable<\/a> to convert ARW to JXL.<\/p>\n\n<p>I exported my test images to JXL, then opened them up in Pixelmator Pro to compare against the original ARW files.<\/p>\n\n<p>The shadow reconstruction is most similar to the DNG file. You don\u2019t get all the detail in the darkest area, but the slightly lighter areas retain more detail and have no colour banding, allowing them to be recovered more easily. Like the DNG they adjust to a natural shade.<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/jxl-shadows.webp\" alt=\"JPEG-XL image with boosted exposure showing kinda-intact shadows\" \/><br \/>\nJPEG-XL image with exposure boosted to see how much detail we\u2019ve kept in the shadows.<\/p>\n\n<p>For comparison, here\u2019s the exposure-boosted ARW file.<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/shadows-arw-exposed.webp\" alt=\"ARW image brightened showing the recovered shadow detail\" \/><br \/>\nARW with the exposure turned up to show the shadow detail.<\/p>\n\n<p>There are some very minor artifacts in the JXL that aren\u2019t present in the DNG file, mostly where a dark area transitions to a slightly lighter area. It\u2019s hard to say whether this is bad enough to spend an extra 50% on storage and having to use the Adobe DNG Converter.<\/p>\n\n<p>Pixelmator Pro, Photomator, and the MacOS Photos app all use Apple\u2019s image libraries to load and edit images, so images loaded into any of them look identical. Darktable has its own image libraries, and so it processes the images slightly differently. You can see this difference in brightness and colour in the two images above.<\/p>\n\n<p>I tried to disable some of the helpful automatic adjustments (like increasing the exposure if the image was captured with a negative exposure value) but JXL export is still a little different than the other formats I\u2019ve been comparing. This is not a problem with Darktable, it\u2019s just a difference that I\u2019m not really accounting for. I\u2019m sure someone more familiar with it could make the default adjustments more closely match those of Apple\u2019s libraries.<\/p>\n\n<p>Interestingly I did export as plain JPEG from Darktable as well, and didn\u2019t see any of the colour banding that I saw with the Photos app exporter. The JPEGs were still about twice the size of a JXL, so there\u2019s not much point in using them, but it seems like the colour banding isn\u2019t a problem intrinsic to the format.<\/p>\n\n<p>I was a little surprised at the encoding time difference between different quality levels with JPEG-XL. Effort is a scale from 1 to 9, and initially I tested level 8 because I wanted these files <em>small<\/em>. It took on average 26 seconds per image on my M4 MacBook Air, and 33 seconds on my home server (an Intel i5-1135G7). It\u2019s surprising to me that the M4 is so close to the i5. The CPU usage didn\u2019t seem to spike much, so I\u2019m not sure where the time is being spent. I didn\u2019t look into this much further than that.<\/p>\n\n<p>Thankfully at lower effort levels, the encoding speeds up dramatically. At level 7 (the default) it\u2019s 5 seconds each, and at level 6 it\u2019s 2 seconds each on the M4.  The size difference between effort level 6 and 9 on my test image was only 100kB, so if I use this for archiving the lower effort level will save me a lot of time while not using that much more storage space. Remember that the original image is 24.9MB, and we\u2019re going down to 2.6MB. Going to 2.5MB for 16 times the encoding time just isn\u2019t worth it.<\/p>\n\n<p>JXL seems to be a clear winner in terms of size and general image quality. I haven\u2019t committed to encoding my entire image archive just yet.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/11\/13\/photo-archiving-with-jpeg-xl\/\">Permalink<\/a>\n&bull; November 13, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Photo%20Archiving%20With%20JPEG-XL\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/11\/13\/photo-archiving-with-jpeg-xl\/","image":"https:\/\/willhbr.net\/images\/2026\/jxl-shadows.webp","date_published":"2026-11-13T00:00:00+11:00","date_modified":"2026-11-13T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/11\/08\/image-formats-for-photo-archiving\/","title":"Image Formats for Photo Archiving","content_html":"<p>Did you know that the \u201craw\u201d in \u201c<a href=\"https:\/\/en.wikipedia.org\/wiki\/Raw_image_format\">raw photo<\/a>\u201d isn\u2019t an acronym? It\u2019s just \u201craw\u201d as in \u201cunprocessed\u201d. So when someone writes it as \u201cRAW\u201d, they are being incorrect?<\/p>\n\n<p>I\u2019ve been looking at the best way to archive old raw photos in my photo library, in an attempt to <a href=\"\/2025\/12\/26\/stuck-in-a-photo-management-factory\/\">dig myself out of the pit of despair that is photo library management<\/a>.<\/p>\n\n<p>My Sony a6500 (and the a6000 before it) save images as Sony ARW files. From the 24MP sensor, these images are usually around 24MB. As I\u2019ll explain later, shooting with these larger files (instead of having the camera just save JPEGs) is worth it, but for long-term storage of images I took years ago, maybe the storage isn\u2019t worth it.<\/p>\n\n<p>The best case scenario here is that I can export the ARW files from my photo library to a format that cuts 20\u201330% of the file size, but still gives me enough data to go back and edit them. Ideally if I edit one of these photos, I\u2019m not prevented from making adjustments due to a lack of data. ARW files from my a6500 have an astonishing amount of detail in the shadows and highlights that can be recovered later, and it would be a shame to throw that away.<\/p>\n\n<h1 id=\"zip-it\">Zip It<\/h1>\n\n<p>Chucking one of my ARW files into a Zip file shrunk it from 24.9MB to 22.9MB, which was more than I expected. A 9% reduction isn\u2019t too bad for zero loss in quality.<\/p>\n\n<h1 id=\"jpeg\">JPEG<\/h1>\n\n<p>The obvious answer is to just export as JPEG. They\u2019re smaller, compatible with everything, and can be exported from any software. I exported two test images from Apple Photos at full size and maximum quality. The resulting files were 13.3MB and 5.8MB, a 47% and 77% saving, which is amazing.<\/p>\n\n<p>To compare how well they\u2019d respond to edits I opened both versions in Pixelmator Pro and applied the same exposure adjustment to see what the shadows looked like. I\u2019m cranking the exposure <em>way<\/em> up to try and spot the details present in the ARW that would probably be thrown away in the process of converting to JPEG. It\u2019s not an adjustment you\u2019d normally make unless you\u2019d messed up your exposure when you took the photo.<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/ground-arw-vs-jpeg.webp\" alt=\"\" \/><br \/>\nARW on the left, JPEG on the right.<\/p>\n\n<p>That looks bad. I did intentionally find a photo with both bright highlights and dark shadows to test with, since that should represent close to the worst case that I\u2019m worried about.<\/p>\n\n<h1 id=\"heic\">HEIC<\/h1>\n\n<p>This is the more efficient format that iPhones have been using for ages, so presumably Apple Photos would be good at exporting them. I exported the same image, opened it in Pixelmator Pro, and was presented with this:<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/heic-ground.webp\" alt=\"\" \/><br \/>\nHEIC image with no exposure adjustments.<\/p>\n\n<p>The HEIC was only 635KB, compared to the 24.9MB of the ARW. That\u2019s a hefty 93% saving, but that\u2019s not just at the expense of shadow detail that you can\u2019t see. This banding is present before any adjustments, and is obvious even without looking at the original.<\/p>\n\n<p>Looking at the second test shot, it\u2019s nowhere near as bad, but this has shattered my confidence in HEIC to actually store an image worth looking at.<\/p>\n\n<h1 id=\"dnglab\">DNGLab<\/h1>\n\n<p>I wanted to see what results I could get from compressed raw formats. Apparently compressed <a href=\"https:\/\/en.wikipedia.org\/wiki\/Digital_Negative\">DNG files<\/a> can get good results. I installed <a href=\"https:\/\/github.com\/dnglab\/dnglab\">DNGLab<\/a> which is a CLI to archive images (including Sony ARWs) as DNGs, offering both lossless and lossy compression.<\/p>\n\n<p>I used these two commands to compress my test images:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ \u00a0dnglab convert -c lossy --embed-raw false . dnglab\/\n$ \u00a0dnglab convert -c lossless --embed-raw false . dnglab\/\n<\/code><\/pre><\/div><\/div>\n\n<p>The lossless files were slightly bigger than the ARWs they replaced, so that\u2019s a bit of a dead end. The lossy images were about 75% less than the original, but both had a significant purple tint. I assume this is a bug in DNGLab\u2019s raw processing, so it seems like it\u2019s not yet ready for this kind of use.<\/p>\n\n<h1 id=\"adobe-dng-converter\">Adobe DNG Converter<\/h1>\n\n<p>Honestly, I wish I didn\u2019t have to do this. Truly. I built DNGLab from source in the hope that I wouldn\u2019t have to go through this, but here we are. I downloaded all 1.8GB from Adobe\u2019s website, ran the installer package, which installed all of the 2.7GB application onto my computer.<\/p>\n\n<p>Just think how many images I could store in the space used by this application, whose one job is to convert between one file format and another file format. Why is this image converter larger than many Linux distribution installer ISOs? No one knows.<\/p>\n\n<p>Anyway, I converted my test images to both lossless and lossy DNGs. Like with DNGLab, the lossless images were slightly bigger than the original files, and the lossy images were about 80% smaller than the originals.<\/p>\n\n<p>So to compare the quality of the shadows I was looking at this part of the image:<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/shadows-arw-original.webp\" alt=\"ARW image showing the almost-black shadows\" \/><br \/>\nARW with no exposure adjustments.<\/p>\n\n<p>The shadows are almost entirely black\u2014because the camera was exposing for bright lights in the foreground. With the power of ARW, I can crank up the exposure and see what was actually there:<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/shadows-arw-exposed.webp\" alt=\"ARW image brightened showing the recovered shadow detail\" \/><br \/>\nARW with the exposure turned up to show the shadow detail.<\/p>\n\n<p>This is why if you\u2019re wanting to get the most out of your camera, you should be shooting raw. The amount of extra flexibility you get to retroactively fix mistakes is incredible. Just imagine if I was working with a JPEG here, it would be a mess of colour banded nonsense.<\/p>\n\n<p>Anyway what\u2019s interesting about the DNG is that it doesn\u2019t recover the darkest shadows, but the areas where this is detail get brightened without terrible banding.<\/p>\n\n<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/shadows-dng-lossy-exposed.webp\" alt=\"DNG image showing the shadows being clipped to black, so there's no detail\" \/><br \/>\nDNG with the same exposure adjustment, showing missing shadow detail.<\/p>\n\n<p>What\u2019s interesting is that the lossless image had the same behaviour, neither DNG would recover the shadows like the ARW did.<\/p>\n\n<hr \/>\n\n<p>The clear winner for me is the lossy DNG, with the huge caveat that I hate having Adobe\u2019s DNG converter installed. It feels like a crime against computing. It\u2019s hard to beat the file size savings of the DNG paired with how well it responded to exposure changes. I wouldn\u2019t be able to get the full detail, but it seems like I\u2019m not going to run into banding or discolouration with DNG.<\/p>\n\n<p>A notable exclusion here is JPEG-XL, which should be able to get smaller file sizes than regular JPEG. I\u2019m not sure if you get more flexibility while editing. I couldn\u2019t find a convenient way of converting ARW to JPEG-XL, but it\u2019s something I want to look into some more.<\/p>\n\n<p>My next step will probably be exporting and converting a <em>lot<\/em> of photos to DNG, seeing what the aggregate storage savings are, and seeing how it handles different types of images.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/11\/08\/image-formats-for-photo-archiving\/\">Permalink<\/a>\n&bull; November 8, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Image%20Formats%20for%20Photo%20Archiving\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/11\/08\/image-formats-for-photo-archiving\/","image":"https:\/\/willhbr.net\/images\/2026\/ground-arw-vs-jpeg.webp","date_published":"2026-11-08T00:00:00+11:00","date_modified":"2026-11-08T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/11\/05\/photo-editing-on-linux\/","title":"Photo Editing on Linux","content_html":"<p class=\"caption\"><img loading=\"lazy\" src=\"\/images\/2026\/digikam.webp\" alt=\"digiKam with a whole bunch of drone photos\" \/><br \/>\ndigiKam with some of my drone photos.<\/p>\n\n<p>My typical photo editing process is the <a href=\"\/2022\/03\/20\/the-good-and-bad-of-photos-for-macos\/\">MacOS Photos app<\/a> for managing the library, then <a href=\"\/2023\/05\/24\/photomator-for-macos\/\">Photomator<\/a> for editing, or Pixelmator Pro for more involved edits. If I\u2019m on my phone, <a href=\"\/2024\/12\/02\/appreciating-the-fine-art-of-phone-photography\/\">I\u2019ll use Photomator for iOS<\/a>.<\/p>\n\n<p>When I <a href=\"\/2026\/10\/11\/inevitably-nixos\/\">tested out NixOS<\/a> I installed it onto my specifically-for-Linux-testing ThinkPad, which I\u2019ve been using to try out some Linux photo editors.<\/p>\n\n<h1 id=\"digikam\">digiKam<\/h1>\n\n<p>DigiKam seems to mostly be a photo library management system with basic editing capabilities. For managing a photo library it seems perfectly competent. You can tag or label photos, and navigating between photos is fast, which I find essential for identifying which version of a shot I want to keep and edit. It easily imported photos from an SD card just fine, copying them into the Pictures directory and adding them to a new album.<\/p>\n\n<p>I haven\u2019t used the library interface heavily\u2014I\u2019m sure I would have more to say if I imported thousands of photos across many albums\u2014but my initial complaints would be at the small size of the thumbnails, with so much space taken up by mostly irrelevant information. The same amount of space is reserved for the filename and time as is given for the actual image. Thankfully this can be configured, so I\u2019ve <em>just<\/em> disabled all the info that would sit under the image.<\/p>\n\n<p>The digiKam editor does not work with the way I edit photos. Each action that you can perform on the image is a separate tool that you must enter into, adjust, and exit from. This separation makes it difficult to do \u201cexploratory\u201d editing where you tweak and adjust different settings to see how they interact in the final image.<\/p>\n\n<p>This is particularly annoying with the rotate and crop tools. I am used to doing both at the same time, and I\u2019ll balance how much I rotate with how it impacts my ability to get my desired crop\u2014or vice versa. Since these are two separate tools in digiKam, I would first need to rotate a certain amount, and then crop in based on that rotation. If I couldn\u2019t get the crop I wanted, I\u2019d have to go back to the rotate tool and adjust before restarting the crop to see if it worked better.<\/p>\n\n<p>What I think is happening is that each tool builds a new image. The rotate tool returns an image with a rotation applied, the crop tool returns an image that is cropped. This means that if I adjust the exposure, use some other tool, and then want to readjust exposure, I\u2019m applying a <em>new<\/em> adjustment on the already-adjusted image. If I adjust the exposure to be too bright, and then try to adjust it back down again, I will have lost data in any area that clipped to 100% brightness with the first adjustment (or in the inverse scenario, that clipped to 0% brightness).<\/p>\n\n<p>If you already know exactly what adjustments you want to make, especially if it\u2019s just one or two adjustments, this model might work for you. However, since I edit quite heavily, and will tweak things back and forth to get it just how I want, this doesn\u2019t work for me.<\/p>\n\n<h1 id=\"rawtherapee\">RawTherapee<\/h1>\n\n<p>Editing an image in RawTherapee works closer to the way I want it. You can move between different adjustments easily. I did get caught out by the fact that adjustment controls look like they\u2019re active, but the section might be deactivated by default, so the controls won\u2019t do anything.<\/p>\n\n<p>It\u2019s also weird that panning the image with the mouse doesn\u2019t move it 1:1. Dragging with the mouse makes the image move faster than the mouse is moving. This isn\u2019t much of a problem (it still moves slow enough that you can easily position it) but it\u2019s weird to break out of a standard \u201cdirect interaction\u201d model.<\/p>\n\n<p>My overall impression with RawTherapee is that there are too many visible knobs in the editing UI. I would prefer a more progressive disclosure of control\/complexity. For example, I often like to tweak the hue, saturation, and brightness of a specific colour range. In Pixelmator the interface looks like this:<\/p>\n\n<p><img loading=\"lazy\" src=\"\/images\/2026\/pixelmator-adjustments.webp\" alt=\"the selective hue adjustments in Pixelmator Pro\" \/><\/p>\n\n<p>In RawTherapee the interface looks like this:<\/p>\n\n<p><img loading=\"lazy\" src=\"\/images\/2026\/rawtherapee-adjustments.webp\" alt=\"the selective hue adjustments in RawThereapee\" \/><\/p>\n\n<p>Obviously most of the problem here is that I don\u2019t know what most of this interface means. I don\u2019t know how the top-level L*a*b* adjustments differ from the standard exposure controls, and having six different drop-downs that reveal the hue adjustment controller is a <em>lot<\/em>.<\/p>\n\n<p>I assume that I can customise this, but it seems weird that the default set of tools includes niche or advanced tools right next to basic ones. Right under white balance is \u201cgamut compression\u201d. White balance is something almost everyone will use to make their image look more natural if it wasn\u2019t captured with quite the right settings, and <a href=\"https:\/\/rawtherapee.com\/downloads\/5.12\/\">gamut compression is<\/a>:<\/p>\n\n<blockquote>\n  <p>A new tool called Gamut Compression applies the ACES (Academy Color Encoding System) Reference Gamut Compression operator to improve the look of highly-saturated colors and bring colors within a selectable gamut before applying other color-related tools offered by RawTherapee.<\/p>\n<\/blockquote>\n\n<p>It is awesome that these tools are available, but I think it would be even better by default the tools you saw were the most relevant ones.<\/p>\n\n<h1 id=\"darktable\">darktable<\/h1>\n\n<p>I\u2019ve played with Darktable a little before, so I went into this expecting to be frustrated again, but I was mildly surprised.<\/p>\n\n<p>Darktable\u2019s interface is similar to RawTherapee. There are a lot of tools with a lot of options, and as a second-time user they don\u2019t feel incredibly relevant. I did find a menu that changed the layout to \u201cworkflow: beginner\u201d that got rid of some stuff, but the tool selection and order still didn\u2019t feel coherent.<\/p>\n\n<p>The controls are set in a scrolling list, but if you scroll while the cursor is over a control, you will adjust the control. This turns the adjustments panel into a hazard. I\u2019ll mouse over to the panel, habitually start to scroll, and then have made some random adjustment to my photo. I ended up carefully grabbing the scrollbar, which was tedious since I\u2019m used to using trackpad gestures to quickly scroll.<\/p>\n\n<p>I\u2019ve just found that there\u2019s a setting to turn this behaviour off (settings, miscellaneous, \u201cmouse wheel scrolls module side panel by default\u201d) but it seems like an error-prone default to me. Perhaps Darktable users use big monitors and curated tool sets, so they have less need for scrolling and the quick input is more valuable.<\/p>\n\n<p>Controls in Darktable also have more range than I find useful, which gives less space for the range that I will actually use. For example the exposure control goes from -4EV to +4EV, but I think the useful range is much closer to -2EV to +2EV. If the control had this smaller range, it would be easier to precisely select a particular value. The selective colour adjustment (\u201ccolor equalizer\u201d) is similar\u2014I rarely want to shift a colour more than say 20 degrees, but the UI shows a full 360 degree range, so a typical adjustment is a very precise, fine movement.<\/p>\n\n<p>Pixelmator works around this really nicely. Every control has\u2014what I think is\u2014a reasonable upper and lower bound, but if you hold the option key, all the limits double and you can push a slider further than it would go by default. Most of the time you get the more precise control, and the higher limit is a single button push away. I think there\u2019s even a setting to use the higher limits all the time.<\/p>\n\n<p>I did pop into the settings to change the UI theme in Darktable to be darker (somewhat closer to 25% grey instead of the default that is closer to 50% grey). This doesn\u2019t change the background behind the image that your editing, which is annoying. You can tweak that with custom CSS, but it would be convenient if that was a simple toggle.<\/p>\n\n<p>More generally, I found Darktable\u2019s custom UI to have insufficient differentiation between sections. Almost everything is similarly-sized text above sliders, so it\u2019s hard to create a clear hierarchy. Using something closer to the system controls (like RawTherapee does) would help here, as the current style doesn\u2019t differentiate enough between a header, a text field, and a dropdown. Borders around controls, colours on active controls, and a few more shades to differentiate control types would go a long way.<\/p>\n\n<p>A common theme while looking up how to make a particular adjustment in Darktable was people giving advice to avoid a particular module (a component in the UI) as it had some problem or wasn\u2019t as accurate as a replacement module. This is obviously just part of using a mature system, but it does create a concern that I might be using the \u201cwrong\u201d set of modules. Keeping the old modules for compatibility is great, but marking them as obsolete would be more friendly to a new user.<\/p>\n\n<p>The most annoying missing feature\u2014or difference in behaviour\u2014between Darktable and what I\u2019m used to is the ability to quickly toggle between the edited and unedited versions of the photo. In Pixelmator you just hold control-m and the preview swaps between the two. Darktable has what is on paper a much more capable system, where you can record snapshots of edits and compare between them, but to me this just seems like unnecessary complexity for a simple feature.<\/p>\n<h1 id=\"verdict\">Verdict<\/h1>\n\n<p>It\u2019s hard to judge these against my usual workflow since I\u2019m testing on a much older and less powerful machine than what I use for photo editing normally. Almost no adjustment works in real time on this laptop, so it\u2019s not a fair comparison to see how effective they are for quickly editing a large batch of photos. The Intel i5-8265U in my ThinkPad has about half the single-threaded CPU performance of the M4 in my MacBook Air.<\/p>\n\n<p>I\u2019ve also got about 7 years of muscle memory with Pixelmator and Photomator, and to make things even easier they share most of their UI.<\/p>\n\n<p>The default interface and behaviours really matter. With the standard interfaces I was ignoring most of the controls and spending a long time hunting around for the most basic tools. Progressive disclosure of complexity would help a lot, as well as having an expected workflow that informs the layout of the tools.<\/p>\n\n<p>Pixelmator and Photomator split tools into crop\/rotate, adjustments, and effects, which gives a little more space for each to have their own custom UI, rather than having a single drawer of tools. This informs my workflow, as I will usually edit the exposure and colours of an image, and then crop to my desired framing as a separate step.<\/p>\n\n<p>Obviously a huge part of this is the fact that I\u2019ve got seven years of habits and muscle memory with Pixelmator and Photomator, and I\u2019ve only spent a few hours tinkering with these three applications. So obviously keep that in mind, as I\u2019m sure someone going in the opposite direction would have their own confusions.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/11\/05\/photo-editing-on-linux\/\">Permalink<\/a>\n&bull; November 5, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Photo%20Editing%20on%20Linux\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/11\/05\/photo-editing-on-linux\/","image":"https:\/\/willhbr.net\/images\/2026\/digikam.webp","date_published":"2026-11-05T00:00:00+11:00","date_modified":"2026-11-05T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/10\/25\/what-can-you-do-for-your-compiler\/","title":"What Can You Do for Your Compiler?","content_html":"<blockquote>\n  <p>And so, my fellow programmers: ask not what your compiler can do for you\u2014ask what you can do for your compiler.<\/p>\n\n  <p>\u2014 <a href=\"https:\/\/en.wikipedia.org\/wiki\/Inauguration_of_John_F._Kennedy#Inaugural_address\">John F. Kennedy<\/a><\/p>\n<\/blockquote>\n\n<p>A friend and I were talking about the (somewhat) new <a href=\"https:\/\/github.com\/swiftlang\/swift-evolution\/blob\/main\/proposals\/0377-parameter-ownership-modifiers.md\"><code>consuming<\/code> and <code>borrowing<\/code> keywords in Swift<\/a>, which led to the question \u201cwhat\u2019s the point, can\u2019t the compiler just work it out for me?\u201d which I think is worth some interrogation.<\/p>\n\n<p>When I used to teach programming at university, one of the common pieces of confusion stemmed from strong typing. For someone who is new to programming, <code>\"5\"<\/code> (string) and <code>5<\/code> (integer) are not meaningfully different. Why can\u2019t I do <code>\"5\" + 5<\/code> and have the computer work it out?<\/p>\n\n<p>In some languages, the computer does work it out. We call that weak typing. If you ask to add two things together, the computer will first try and turn both into numbers, and use the result for the addition. You\u2019ll probably be most familiar with this from JavaScript\u2014more so with subtraction than addition\u2014where <code>4 - \"5\"<\/code> evaluates to <code>-1<\/code>, exactly how a beginner would expect.<\/p>\n\n<p>However, these rules are hard to internalise, especially because <code>+<\/code> can mean both addition and concatenation. <code>4 - \"5\"<\/code> is <code>-1<\/code> but <code>4 + \"5\"<\/code> is <code>\"45\"<\/code>. <code>1 - 4 + \"5\"<\/code> is <code>\"-35\"<\/code>. This isn\u2019t an insurmountable problem, but it will definitely surprise you if you\u2019re not careful. There <a href=\"https:\/\/eev.ee\/blog\/2012\/04\/09\/php-a-fractal-of-bad-design\/#operators\">is even weaker typing in PHP<\/a>, where strings that contain numbers will be converted to numbers first and then compared numerically.<\/p>\n\n<p>An honourable weak typing mention is the iOS Shortcuts app, where the weak typing doesn\u2019t just happen in the realm of simple data types, but complex objects. Depending on how you read it, a network request can either be a string of characters, a dictionary of values (probably by parsing it as JSON), or a rich text document. It means that your program will keep running further, but the result might be something completely different to what you expected.<\/p>\n\n<p>This is why most dynamic programming languages are strongly typed. A value can be any type, but it usually won\u2019t change type depending on how you use it. Python is a good example of this. If you want to turn a string into a number, you need to explicitly convert it with <code>int()<\/code> or <code>float()<\/code>. If you don\u2019t do this, your program will raise an exception and stop.<\/p>\n\n<p>So the next logical question is, why can\u2019t the compiler just tell me if I\u2019m doing an operation that\u2019s not allowed before I run the program?<\/p>\n\n<p>Which is how you get to static typing. In a dynamic language, it\u2019s impossible to know exactly what type each value will be in order to validate whether the operations done on them are allowed. In order to do that validation, you need to give more information to the compiler, in the form of type annotations.<\/p>\n\n<p>In a language like Java, you\u2019re not going to get a <code>NoMethodError<\/code> when you run your program,<sup id=\"fnref:reflection\"><a href=\"#fn:reflection\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> because the compiler checks that everything exists beforehand. The cost of this is that you need to tell the compiler the structure of everything ahead of time.<\/p>\n\n<p>Crystal\u2019s type system is a great example of \u201clet the compiler figure it out\u201d. Most of the time you can get away with not writing type annotations, but any experienced Crystal programmer knows that it is easiest to throw some annotations in the places where you know the type of something, so that the compiler is able to provide you with a better error message.<\/p>\n\n<p>Let\u2019s change course from typing and talk about memory management.<\/p>\n\n<p>As a beginner learning C, you probably have the thought \u201cwhy can\u2019t the computer just work out where the <code>free()<\/code> calls need to go?\u201d. Which it can, with a garbage collector\u2014but only if you tell it the structure of your data. The C compiler basically knows nothing, and so it couldn\u2019t collect your garbage even if it wanted to. The Java compiler (and runtime\/virtual machine) know everything, and so they can\u2014and will\u2014collect your garbage.<\/p>\n\n<p>However, the garbage collector is limited by the information that you give it, and so it\u2019s still possible to get memory leaks (memory that \u201cshould\u201d be freed, but isn\u2019t) in languages with a garbage collector. This happens when your program references something that it no longer needs. It may never access this data, but the computer doesn\u2019t know that; all it knows is that it has to keep a hold of everything that is still referenced.<\/p>\n\n<p>This is more pronounced in languages with reference counting instead of a garbage collector. Reference counting doesn\u2019t keep track of the relationships between objects, but instead how many objects hold a reference to each object. It\u2019s the difference between knowing who everyone\u2019s friends are, and knowing how many friends everyone has. When the reference count hits zero, the object can be freed. If two objects both reference one another, the count for both will never reach zero, and so they can never be freed. The computer is doing everything it can with the information available to it, it\u2019s not able to find out whether these two objects can be accessed, and so they have to be kept around forever.<\/p>\n\n<p>Reference-counted languages\u2014like Swift\u2014have features to communicate more detail about the inter-object relationships to the compiler. You can mark a relationship as <code>weak<\/code> so you don\u2019t increment the reference count. The compiler and runtime still can\u2019t save you if you forget this annotation.<\/p>\n\n<p>To avoid the pitfalls of garbage collection or reference counting, you can add explicit ownership information into the language, so the compiler can verify that there aren\u2019t leaks before the program runs. However, just like the move from dynamically-typed languages to static typing, you have to model these relationships in a way that the compiler understands. You\u2019ve basically going from dynamic lifetimes to static lifetimes.<\/p>\n\n<p>Rust is the classic example of this, where data ownership and borrowing are core to how the language works. Although there\u2019s nothing stopping you from correctly annotating that you want to retain a whole bunch of information in memory that will continue to grow unbounded, the difference is just that you have to write that down.<\/p>\n\n<p>So this brings us back to Swift\u2019s <code>consuming<\/code> and <code>borrowing<\/code>\u2014can the compiler just work it out?<\/p>\n\n<p>We could leave it up to the compiler, but since the compiler is just doing what we tell it to do, we could inadvertently make a change in one part of our program that forced a function to stop being <code>borrowing<\/code>. Just like how in dynamically typed languages, a change in one part of the codebase can change the structure of data to be incompatible with another part.<\/p>\n\n<p>What <code>consuming<\/code> and <code>borrowing<\/code> do is let us tell the compiler our intention for particular variables. If something is <code>consuming<\/code> then it can\u2019t be used again later. If something is <code>borrowing<\/code> then we have to give it back when we\u2019re finished.<\/p>\n\n<p>At the end of the day, the computer can only do what you tell it, so having a bigger vocabulary to talk to it is probably useful.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:reflection\">\n      <p>Well unless you\u2019re doing something interesting with reflection, or dynamic class loading, etc.\u00a0<a href=\"#fnref:reflection\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/10\/25\/what-can-you-do-for-your-compiler\/\">Permalink<\/a>\n&bull; October 25, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20What%20Can%20You%20Do%20for%20Your%20Compiler?\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/10\/25\/what-can-you-do-for-your-compiler\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-10-25T00:00:00+11:00","date_modified":"2026-10-25T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/10\/11\/inevitably-nixos\/","title":"Inevitably, NixOS","content_html":"<p>Look it was bound to happen at some point. It\u2019s like when I <a href=\"\/2025\/04\/26\/writing-in-crystal-rewriting-in-rust\/\">rewrote some stuff in Rust<\/a>, it wasn\u2019t a matter of if, but when. I\u2019ve just swapped over my little VPS (that <a href=\"\/2025\/03\/28\/building-nz-topomap-of-the-day\/\">runs NZ Topomap of the Day<\/a> and some other stuff) to <a href=\"https:\/\/nixos.org\">NixOS<\/a>, and plan to swap my home server soon.<\/p>\n\n<p>My go-to Linux has been Ubuntu since around 2008, for desktops, laptops, and servers. Even though I\u2019ve been using MacOS since 2012, for years now I\u2019ve been doing basically all of my development over SSH to an Ubuntu server.<\/p>\n\n<p>Last year I wrote about how I\u2019d <a href=\"\/2025\/03\/09\/a-slim-home-server-with-alpine-linux\/\">swapped my home server to Alpine Linux<\/a>. I didn\u2019t really have a well-justified reason for doing it, apart from the fact that it seemed interesting and a vague notion of \u201csimplicity\u201d or whatever. It would probably be easier if I could just say it was because I dislike <a href=\"https:\/\/en.wikipedia.org\/wiki\/Snap_(software)\">Snaps<\/a>.<\/p>\n\n<h1 id=\"why-nixos\">Why NixOS?<\/h1>\n\n<p>Nix (the package manager) and NixOS (the operating system) have a bunch of interesting features, which I know next to nothing about. The thing that entices me is that you can configure the entire operating system from a single declarative config file. This has two benefits. The first is that to set up a new computer, I just use the same config and it\u2019ll work like the previous one. The second is that because everything is declaratively configured, the config is the source of truth and reflects what\u2019s <em>actually<\/em> on the computer.<\/p>\n\n<p>I have scripts to set up an Alpine server, but often I\u2019ll have to SSH in to fix something and end up running some random command (like <code>ufw enable<\/code>) and forgetting about it. Now <em>that<\/em> computer has a firewall, but any new ones don\u2019t. My servers might all start out the same, but from then on they\u2019ll slowly diverge.<\/p>\n\n<h1 id=\"nixos-on-test-laptop\">NixOS on Test Laptop<\/h1>\n\n<p>Before committing to reinstalling the OS on one of my \u201creal\u201d computers, it seemed like a good idea to get my hands dirty and play around with NixOS. I\u2019ve got an old ThinkPad for exactly this purpose. Installing directly on a laptop meant I couldn\u2019t lock myself out from SSH or something like that if I made a config error.<\/p>\n\n<p>The GUI installer was as easy as any other Linux distro I\u2019ve used. I clicked \u201cnext\u201d a bunch of times and then had NixOS running. I was pleasantly surprised that it offered a handful of different window managers (Gnome, KDE, Xfce, and some others) as options during the install. I\u2019ve always just stuck with the default of whatever distribution I\u2019m using, so it\u2019s nice to have a choice right in the installer.<\/p>\n\n<p>Drivers for wireless were also installed correctly with no trouble right out of the box. This is the kind of convenience and wide support that I go to Ubuntu for, so it\u2019s nice to see it elsewhere. It has been a long time since I\u2019ve used wifi on Linux, so I guess this is just standard now.<\/p>\n\n<p>Once NixOS was installed, I had a great time editing <code>\/etc\/nixos\/configuration.nix<\/code> and running <code>sudo nixos-rebuild switch<\/code> to see what I\u2019d done. My goal was always to see how I could use NixOS as a host for containers, so I got the laptop set up in the same way I\u2019d set up a server. This involves Tailscale, a separate no-sudo user for Podman, a firewall, <a href=\"https:\/\/prometheus.io\/docs\/guides\/node-exporter\/\">node exporter<\/a>, and the correct SSH public keys.<\/p>\n\n<p>This process was reasonably easy, so I went ahead and created a temporary VPS to try out the server\/non-GUI install process.<\/p>\n\n<h1 id=\"nixos-server-install\">NixOS Server Install<\/h1>\n\n<p>I created one of the second-smallest shared-CPU servers on Vultr to test with. I would\u2019ve used the smallest one, but they\u2019re not available in all locations. For interactive use, latency is worth the extra cost. Especially when the cost of running a server for a few hours of tinkering is about $0.10.<\/p>\n\n<p>My first attempt was to follow the <a href=\"https:\/\/nixos.wiki\/wiki\/NixOS_Installation_Guide\">NixOS installation instructions<\/a> on the NixOS wiki. The process basically involves running <code>fdisk<\/code> to partition the drive, generating the <code>hardware-configuration.nix<\/code> file, making some edits to <code>configuration.nix<\/code>, then running <code>nixos-install<\/code> to set up the OS on the newly-formatted drive.<\/p>\n\n<p>When I realised that I\u2019d have to manually create partitions, I mostly lost interest in NixOS. Both Alpine and Ubuntu have guided installers with a sensible default \u201cwipe the drive and use the whole thing for the new install\u201d option. I can run through <code>setup-alpine<\/code> with my eyes closed. If setting up a new server meant finding the documentation for <code>fdisk<\/code> and working out whether I needed DOS or UEFI partitioning, NixOS probably wasn\u2019t going to be for me.<\/p>\n\n<p>I then found Samuel Ainsworth\u2019s <a href=\"https:\/\/github.com\/samuela\/nixos-up\"><code>nixos-up<\/code><\/a> script. It\u2019s basically <code>setup-alpine<\/code>, but for NixOS. It partitions your disk, creates a user, sets a password, and delegates to <code>nixos-install<\/code> with a sensible default configuration. I was a big fan.<\/p>\n\n<p>Sadly my optimism was short-lived. When <code>nixos-install<\/code> runs it needs to evaluate the whole Nix config to understand the intended state of the machine. Doing this\u2014even on a trivial install\u2014takes about 1.7GB of memory. Since I was running on a VPS with 1GB of memory, the process would OOM and the install would fail.<\/p>\n\n<p>To test this, I created a higher-spec\u2019d VPS with 4GB of memory, and the install completed in a few minutes. This is a useful data point, but not very useful since my actual VPS only has 1GB of memory.<\/p>\n\n<p>I could just configure a swap file, but I\u2019d have to do that in the booted installer as a separate step before running <code>nixos-up<\/code>. Any subsequent changes to the OS (running <code>nixos-rebuild switch<\/code>) would also require swap, and presumably take the server out of action while it\u2019s running, as any other process would be starved of memory.<\/p>\n\n<p>My next approach was to use <a href=\"https:\/\/github.com\/elitak\/nixos-infect\">NixOS-Infect<\/a>, which runs on an existing install and swaps the OS in-place to NixOS. I set up a new Ubuntu VM and gave it a whirl.<\/p>\n\n<p>I had to make a few modifications to the script to not write to <code>\/tmp<\/code>, since that\u2019s a tmpfs, and doesn\u2019t have enough space for NixOS-Infect to work in. The end result was a working install, but it didn\u2019t <em>feel<\/em> robust. It installed an older version of NixOS (from 2024, I think) and the whole process of editing a downloaded shell script to change random paths is not something I want in my server setup process.<\/p>\n\n<p>There is an alternative. The NixOS config can be built on a remote machine and then the artefacts copied to the target server. No evaluation actually needs to run on the VPS; it can all happen on my (comparatively) beefy local computer.<\/p>\n\n<p>I vaguely followed the instructions in <a href=\"https:\/\/yashgarg.dev\/posts\/nixos-on-low-memory-servers\/\">this blog post<\/a>. The basic idea is that you can build the config locally:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>nixos-rebuild build -I nixos-config=.\/configuration.nix\n<\/code><\/pre><\/div><\/div>\n\n<p>Then import that into <code>\/nix\/store<\/code> on the target (low memory) machine:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>nix-store --export $(nix-store -qR result) | ssh root@target \"nix-store --import --store \/mnt\"\n<\/code><\/pre><\/div><\/div>\n\n<p>And finally install that result:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ ssh root@target \"nixos-install --system $(readlink result)\"\n<\/code><\/pre><\/div><\/div>\n\n<p>The author does say that they create a swap file, but I skimmed over that since their machine only had 512MB of memory, so I assumed that my 1GB machine would be fine.<\/p>\n\n<p>I\u2019m not completely sure this is the root cause, but despite <code>nix-store --import<\/code> receiving piped input, it does actually need to use a lot of memory to validate the input. Or something like that. The result was that I\u2019d run the command to export from my local machine and import onto the VPS, and it would stall completely. I thought this was because of my slow home internet (copying 5GB of data isn\u2019t going to be quick) but I realised later that the <code>nix-store<\/code> process had been OOM killed.<\/p>\n\n<p>Before I realised that memory was the culprit, I exported the result to an archive, copied the archive up to the VPS, and only then realised that importing from archive was exhausting my memory.<\/p>\n\n<p>I also tried <a href=\"https:\/\/nix.dev\/manual\/nix\/2.35\/command-ref\/nix-copy-closure.html\"><code>nix-copy-closure<\/code><\/a> but you can\u2019t override the destination Nix store path. Since the remote machine was booted from an ISO, I needed to write into the mounted drive, which was at <code>\/mnt\/nix\/store<\/code> instead of <code>\/nix\/store<\/code>.<\/p>\n\n<p>During this whole process I was emailing back and forth with my friend Tom, a certified NixOS expert. He did some more research and pointed me to <a href=\"https:\/\/github.com\/nix-community\/nixos-anywhere\">nixos-anywhere<\/a>. This was how I wanted NixOS to work.<\/p>\n\n<h1 id=\"nixos-anywhere\">NixOS Anywhere<\/h1>\n\n<p><a href=\"https:\/\/github.com\/nix-community\/nixos-anywhere\">NixOS-Anywhere<\/a> allows for a fully declarative install\u2014including partitioning\u2014and then you use the same config to do updates.<\/p>\n\n<p>In theory you can do the same trick as NixOS-Infect and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Kexec\"><code>kexec<\/code><\/a> from another distribution into your new NixOS install, but for simplicity I booted a NixOS image on the VPS and installed from that.<\/p>\n\n<p>I followed the <a href=\"https:\/\/github.com\/nix-community\/nixos-anywhere\/blob\/main\/docs\/quickstart.md\">quickstart guide<\/a> and used their example configs, merged with the config that I\u2019d created on my laptop earlier. The process basically involves adding a public key so you can SSH in as root, setting the right disk in the <a href=\"https:\/\/github.com\/nix-community\/disko\">disko<\/a> config, then running:<\/p>\n\n<div class=\"language-console highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ nix run github:nix-community\/nixos-anywhere -- \\\n  --generate-hardware-config nixos-generate-config .\/hardware-configuration.nix \\\n  --flake .#&lt;flake name&gt; \\\n  --target-host root@&lt;ip address&gt;\n<\/code><\/pre><\/div><\/div>\n\n<p>This generates <code>hardware-configuration.nix<\/code> based on the actual target machine and saves it locally. It\u2019ll then do all the necessary <code>nixos-install<\/code> stuff for you.<\/p>\n\n<p>Overall it\u2019s a very straightforward process. I\u2019ve only done it twice though, so maybe there\u2019s some other problem I don\u2019t know about.<\/p>\n\n<h1 id=\"verdict\">Verdict<\/h1>\n\n<p>Apart from the installation process, I haven\u2019t had <em>that<\/em> many problems. I basically have no understanding of Nix as a language, so I\u2019ve just been updating <code>configuration.nix<\/code> by pattern-matching it as a config file, which is fine so far. Tom pointed me to <a href=\"https:\/\/code.tvl.fyi\/about\/nix\/nix-1p\">this reference<\/a>, which I will read at some point.<\/p>\n\n<p>It is really satisfying to be able to edit a file, do <code>nixos-rebuild switch<\/code>, and then have your system just <em>be<\/em> updated. I have run into two instances where updating the config just didn\u2019t apply changes to the system. The first was changing the user ID of a particular account. That\u2019s fair enough, since it would have to delete and recreate the account, but it would be nice if that was an error instead of just doing nothing. The second was when I removed Zsh (since I wouldn\u2019t need an interactive shell) and unset it as the login shell. I ended up with an account that still had Zsh as the login shell, but no Zsh binary to run. Explicitly setting Bash as the shell worked, but shouldn\u2019t it fall back to some default? Maybe rebooting would have saved me, but like the user ID switch, I would like this to fail at build time or on <code>switch<\/code>.<\/p>\n\n<p>When something does fail (because I don\u2019t know Nix) the error messages are not intuitive. I think a good analogy is the classic JavaScript \u201c<code>undefined<\/code> is not a function\u201d error. It\u2019s technically correct from the perspective of the interpreter, but from the programmer\u2019s perspective, the error should be \u201cyou tried calling method <code>X<\/code> and it doesn\u2019t exist\u201d.<\/p>\n\n<p>The command-line interface is also stuck between the old commands (like <code>nixos-rebuild<\/code> or <code>nix-copy-closure<\/code>) and the new unified <code>nix<\/code> CLI. Finding the right command, subcommand, or flag was difficult. You don\u2019t have to rewrite it in Rust, but the default behaviour of <a href=\"https:\/\/docs.rs\/clap\/latest\/clap\/\">Clap<\/a> does make very nice and consistent flag handling behaviour with good defaults and error messages.<\/p>\n\n<p>Everyone that uses Nix seems to use flakes, but it\u2019s experimental so all or most of the documentation pretends they don\u2019t exist. Any explanation I read of what a flake <em>is<\/em> reads to me like the unhelpful descriptions of a Haskell Monad. I\u2019ve definitely made it more difficult for myself by starting from the finish line (installing and using NixOS) rather than building up my understanding of the Nix package manager and how it builds software. But why walk when you can run?<\/p>\n\n<p>So far only my VPS is running NixOS. I do plan to swap my home server soon, but since it does actually store some useful data I want to be a little more careful with it. I <a href=\"\/2026\/07\/19\/backups-with-restic\/\">do have backups<\/a>, but it\u2019s even better to not have to use a backup.<\/p>\n\n<p>My first task is to understand the Nix language enough to structure my existing configurations to allow for most of the stuff to be shared (Podman, SSH, firewall) alongside some server-specific config (hostname, mounts and partitions).<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/10\/11\/inevitably-nixos\/\">Permalink<\/a>\n&bull; October 11, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Inevitably,%20NixOS\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/10\/11\/inevitably-nixos\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-10-11T00:00:00+11:00","date_modified":"2026-10-11T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/09\/28\/owning-my-streaming-with-navidrome\/","title":"Owning My Streaming With Navidrome","content_html":"<p><img loading=\"lazy\" src=\"\/images\/2026\/cover-art.webp\" alt=\"album art collage of my music library so far\" \/><\/p>\n\n<p>This started after I watched <a href=\"https:\/\/www.youtube.com\/watch?v=Yx7baJMQuVA\">Drew Gooden\u2019s video about the music industry<\/a>, focusing on Spotify. It\u2019s a good video, and like with many of his videos you\u2019ll end up going \u201cyeah, that <em>is<\/em> crappy!\u201d every few minutes.<\/p>\n\n<p>I\u2019ve been using Spotify continually since 2019; before then I\u2019d moved between a few services (making the most of free trials while I was a student). Overall my attitude to Spotify was that it was <em>fine<\/em>. The app wasn\u2019t great, but it wasn\u2019t overly offensive. It would play music when you asked it to. Every streaming service effectively has \u201call the music\u201d, so selection isn\u2019t a differentiating factor. The price isn\u2019t too bad, despite it <a href=\"https:\/\/pricetimeline.com\/data\/price\/spotify-premium\">increasing in price every year for the last four years<\/a>.<sup id=\"fnref:not-aud\"><a href=\"#fn:not-aud\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> These were all just things you put up with to have the convenience of any music you want, for a flat monthly fee.<\/p>\n\n<p>Of course, I do have complaints. Spotify seemingly would rather I listen to podcasts or audiobooks instead of music, and would spend about a third of the main screen in the app with suggested podcasts that I had no interest in. I already listen to podcasts <a href=\"https:\/\/overcast.fm\/\">in another app<\/a>. These suggestions couldn\u2019t be disabled, and there\u2019s always the looming threat of Spotify deciding that they need to <a href=\"https:\/\/www.theverge.com\/2023\/3\/8\/23630821\/spotify-design-home-music-podcasts-audiobooks-app\">become TikTok<\/a>.<\/p>\n\n<p>A persistent issue that I\u2019ve had with Spotify\u2019s UI is browsing for music by a particular artist. When you view an artist\u2019s page you\u2019ll see a few of their recent or popular albums as cover art, but if you want to find something that\u2019s not there, you get to a list of all songs grouped by album. This means you\u2019ve got to scroll for ages to find what you\u2019re looking for. It\u2019s especially bad for electronic music artists that have lots of remixes released as singles, which makes the list really hard to navigate.<\/p>\n\n<p>Anyway, the app being <em>fine<\/em> is only a part of the story.<\/p>\n\n<h1 id=\"the-economics\">The Economics<\/h1>\n\n<p>I won\u2019t rehash the content of the video, but I didn\u2019t feel like I was getting value out of my Spotify subscription, since I don\u2019t spend that much time listening to music. Because of the way the artists\u2019 pay out is calculated, most of my subscription would be going to artists I don\u2019t listen to. My understanding is that all the subscriptions are pooled, Spotify takes their cut, and then the rest is divvied up to artists based on what portion of the overall streaming time was for their music. So if you don\u2019t listen very much, your streaming time won\u2019t move the needle on how much your favourite bands contribute to the total listening time across all of Spotify.<\/p>\n\n<p>In 2021 I basically only listened to <a href=\"https:\/\/en.wikipedia.org\/wiki\/Typhoons_(album)\"><em>Typhoons<\/em> by <em>Royal Blood<\/em><\/a>, but since I didn\u2019t spend that much time listening to music overall, I doubt that they even got a dollar from me. Instead, I could have just bought their album for $16, they would hopefully get at least a dollar from that sale, and then I\u2019d save paying $16 a month to stream it.<\/p>\n\n<p>Which of course leads to the economics portion of this post. If we assume I\u2019ve paid $12 a month, (ignoring the fact the price has increased a few times) since 2019, I have paid just over $1000 on Spotify. For the next 7.5 years at the current price of $16 per month, it would be $1440. If for the last 7 years I\u2019d taken that money and bought an album every month or so, I would probably own most of the music I like listening to. I might not have to spend anything going forward. If I continued to pay for music streaming, I\u2019d have to pay almost 50% extra just to maintain access.<sup id=\"fnref:ignoring-inflation\"><a href=\"#fn:ignoring-inflation\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">2<\/a><\/sup><\/p>\n\n<p>Basically if most of your listening is repeat and casual, you\u2019ll probably save money in the long term by buying the music up front. The best time to start a music library was before you started streaming, but the second best time is today.<\/p>\n\n<h1 id=\"buying-music-in-2026\">Buying Music in 2026<\/h1>\n\n<p>So what\u2019s the best way to buy music in 2026? It\u2019s iTunes. At least if you\u2019re in Australia, for most music that\u2019s released via major record labels. <a href=\"https:\/\/www.qobuz.com\/\">Qobuz<\/a> is apparently another option, but for the albums I was looking at it was slightly more expensive, and the website works poorly.<\/p>\n\n<p>The other big player that I\u2019ve seen referenced is Amazon Music, who seem to sell digital music cheaper than iTunes, but don\u2019t operate in Australia so it\u2019s not an option for me.<\/p>\n\n<p>Music bought through iTunes has no DRM, and so you can play it anywhere that supports <a href=\"https:\/\/en.wikipedia.org\/wiki\/MP4_file_format\">M4A<\/a> files. Actually buying the music isn\u2019t particularly easy\u2014the iTunes store is a forgotten section of the Apple Music app on MacOS, so finding music to buy rather than stream is clumsy. It does work, and after clicking \u201cretry\u201d on the download a few times, you get the files in <code>~\/Music<\/code>, ready for you to do whatever you want with them.<\/p>\n\n<p>I haven\u2019t ended up buying a lot of music through iTunes\u2014it\u2019s mainly a fallback\u2014but a \u201ccheap\u201d album there is $10, a more typical album is $16, and an \u201cexpensive\u201d album is $24. So if you\u2019re setting aside your music streaming money, you might have to pool two months together to get some albums.<\/p>\n\n<p>Buying everything through iTunes would be a slow and expensive way to build up a music library. Thankfully my tastes are mainstream enough that I could go retro: buying CDs. A few searches on Gumtree and I was able to pick up the entire Foo Fighters discography\u2014ten full-length albums\u2014for $42, shipped all the way from Perth.<\/p>\n\n<p>I also picked up a bundle of CDs from someone who must\u2019ve had hundreds of listings for various albums. This wasn\u2019t quite as good a deal since they wanted at least $30 worth before they\u2019d bother shipping them. Each album was around $3-4, but I definitely padded it with some albums I wouldn\u2019t buy otherwise. Top scores in this bundle were <a href=\"https:\/\/en.wikipedia.org\/wiki\/Franz_Ferdinand_(album)\"><em>Franz Ferdinand<\/em><\/a> and <a href=\"https:\/\/en.wikipedia.org\/wiki\/The_Resistance_(album)\"><em>The Resistance<\/em><\/a> by <em>Muse<\/em>.<\/p>\n\n<p>The best place to buy music\u2014if it\u2019s available\u2014is Bandcamp. On <a href=\"https:\/\/isitbandcampfriday.com\">Bandcamp Friday<\/a> the platform fee is waived (aside from payment processing, I believe) and the artist gets the whole amount. This is the best way to get music and have your money go to the people that are making the music. You won\u2019t find many big names on Bandcamp, but many of the smaller electronic artists that I like are there. I picked up some <a href=\"https:\/\/arkpatrol.bandcamp.com\"><em>Ark Patrol<\/em><\/a>, <a href=\"https:\/\/theglitchmob.bandcamp.com\"><em>Glitch Mob<\/em><\/a>, and <a href=\"https:\/\/caravanpalace.bandcamp.com\"><em>Caravan Palace<\/em><\/a> here.<\/p>\n\n<h1 id=\"naughty-music\">Naughty Music<\/h1>\n\n<p>Something that I\u2019d forgotten about after many years of streaming-only is naughty music. By \u201cnaughty\u201d I mean mash-ups and albums released outside of normal record deals, and so aren\u2019t available on streaming platforms. I hadn\u2019t listened to <a href=\"http:\/\/www.neilcic.com\/mouthmoods\/\"><em>Mouth Moods<\/em><\/a> or <a href=\"https:\/\/illegalart.net\/allday\/\"><em>All Day<\/em><\/a> in ages because they weren\u2019t available in Spotify with the rest of my music. If I\u2019m managing my own library, I can just grab the MP3s and listen to them just like everything else.<\/p>\n\n<p>This also includes albums like <a href=\"https:\/\/en.wikipedia.org\/wiki\/My_Name_Is_Skrillex\"><em>My Name Is Skrillex<\/em><\/a>, which was at one point available as a free download. I\u2019ve got a copy from a backup of my old laptop, and so I could just scoop up those files into my library.<\/p>\n\n<p>Then there\u2019s music from bands that are unpopular or went defunct before streaming took off. I\u2019ve got a copy of <em>Apollo Me<\/em> by <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rival_State\"><em>Rival State<\/em><\/a> that I bought after seeing them play at a high school band competition.<sup id=\"fnref:rival-state\"><a href=\"#fn:rival-state\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">3<\/a><\/sup>  This is a great album that I would have listened to more if they\u2019d been accessible. Thankfully I had a CD rip in my aforementioned laptop backup so I didn\u2019t have to get the disk shipped over.<\/p>\n\n<h1 id=\"ripping-cds\">Ripping CDs<\/h1>\n\n<p>The cheat code to this whole process was my partner\u2019s CD collection, which admittedly doesn\u2019t have a huge overlap with what I want to listen to. However, it was a good way to bulk out my collection so it didn\u2019t feel so empty.<\/p>\n\n<p>Over three evenings I sat on the couch with an external CD drive connected to my laptop, slowly ripping each CD. The easiest way to do this on MacOS was in iTunes\/Apple Music. I left everything at the defaults and imported as M4A\u2014I can always re-rip or transcode if this ends up being problematic.<\/p>\n\n<p>One disk (<em>Songs for the Deaf<\/em> by <em>Queens of the Stone Age<\/em>) just failed to rip in iTunes. It managed to lock my whole laptop up to the point that Finder couldn\u2019t see new files being added (despite them being visible in the terminal). I rebooted and still wasn\u2019t able to read the disk. I tried using <a href=\"http:\/\/littlesvr.ca\/asunder\/\">Asunder<\/a> on my Linux laptop<sup id=\"fnref:linux-laptop\"><a href=\"#fn:linux-laptop\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">4<\/a><\/sup> and it worked fine. Not sure what was going wrong with iTunes here.<\/p>\n\n<h1 id=\"playing-music\">Playing Music<\/h1>\n\n<p>Acquiring music is only half the story. Actually listening to it is arguably more important.<\/p>\n\n<p>The easiest thing would probably be to copy the files across to my phone manually, and play them in Apple Music\u2014which does still support local playback of your iTunes library, like an iPod. This would mean storing the whole library on my phone, and copying anything new as I acquired it. I\u2019d also like to avoid using an app in a way it wasn\u2019t intended. It\u2019s fairly clear that the Music app is designed to be a client for the streaming service, not for playing your own local library.<\/p>\n\n<p>I didn\u2019t spend very long looking at other local-first players, as I was already pretty set on hosting a streaming system. Unsurprisingly I landed on <a href=\"https:\/\/www.navidrome.org\">Navidrome<\/a>, a self-hosted streaming service that supports standard APIs as well as its own API, allowing it to be used with a <a href=\"https:\/\/www.navidrome.org\/apps\/\">variety of client apps<\/a>.<\/p>\n\n<p>It was almost hilariously simple for me to set it up. I just copied the Docker compose config and made the appropriate changes to make it work with <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">Pod<\/a>. Once it started up it got an automatically-assigned subdomain and reverse proxy config from <a href=\"https:\/\/codeberg.org\/willhbr\/endash\">endash<\/a>, and I could access it in the browser. I made an account, and then I could sign in from a client app on my phone.<\/p>\n\n<p>The first iOS client I used was <a href=\"https:\/\/vkugler.app\">Shelv<\/a>. It\u2019s free, has a reasonable UI, and works fine. It let me test out the system without committing any money. I did find that whatever settings I had selected meant that it would eagerly try and load the whole song before actually playing anything. This added a 2-3 second delay before any song started, and would sometimes fail altogether. I don\u2019t know if this is my fault for turning on some pathological combination of settings, or Shelv not anticipating the crappy upload speed from my home internet. I downloaded most of my library via Shelv to avoid this, but that somewhat defeats the purpose of streaming, and anything that\u2019s not downloaded is still a poor experience.<\/p>\n\n<p>Instead, I\u2019ve been using <a href=\"https:\/\/nautiline.app\">Nautiline<\/a> which doesn\u2019t have these issues. It\u2019s paid\u2014$15\u2014but it has a generous 7-day free trial that only counts a day if you actually use the app. The UI structure is reasonably customisable, it even has options to appear more like a streaming app (showing a list of popular songs as the first element on an artist\u2019s page) or a more traditional \u201cMP3 player\u201d interface that just shows albums. Whatever Nautiline does when streaming agrees with my server and network setup, as I\u2019ve not run into any delays, drops, or stuttering so far.<\/p>\n\n<h1 id=\"whats-next\">What\u2019s Next<\/h1>\n\n<p>I\u2019ve spent more on music in the last three months than I would have if I\u2019d just kept Spotify. A lot more. But I\u2019ve also spent more time listing to music that I\u2019ve really enjoyed. It\u2019s been a fun project to collect my favourite music into one place.<\/p>\n\n<p>There\u2019s a really healthy number of Navidrome clients, and I don\u2019t lose anything by moving from Nautiline to a different one in the future. Or using two in parallel for different reasons. I could even stop using Navidrome altogether. Since I own the bytes of all this music, I\u2019m not limited to just playing through a particular piece of software. As long as I can play audio files, I\u2019ll have access to them.<sup id=\"fnref:backups\"><a href=\"#fn:backups\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">5<\/a><\/sup><\/p>\n\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:not-aud\">\n      <p>That\u2019s in USD, not AUD. I couldn\u2019t find a good reference with AUD prices.\u00a0<a href=\"#fnref:not-aud\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:ignoring-inflation\">\n      <p>Ignoring inflation, because I don\u2019t want to do maths here.\u00a0<a href=\"#fnref:ignoring-inflation\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:rival-state\">\n      <p>The singer told me and my friend that he liked the fact we had a synth in our otherwise-rock band. I still remember that 13 years later. Maybe that\u2019s why I went out and bought their album.\u00a0<a href=\"#fnref:rival-state\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:linux-laptop\">\n      <p>A story for another time.\u00a0<a href=\"#fnref:linux-laptop\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:backups\">\n      <p>This is partially enabled by <a href=\"\/2026\/07\/19\/backups-with-restic\/\">my more robust backup system<\/a>. The whole music library is 3-2-1 backed up.\u00a0<a href=\"#fnref:backups\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/09\/28\/owning-my-streaming-with-navidrome\/\">Permalink<\/a>\n&bull; September 28, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Owning%20My%20Streaming%20With%20Navidrome\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/09\/28\/owning-my-streaming-with-navidrome\/","image":"https:\/\/willhbr.net\/images\/2026\/cover-art.webp","date_published":"2026-09-28T00:00:00+10:00","date_modified":"2026-09-28T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/09\/25\/crystal-type-system-code\/","title":"Running Code in the Crystal Type System","content_html":"<p>This isn\u2019t really that surprising, but sometimes you\u2019ve just gotta point out the obvious stuff, you know? Anyway, Crystal\u2019s global type inference can be easily manipulated into doing arbitrary computations at compile time. Of course you can do whatever you want with macros, but this doesn\u2019t rely on a single syntax macro, and only lightly uses macro methods for convenience. The usage of macro methods can be removed, which I\u2019ll explain at the end.<\/p>\n\n<p>The rules of the game are that we can\u2019t use the <code>macro<\/code> keyword, and we can only use <code>{{ }}<\/code> for macro methods sparingly. For a slight extra challenge, we can\u2019t use <code>new<\/code> either. Not that it would be very useful\u2014it only does something at run time\u2014but the goal is to write code that will do as little as possible at runtime.<\/p>\n\n<p>Let\u2019s start with Crystal type inference. This function returns a <code>String<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get_message : String\n  return \"wow this is such a useful function!\"\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>You can tell by the <code>: String<\/code> after the method name. Crystal\u2019s main trick is that you can actually omit the type annotations in most places, so this function still returns a <code>String<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get_message\n  return \"omg no type annotations!\"\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>In this case, the return type is calculated based off the type of the value that is returned. That\u2019s simple for literals, but it also extends to variables:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get_message(msg : String)\n  return msg\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Since <code>msg<\/code> is annotated as a <code>String<\/code>, the return type is inferred to also be a <code>String<\/code>.<\/p>\n\n<p>Where this gets more complicated is if we omit the type annotation on <code>msg<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get_message(msg)\n  return msg\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The compiler can\u2019t infer the type of <code>msg<\/code> or the return type of the function since the whole snippet is missing any type annotations. This function is effectively a simple generic function on its one argument. In a language without global type inference\u2014like Rust\u2014you\u2019d write it like this:<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>fn get_message&lt;T&gt;(msg: T) -&gt; T {\n  return msg;\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This doesn\u2019t have any useful type information, but we\u2019ve told the compiler that the return type must match the type of the first argument exactly. If we call it with <code>get_message(\"Wow nice function!\".to_string())<\/code> then the return type will be <code>String<\/code>. Exactly how the generics are handled at runtime depends on a few factors and varies between languages. In a lot of languages\u2014and the model that I think is easiest to understand\u2014you effectively get an autogenerated method with the concrete type substituted in for <code>T<\/code>.<\/p>\n\n<p>In Crystal, every un-annotated argument acts like a generic type parameter. I can call <code>get_message(\"omg types!\")<\/code> and a specialisation for <code>String<\/code> will be generated, or I can call <code>get_message(1234)<\/code> and a specialisation for <code>Int32<\/code> is generated.<\/p>\n\n<p>So if we call <code>get_message<\/code> with different arguments, the return type will be different:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>typeof(get_message(123))\n# =&gt; Int32\ntypeof(get_message(\"Hello!\"))\n# =&gt; String\n<\/code><\/pre><\/div><\/div>\n\n<p>This isn\u2019t just a method that can return two different types; at compile time we know that the first call will only ever return an <code>Int32<\/code>, and the second call will only return a <code>String<\/code>. If the decision to return one type or the other was made at run time, the compile-time type would be <code>Int32 | String<\/code>.<\/p>\n\n<p>Crystal\u2019s macro system allows you to run arbitrary compile-time code during method expansion.<\/p>\n\n<p>To help ourselves debug, we can make a <code>print<\/code> method that calls a macro to print the type of its argument:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def print(arg : T) forall T\n  {% puts T %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>It doesn\u2019t do anything at runtime, but it lets us see the result of a type-system \u201ccomputation\u201d.<\/p>\n\n<p>Let\u2019s start with numbers. There\u2019s nothing stopping us from creating a new type that has a number as a type parameter:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Num(T)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>It doesn\u2019t look like much because there\u2019s nothing to say \u201c<code>T<\/code> must be a number!\u201d We just have to do that ourselves. Using our <code>print<\/code> \u201cfunction\u201d from before, we can get numbers:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>print Num(5).new\nprint Num(9).new\n<\/code><\/pre><\/div><\/div>\n\n<p>Somewhat uninterestingly, this prints <code>Num(5)<\/code> and then <code>Num(9)<\/code>. Sadly this is breaking our \u201cno <code>new<\/code>\u201d rule that we agreed on earlier, so we\u2019re going to have to introduce class types.<\/p>\n\n<p>If the return type of <code>get_message<\/code> is inferred to be <code>String<\/code>, then what does this return?<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get_string\n  String\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>That\u2019s right, <code>String.class<\/code>! It\u2019s basically <code>Class&lt;String&gt;<\/code> from Java land, but spelled weird. The important thing is that we can control the inferred return type without needing <code>.new<\/code>. This does mean we need to tweak <code>print<\/code> a little bit. Instead of extracting the type of the parameter into a type variable, we\u2019ll extract the type of the class of the parameter into a type variable. Type type class type parameter infer type type. It makes more sense when you see it:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def print(arg : T.class) forall T\n  {% puts T %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Now <code>print<\/code> doesn\u2019t accept an argument of type <code>T<\/code>, it accepts a <code>Class<\/code> of type <code>T.class<\/code>. In Java that would be written <code>T print&lt;T&gt;(Class&lt;T&gt; cls)<\/code>. The important thing is that I can call <code>print<\/code> without actually creating a new instance:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>print Num(5)\nprint Num(9)\n<\/code><\/pre><\/div><\/div>\n\n<p>That\u2019ll print the same thing as before, but we\u2019ve dropped both <code>new<\/code> calls.<\/p>\n\n<p>So after all that trouble, we can store numbers in the type system, mostly because Crystal lets us do it already. Well, just watch this, we\u2019re going to add some methods to our type that we can call at compile time.<\/p>\n\n<p>Of all the weird hacks here, I think this is the coolest. We can just write perfectly normal Crystal code with types, overloading, and everything and it\u2019ll all \u201crun\u201d at compile time. Here\u2019s how we can add two numbers together:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Num(T)\n  def self.+(r : Num(R).class) forall R\n    {% begin %}\n      Num({{ T + R }})\n    {% end %}\n  end\nend\n\nNum(5) + Num(6)\n# =&gt; Num(11)\n<\/code><\/pre><\/div><\/div>\n\n<p class=\"caption\">That <code>begin<\/code>\/<code>end<\/code> is just to tell the compiler to treat the whole thing as one unit to parse, otherwise it gets confused.<\/p>\n\n<p>This is easy because adding numbers together is something Crystal supports in its type system, as part of the macro language. <code>T<\/code> and <code>R<\/code> are type parameters, but they\u2019re actually both constant numbers known at compile time, and we can add them together. So <code>Num(T).+<\/code> operates on a <code>Num(T).class<\/code> and accepts another <code>Num(R).class<\/code>. Given those parameters, the return type is inferred by the single expression in the method body, which is based on <code>T + R<\/code>.<\/p>\n\n<p>A separate version of this method will be generated for every used combination of <code>T<\/code> and <code>R<\/code>. Each generated method will have the return type inferred from the generated body, which will be known at compile time before the program is run.<\/p>\n\n<p>It\u2019s probably easier to think about this with normal Crystal code:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>\"foo\" + \"bar\"\n1 + 2\n3 + 4.5\n<\/code><\/pre><\/div><\/div>\n\n<p>There are three different <code>+<\/code> methods that will have to be instantiated here. One that operates on two <code>String<\/code> objects, one that operates on two <code>Int32<\/code> values, and one that operates on an <code>Int32<\/code> and a <code>Float32<\/code>. Based on their parameters, they each return a different type (<code>String<\/code>, <code>Int32<\/code>, or <code>Float32<\/code>) all known at compile time.<\/p>\n\n<p>This isn\u2019t the only way to implement numbers\u2014it\u2019s definitely the most convenient\u2014but I\u2019ll get to the other way later.<\/p>\n\n<p>Crystal also makes it really easy to get lists into the type system. There is basically first-class support for it:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct List(*T)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>It\u2019s that simple! To make a list, you just build the type:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>List(Num(1), Num(2), Num(3))\n<\/code><\/pre><\/div><\/div>\n\n<p>The fact that generic type parameters are written with round brackets really makes this whole endeavour less bizarre-looking. Imagine that in Java-like syntax for a moment: <code>List&lt;Num&lt;1&gt;, Num&lt;2&gt;, Num&lt;3&gt;&gt;<\/code>. So weird!<\/p>\n\n<p>Just like with <code>Num<\/code>, we can define methods where the inferred return type gives us useful information:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct List(*T)\n  def self.[](index : Num(I).class) forall I\n    {{ T[I].instance }}\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Again, we\u2019re leaning heavily on Crystal\u2019s ability to introspect on types in the macro system. All we have to do is translate from the types used as parameters to the result we want. We can continue exposing the builtin macro methods to the type resolution system as \u201cmethods\u201d like this, just by defining methods on classes.<\/p>\n\n<p>To avoid using the macro system, we could just use linked lists. Type-system linked lists, obviously.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class Cons(H, T)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The list has a head (<code>H<\/code>) and a tail (<code>T<\/code>). The tail is itself just another <code>Cons<\/code> list, or <code>Nil<\/code> if that\u2019s the end of the list. We then just need to define a few helpers to create, concatenate, and destructure lists:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def newlist(item : I.class) : Cons(I, Nil).class forall I\n  Cons(I, Nil)\nend\n\ndef concat(item : I.class, rest : Cons(H, T).class) : Cons(I, Cons(H, T)).class forall I, H, T\n  Cons(I, Cons(H, T))\nend\n\ndef head(list : Cons(H, T).class) : H.class forall H, T\n  H\nend\n\ndef rest(list : Cons(H, T).class) : T.class forall H, T\n  T\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Numbers and lists are fine, but eventually we\u2019ll want structured data. We could use <code>NamedTuple<\/code>, which is the <a href=\"\/2026\/08\/15\/crystal-macro-sql-type-checking\/\">most versatile tool for Crystal type system hacks<\/a>. It would look something like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Struct(T)\nend\n\ndata = Struct(NamedTuple(\n  a: Num(1),\n  b: Num(2)\n))\n<\/code><\/pre><\/div><\/div>\n\n<p>Or you could define your own types and use generics as parameters:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code># N is name\n# E is extension\nstruct Language(N, E)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>When passed as an argument to a function, you can destructure it just like the <code>Cons<\/code> above.<\/p>\n\n<p>Conditionals are a bit tricky to manage, but conceptually aren\u2019t that complicated. We just define two types\u2014<code>True<\/code> and <code>False<\/code>\u2014and then make a method with different overloads depending on the parameter:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct True\nend\n\nstruct False\nend\n\ndef conditional(c : True.class)\n  # some code if our condition is true\nend\n\ndef conditional(c : False.class)\n  # some code if our condition is false\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>This works because the type system will work out the type of the argument being passed to <code>conditional<\/code>, and since the type of the argument can only be one of <code>True<\/code> or <code>False<\/code>, only one method is actually used by the program. Unused methods aren\u2019t type checked, and so they won\u2019t be \u201cevaluated\u201d as part of our type system program.<\/p>\n\n<p>To implement comparisons between numbers, you just make a macro method:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Num(T)\n  def self.&lt;(r : Num(R).class) forall R\n    {{ T &lt; R ? True : False }}\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Using a macro method does feel a little bit like cheating, which is a good time to mention that other way of implementing numbers. It works like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct One\nend\n\nstruct Zero\nend\n\nstruct Byte(A, B, C, D, E, F, G, H)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>We represent 42 as <code>Byte(Zero, Zero, One, Zero, One, Zero, One, Zero)<\/code>. Arithmetic operations can be done with function overloading. This gets a bit verbose, but as a quick example here\u2019s how you implement <code>AND<\/code> between two bits:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def and(l : One.class, r : One.class) : One.class\n  One\nend\n\ndef and(l, r) : Zero.class\n  Zero\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Call <code>and<\/code> with two <code>One<\/code> objects, and the return type is <code>One.class<\/code>. Call it with anything else, and it\u2019s a <code>Zero<\/code>. Repeat that for all the bits in the byte, and you\u2019re most of the way to a CPU.<\/p>\n\n<p>I did try and write a compiler that turns Python code into Crystal types that can be evaluated during the build stage, but the computation model is different enough that it was going to be a bunch of work. It would be better for a purely functional, side-effect-free language. Since the return type of each method is stored, calling the same method with the same types of arguments will always produce the same result.<\/p>\n\n<p>As I said at the beginning, it\u2019s not exactly surprising that you can do so much with the type system. I was more surprised at how easy it was. So next time you\u2019re getting frustrated at a slow build, just remember that it basically has to run your code in order to check your types.<\/p>\n\n<p>Maybe add some type annotations.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/09\/25\/crystal-type-system-code\/\">Permalink<\/a>\n&bull; September 25, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Running%20Code%20in%20the%20Crystal%20Type%20System\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/09\/25\/crystal-type-system-code\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["languages","crystal"],"date_published":"2026-09-25T00:00:00+10:00","date_modified":"2026-09-25T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/08\/17\/html-safe-string-interpolation\/","title":"HTML-Safe String Interpolation","content_html":"<p>Last year I made a version of ECR (the Crystal templating language) that <a href=\"\/2025\/11\/13\/html-safe-ecr-templates\/\">allows for automatic escaping of values injected into an HTML template<\/a>. This avoids having to litter your code with <code>HTML.escape<\/code> around everything that you put into the template.<\/p>\n\n<p>A little while after writing that post, I realised that it was a whole lot simpler if instead of using <code>to_s<\/code> to build my template, I created a new method, <code>to_html<\/code>. This got rid of the <code>Builder<\/code> and the <code>unsafe_write<\/code> and all that nonsense. Instead, a class can override <code>to_html(io : IO)<\/code> and write HTML content into the <code>IO<\/code>. If it don\u2019t implement it, the default implementation will proxy <code>to_s<\/code> through an <code>HTMLEscapingIO<\/code> that calls <code>HTML.escape<\/code> on any data as it\u2019s written.<\/p>\n\n<p>This made it easier to implement \u201cpartials\u201d that can be placed into a larger template, just by creating objects that override <code>to_html<\/code>. You can see the new code <a href=\"https:\/\/codeberg.org\/willhbr\/geode\/src\/branch\/main\/src\/geode\/html_safe_ecr.cr\">on Codeberg<\/a>.<\/p>\n\n<p>HTML-safe ECR is cool, but sometimes you just want to build a quick and dirty string, without making a separate file. Something like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def homepage_link\n  \"&lt;a href=\\\"\/home\\\"&gt;#{HTML.escape @title}&lt;\/a&gt;\"\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Now we\u2019re back to wrapping everything in <code>HTML.escape<\/code>, and we\u2019re <a href=\"\/2025\/11\/07\/tracking-down-progressively-enhanceable-apis\/\">allocating an intermediate <code>String<\/code> unnecessarily<\/a>. To avoid that allocation, we could use <code>String.build<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def homepage_link\n  String.build do |io|\n    io &lt;&lt; \"&lt;a href=\\\"\/home\\\"&gt;\"\n    HTML.escape @title, io\n    io &lt;&lt; \"&lt;\/a&gt;\"\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>We\u2019ve made it more efficient, but we\u2019ve also made it verbose and terrible.<\/p>\n\n<p>You know the drill. We can solve this with macros.<\/p>\n\n<p>In the syntax tree, a string interpolation is distinct from a regular string as it actually has to be built at run time. I assume this is basically just doing <code>String.build<\/code>, but I haven\u2019t checked.<\/p>\n\n<p>We can make a macro that takes a <a href=\"https:\/\/crystal-lang.org\/api\/1.21.0\/Crystal\/Macros\/StringInterpolation.html\"><code>StringInterpolation<\/code> node<\/a> as an argument, and iterate through each of its <code>expressions<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro interpolate(literal)\n  {% for expr in literal.expressions %}\n    {% p expr %}\n  {% end %}\nend\n\ninterpolate \"&lt;h1&gt;#{title}&lt;\/h1&gt;\"\n<\/code><\/pre><\/div><\/div>\n\n<p>At compile time, that\u2019ll print out the components of our string:<\/p>\n\n<div class=\"language-shell highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ crystal build example.cr\n\"&lt;h1&gt;\"\ntitle\n\"&lt;\/h1&gt;\"\n<\/code><\/pre><\/div><\/div>\n\n<p>Now we just need to use those to build a string:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro interpolate(literal)\n  String.build do |%io|\n    {% for expr in literal.expressions %}\n      {% if expr.is_a? StringLiteral %}\n        %io &lt;&lt; {{ expr }}\n      {% else %}\n        ({{ expr }}).to_html(%io)\n      {% end %}\n    {% end %}\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>That will produce code that looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>String.build do |__temp_94|\n  __temp_94 &lt;&lt; \"&lt;h1&gt;\"\n  (title).to_html __temp_94\n  __temp_94 &lt;&lt; \"&lt;\/h1&gt;\"\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>This does the same thing that the ECR templating does: instead of calling <code>to_s<\/code> on the values to be interpolated, it calls <code>to_html<\/code>. If a class doesn\u2019t override <code>to_html<\/code>, they get the default implementation that does the escaping automatically:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class Object\n  def to_html(io : IO)\n    self.to_s Geode::HTMLSafeECR::HTMLEscapingIO.new(io)\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>There\u2019s only one last trick: we need to mark the resulting <code>String<\/code> as safe to use in an HTML template. Otherwise, if someone calls <code>to_html<\/code> on it, it\u2019ll automatically get proxied through the <code>HTMLEscapingIO<\/code> and all our HTML-building will be lost in a sea of <code>&amp;gt;<\/code> and <code>&amp;lt;<\/code>.<\/p>\n\n<p>I already have a <code>.html_safe<\/code> extension method on <code>String<\/code> that returns a <code>SafeString<\/code>, which forgoes further escaping. That leaves us with a final macro:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro interpolate(literal)\n  {% if literal.is_a? StringLiteral %}\n    ({{ literal }}).html_safe\n  {% elsif literal.is_a? StringInterpolation %}\n    (String.build do |%io|\n      {% for expr in literal.expressions %}\n        {% if expr.is_a? StringLiteral %}\n          %io &lt;&lt; {{ expr }}\n        {% else %}\n          ({{ expr }}).to_html(%io)\n        {% end %}\n      {% end %}\n    end).html_safe\n  {% else %}\n    {% raise \"argument to interpolate must be string, not '#{literal}'\" %}\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>You don\u2019t have to do anything special to support multiline strings, or strings with other delimiters. You could even build a whole HTML file this way:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>interpolate %(\n  &lt;!doctype html&gt;\n  &lt;html&gt;\n    &lt;head&gt;\n      &lt;title&gt;#{title}&lt;\/title&gt;\n    &lt;\/head&gt;\n    &lt;body&gt;\n      #{content}\n    &lt;\/body&gt;\n  &lt;\/html&gt;\n)\n<\/code><\/pre><\/div><\/div>\n\n<p>I did think about hacking in some live-reloading (like <a href=\"\/2025\/11\/17\/hot-ecr-reloading-in-your-area\/\">I did with ECR<\/a>) but you\u2019d have to re-parse the whole Crystal source file and try to find the right <code>interpolate<\/code> call, which would be difficult. You could get away with using <code>#line_number<\/code> and <code>#column_number<\/code> on the <code>StringInterpolation<\/code> node, but that would fall down if there were two <code>interpolate<\/code> calls in the same file.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/08\/17\/html-safe-string-interpolation\/\">Permalink<\/a>\n&bull; August 17, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20HTML-Safe%20String%20Interpolation\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/08\/17\/html-safe-string-interpolation\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-08-17T00:00:00+10:00","date_modified":"2026-08-17T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/08\/15\/crystal-macro-sql-type-checking\/","title":"Type-Checking SQL Queries With Crystal Macros","content_html":"<p>The aim of the game here is to use as few macros as possible. I could just have one macro that parses an SQL query, but the fun here is to use the Crystal type system to check the query for us, similar to how I <a href=\"\/2026\/01\/31\/crystal-dependency-injection\/\">used the type system to implement dependency injection<\/a>. I\u2019ll be avoiding macros, but I\u2019ll be using macro <em>methods<\/em> heavily, as they let you introspect on the types of variables.<\/p>\n\n<p>The API should also be decomposable, which is more difficult with regular macros. You should be able to split up the query like you would any other expression and have it work as expected, maybe after including a few type annotations.<\/p>\n\n<p>What makes this process easier is modelling the queries on <a href=\"https:\/\/research.google\/pubs\/sql-has-problems-we-can-fix-them-pipe-syntax-in-sql\/\">SQL pipe syntax<\/a>, instead of traditional SQL. Pipe syntax is conceptually simpler, as each statement is just a transform of the output of the previous statement, and this will make our type-checking much easier.<\/p>\n\n<p>If you\u2019ve not come across the pipe syntax, you can take this query:<\/p>\n\n<div class=\"language-sql highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>SELECT name, computer_count\nFROM people\nWHERE computer_count &gt; 5\nORDER BY name\n<\/code><\/pre><\/div><\/div>\n\n<p>And rewrite it as a pipeline:<\/p>\n\n<div class=\"language-sql highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>FROM people\n|&gt; WHERE computer_count &gt; 5\n|&gt; SELECT name, computer_count\n|&gt; ORDER BY name\n<\/code><\/pre><\/div><\/div>\n\n<p>You can just keep tacking on extra steps to the query, which avoids needing nested queries in many cases. As a slightly contrived example, say I wanted to get the alphabetically last person with more than five computers:<\/p>\n\n<div class=\"language-sql highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>FROM people\n|&gt; WHERE computer_count &gt; 5\n|&gt; ORDER BY name DESC\n|&gt; SELECT name\n|&gt; LIMIT 1\n<\/code><\/pre><\/div><\/div>\n\n<p>You get the idea. The important thing to note is that you can fairly easily translate these pipeline queries into quite ugly, very nested regular SQL queries. A query optimiser should be able to translate that back into a sensible query plan, but we\u2019re not here to worry about that, we\u2019re here to do naughty things with macros.<\/p>\n\n<p>The pipeline syntax matches really well with method chaining, so the goal is to build queries somewhat like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>People\n  .where(computer_count &gt; 5)\n  .order_by(:name)\n  .select(:name)\n  .limit(1)\n<\/code><\/pre><\/div><\/div>\n\n<p>The other ingredient that makes this whole escapade work is <a href=\"https:\/\/crystal-lang.org\/api\/latest\/NamedTuple.html\">named tuples<\/a>. They\u2019re unlike other types in Crystal in that the names of the fields are part of the type itself, which you can introspect with macros. We\u2019ll use lots of generics, and using a named tuple as the generic type allows us to encode the structure of a table as a type\u2014since what are tables if not a collection of names and types?<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def inspect(var : T) forall T\n  {% for name, type in T %}\n    {% puts \"#{name}: #{type}\" %}\n  {% end %}\nend\n\nnt = {\n  name: \"Will\",\n  admin: true\n}\ninspect(nt)\n<\/code><\/pre><\/div><\/div>\n\n<p>There\u2019s a lot going on here, but it\u2019s got the main tricks we need to do this whole thing. <code>inspect<\/code> is a macro method, where the body is generated from macro code once for each set of input types. We call it once with the variable <code>nt<\/code>, which has the type <code>NamedTuple(name: String, admin: Bool)<\/code>. In the actual <code>inspect<\/code> method we introduce a type variable <code>T<\/code> with the <code>forall T<\/code> suffix. This is more akin to the little <code>&lt;T&gt;<\/code> you\u2019d find in <code>fn foo&lt;T&gt;(arg: T) { ... }<\/code>. The <code>forall<\/code> doesn\u2019t actually mean that it needs to work for any type <code>T<\/code>, you can just <code>raise<\/code> an exception in the macro code and fail for a particular type. It\u2019ll also only be attempted on types that are used to call the function.<\/p>\n\n<p>The type variable can be accessed from the macro code, whereas the actual variable <code>var<\/code> obviously cannot. Since we\u2019ve got <code>T<\/code> and we know it\u2019s some kind of <code>NamedTuple<\/code>, we can iterate over it to pull out the field names and types. This program won\u2019t actually do anything at runtime, but at compile time it\u2019ll print:<\/p>\n\n<pre><code>name: String\nadmin: Bool\n<\/code><\/pre>\n\n<p>As a basis for the whole query system, we\u2019ll define a generic interface <code>Source(T)<\/code>. This could either be a definition of a table, or some query on a table that produces a schema of type <code>T<\/code>, which we\u2019ll just ensure is always a <code>NamedTuple<\/code>.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Source(T)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>We\u2019ll then implement a source that reads from a table:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct TableSource(T)\n  include Source(T)\n\n  def initialize(@name : String)\n  end\n\n  def to_sql(params : Deque(DB::Any)) : String\n    \"SELECT * FROM #{@name}\"\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>You could construct this manually, but we can be civilised and use a macro to build one based on the instance variables in a data object:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Table\n  macro included\n    {% verbatim do %}\n      def self.query\n        {% begin %}\n          TableSource(NamedTuple(\n            {% for var in @type.instance_vars %}\n              {{ var.name }}: {{ var.type }},\n            {% end %}\n          )).new({{ @type.name.stringify.downcase }})\n        {% end %}\n      end\n    {% end %}\n  end\nend\n\nclass User\n  include Table\n  getter name : String\n  getter computer_count : Int32\n\n  def initialize(@name, @computer_count)\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>We can then just do <code>User.query<\/code> and we\u2019ve got an appropriate <code>Source<\/code> for that table. Calling <code>to_sql<\/code> on that <code>TableSource<\/code> object would simply give us <code>SELECT * FROM user<\/code>.<\/p>\n\n<h1 id=\"select\"><code>SELECT<\/code><\/h1>\n\n<p>The simplest transformation you can do in SQL is a <code>SELECT<\/code>, where you take the fields you have access to and return a different set of fields, usually a subset. We\u2019ll ignore computed properties for now and just handle selecting a subset of the fields.<\/p>\n\n<p>On second thought it\u2019s not that much simpler than anything else, but this is where I started anyway.<\/p>\n\n<p>All the operations will be defined as methods on the <code>Source(T)<\/code> module, and they\u2019ll return another <code>Source<\/code>, probably of a different type. This is how the pipelining will work. In the simplest case, a <code>SELECT<\/code> from <code>Source(T)<\/code> will return a <code>Source(R)<\/code> where <code>R<\/code> is a strict subset of the fields in <code>T<\/code>.<\/p>\n\n<p>Anyway, the most basic version of <code>select<\/code> looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Source(T)\n  def select(**kwargs : K) forall K\n    # the macro system is dynamically typed, so the type here doesn't matter\n    {% fields = {} of String =&gt; Nil %}\n    {% for name, type in T %}\n      {% fields[name] = type %}\n    {% end %}\n    {% for name, type in K %}\n      {% if fields[name].nil?\n           raise \"unknown field: #{name}\"\n         end %}\n    {% end %}\n    Select(T, NamedTuple(\n      {% for name, type in K %}\n        {{ name }}: {{ fields[name] }},\n      {% end %}\n    )).new(kwargs)\n  end\nend\n\n\nclass Select(F, T)\n  include Source(T)\n\n  def initialize(@source : Source(F), @fields : ...)\n  end\nend\n\nUser.query.select(name: String)\n<\/code><\/pre><\/div><\/div>\n\n<p>Inside the <code>select<\/code> method, we can use macros to inspect both <code>T<\/code> (the structure of the source table or query) and <code>K<\/code> (the fields that we want to select down to) and produce a <code>Select<\/code> object with the right type parameters. The type signature of the <code>select<\/code> method can just omit the return type and have the compiler fill that in, since there\u2019s no way to describe the nonsense we\u2019re doing here (filtering down from one set of fields to another).<\/p>\n\n<p>This approach is a bit of a dead end, however. We won\u2019t be able to use this model to select arbitrary expressions (like <code>computer_count &gt; 4 AS many_computers<\/code>) and when we try to find a type for <code>@fields<\/code> we\u2019ll run into this limit.<\/p>\n\n<p>The other problem with it is that you have to provide types for the fields you\u2019re selecting (like <code>name: String<\/code>) but we\u2019re not even checking that the type is correct. Type-checking this is a little tricky, since the argument isn\u2019t of type <code>NamedTuple(name: String)<\/code> it\u2019s of <code>NamedTuple(name: String.class)<\/code>, so simple equality checking won\u2019t work.<\/p>\n\n<p>To get proper type-checking and computed properties, the <code>Select<\/code> class needs to have more generics\u2014the source, destination, and fields all need to be their own separate type variables. The <code>Select<\/code> class is fairly simple:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class Select(F, T, K)\n  include Source(T)\n\n  def initialize(@source : Source(F), @args : K)\n  end\n\n  def to_sql(params : Deque(DB::Any)) : String\n    String.build do |io|\n      io &lt;&lt; \"SELECT \"\n      @args.each_with_index do |name, arg, idx|\n        io &lt;&lt; \", \" unless idx.zero?\n        case arg\n        when Expr\n          io &lt;&lt; arg.to_sql &lt;&lt; \" AS \" &lt;&lt; name\n        else\n          io &lt;&lt; name\n        end\n      end\n      io &lt;&lt; \" FROM (\"\n      io &lt;&lt; @source.to_sql(params)\n      io &lt;&lt; \")\"\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p><code>F<\/code> is the schema we\u2019re mapping from, <code>T<\/code> is the schema we map to, and <code>K<\/code> is how we\u2019re mapping between them. Although to do this properly we need to handle expressions.<\/p>\n\n<h1 id=\"expressions\">Expressions<\/h1>\n\n<p>Any sufficiently complicated SQL query will compute values on the fly in <code>SELECT<\/code>, but even the simplest queries will use expressions in the <code>WHERE<\/code> clause. This would be easy to do as a little DSL with no type-checking, but that\u2019s amateur hour stuff. To do type-checking, we need more generics.<\/p>\n\n<p>What we need is for the name of the variables that we\u2019re accessing to be available in the type system. When we use them in our query, the transform functions (like <code>select<\/code> or <code>where<\/code>) can check that a column with that name actually exists when it\u2019s building the type of the result. We\u2019ll do this with <code>ExprWithVar(P, T)<\/code>. <code>P<\/code> is a <code>NamedTuple<\/code> of the fields we\u2019re reading, and <code>T<\/code> is the return type of the expression. This expression:<\/p>\n\n<div class=\"language-sql highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>computer_count &gt; 4\n<\/code><\/pre><\/div><\/div>\n\n<p>Would have the type <code>ExprWithVar(NamedTuple(computer_count: Int32), Bool)<\/code>. A limitation here is that we have to include the type of the variable (<code>Int32<\/code>), but there are some shortcuts to help that we\u2019ll get to later.<\/p>\n\n<p>Just like our <code>Source<\/code> module, we can define extra methods on <code>ExprWithVar<\/code> to build more complicated expressions. The basis of this is an <code>Expr<\/code> type that represents any kind of expression. That can be an expression accessing a variable (<code>ExprWithVar<\/code>), or a constant value (<code>ConstExpr<\/code>) , or an expression based on two other subexpressions (<code>BiExpr<\/code>). You could also implement wrappers for SQL functions, and do type-checking based on their arguments and return values.<\/p>\n\n<p>I didn\u2019t go too far with this, but someone with more time could add all the necessary boilerplate. Here\u2019s the basic structure of a <code>&gt;<\/code> operator that can either operate on two expressions, or a constant value.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def &gt;(other : R) forall R\n  {% if R &lt; Expr %}\n    {% if R.type_vars[1] != T\n         raise \"#{R} can't be compared with #{T}\"\n       end %}\n    {% begin %}\n      {% fields = {} of Symbol =&gt; Nil %}\n      {% for name, type in P %}\n        {% fields[name] = type %}\n      {% end %}\n      {% for name, type in R.type_vars[0] %}\n        {% if (t = fields[name]) &amp;&amp; t != type\n             raise \"mismatching types: #{t} != #{type}\"\n           end\n           fields[name] = type %}\n      {% end %}\n      {% puts fields %}\n      BiExpr(NamedTuple(\n        {% for name, type in fields %}\n          {{ name }}: {{ type }},\n        {% end %}\n        ), Bool, T, {{ R.type_vars[1] }}).new(self, other, \"&gt;\")\n    {% end %}\n  {% else %}\n    BiExpr(P, Bool, T, R).new(self, ConstExpr(R).new(other), \"&gt;\")\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>What\u2019s a bit of a hack is that we have to keep the type variables in the same place across different types, so that we can pull out the field names and return type correctly. I\u2019ve made it so the names are always first, and the type is always second.<\/p>\n\n<p>It would be great if you could instead cast a particular type to another (in this case <code>ExprWithVar<\/code> to <code>Expr<\/code>) and then access the type variables that it implements that interface with. For example, I don\u2019t think there\u2019s any simple way to find what type of <code>Expr<\/code> this <code>ComparisonExpr<\/code> is:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class ComparisonExpr(P)\n  include Expr(Bool)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>It can obviously be used as an <code>Expr(Bool)<\/code>, but as far as I\u2019m aware you can\u2019t access that from a <code>TypeNode<\/code> in a macro. I solved this by adding type variables that are not strictly necessary, just so the information was easier to access. I have <code>ComparisonExpr(P, T)<\/code> where <code>T<\/code> is only ever <code>Bool<\/code>, but it means I can grab that type with <code>.type_vars[1]<\/code>.<\/p>\n\n<p>Going back to our <code>select<\/code> method, the extra type parameter <code>K<\/code> will be a <code>NamedTuple<\/code> where the fields match those in <code>T<\/code>, but all the types will be an <code>Expr(R)<\/code> where <code>R<\/code> matches the type of the field in <code>T<\/code>.<\/p>\n\n<p>Simple, right?<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def select(**kwargs : K) forall K\n  {% begin %}\n    {% source_fields = {} of String =&gt; String\n       dest_fields = {} of String =&gt; String %}\n    {% for name, type in T %}\n      {% source_fields[name] = type %}\n    {% end %}\n    {% for name, type in K %}\n      {% if type &lt;= Passthrough %}\n        {% if source_fields[name].nil?\n             raise \"missing field #{name}\"\n           end %}\n        {% dest_fields[name] = source_fields[name] %}\n        {{ name }} : Expr({{ source_fields[name] }}) = (\n          VarExpr(NamedTuple({{ name }}: {{ source_fields[name] }}), {{ source_fields[name] }}).new)\n      {% elsif type &lt;= Expr %}\n        {% dest_fields[name] = type.type_vars[1] %}\n        {% for input_var, input_type in type.type_vars[0] %}\n          {% if source_fields[input_var].nil? || source_fields[input_var] != input_type\n               raise \"type mismatch: #{input_var}: #{input_type} != #{source_fields[input_var]}\"\n             end %}\n        {% end %}\n        {{ name }} : Expr({{ type.type_vars[1] }}) = kwargs[:{{ name }}]\n      {% else %}\n        {% raise \"unknown type #{type}, should be Expr or Passthrough\" %}\n      {% end %}\n    {% end %}\n\n    Select(T, NamedTuple(\n      # Output types\n      {% for name, type in dest_fields %}\n        {{ name }}: {{ type.id }},\n      {% end %}\n    ), NamedTuple(\n      # Expression types\n      {% for name, type in dest_fields %}\n        {{ name }}: Expr({{ type.id }}),\n      {% end %}\n    )).new(self, {\n      # Expression values\n      {% for name, type in dest_fields %}\n        {{ name }}: {{ name }},\n      {% end %}\n    })\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The first part of this method is doing the type-checking by introspecting on the variables in any expressions and making sure the types of those variables match the types in the source table:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>{% dest_fields[name] = type.type_vars[1] %}\n{% for input_var, input_type in type.type_vars[0] %}\n  {% if source_fields[input_var].nil? || source_fields[input_var] != input_type\n       raise \"type mismatch: #{input_var}: #{input_type} != #{source_fields[input_var]}\"\n     end %}\n{% end %}\n<\/code><\/pre><\/div><\/div>\n\n<p>The last bit is just building the right generic arguments for the <code>Select<\/code> so it has the right input, output, and transformation types.<\/p>\n\n<p>As a shortcut I\u2019ve also made a <code>Passthrough<\/code> type, which is special-cased to lookup the field in the source table and add it directly to the output.<\/p>\n\n<p>The type of a <code>Select<\/code> that maps from the <code>User<\/code> table to just select the <code>name<\/code> field would be:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>Select(\n  NamedTuple(name: String, computer_count: Int32),\n  NamedTuple(name: String),\n  NamedTuple(name: ExprWithVar(NamedTuple(name: String), String)))\n<\/code><\/pre><\/div><\/div>\n\n<h1 id=\"where\"><code>WHERE<\/code><\/h1>\n\n<p>Once we\u2019ve got expressions, <code>WHERE<\/code> statements are actually really easy. The simplest case is just passing a single <code>Expr<\/code> to <code>where<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def where(expr : R) forall R\n  {% unless R &lt; Expr(Bool)\n       raise \"#{R} is not a boolean expression\"\n     end %}\n  {% if R &lt; ExprWithVar %}\n    {% fields = {} of String =&gt; String %}\n    {% for name, type in T %}\n      {% fields[name] = type %}\n    {% end %}\n    {% for name, type in R.type_vars[0] %}\n      {% if fields[name].nil?\n           raise \"unknown field #{name} in #{T}\"\n         end %}\n    {% end %}\n  {% end %}\n  WhereExpr(T).new(self, expr)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>You don\u2019t need to build up any complicated types, because the expression has to return a boolean, and the structure of the table doesn\u2019t change. <code>WhereExpr<\/code> just needs to build the SQL:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class WhereExpr(T)\n  include Source(T)\n\n  def initialize(@source : Source(T), @expr : Expr(Bool))\n  end\n\n  def to_sql(params : Deque(DB::Any)) : String\n    String.build do |io|\n      io &lt;&lt; \"SELECT * FROM (\"\n      io &lt;&lt; @source.to_sql(params)\n      io &lt;&lt; \") WHERE \"\n      io &lt;&lt; @expr.to_sql(params)\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>I also added a special-case where you can use keyword arguments as intended to do simple equality checks on multiple fields, allowing for <code>.where(name: \"Will\")<\/code>.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Source(T)\n  def where(**kwargs)\n    WhereEq(T, typeof(kwargs)).new(self, kwargs)\n  end\nend\n\nclass WhereEq(T, Q)\n  include Source(T)\n\n  def initialize(@source : Source(T), @query : Q)\n  end\n\n  def to_sql(params : Deque(DB::Any)) : String\n    String.build do |io|\n      io &lt;&lt; \"SELECT * FROM (\"\n      io &lt;&lt; @source.to_sql(params)\n      io &lt;&lt; \") WHERE \"\n      {% for name, type in Q %}\n        io &lt;&lt; {{ name.stringify }} &lt;&lt; \" = ?\"\n        params &lt;&lt; @query[:{{ name }}]\n        io &lt;&lt; \" AND \"\n      {% end %}\n      io &lt;&lt; \"TRUE\"\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p><code>Q<\/code> will have a subset of the fields in <code>T<\/code>, and I should probably check that the types match up here, but I didn\u2019t. Oh well.<\/p>\n\n<h1 id=\"sugar\">Sugar<\/h1>\n\n<p>Up until this point the main party trick has been doing weird things with named tuples in macros to skirt around the type system. Well I have at least one other trick.<\/p>\n\n<p>Calling <code>where<\/code> with an expression is not particularly ergonomic. Even if you made a macro to help define typed variables, like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro field(name)\n  VarExpr(NamedTuple({{ name.var }}: {{ name.type }}), {{ name.type }}).new\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Your <code>where<\/code> would still be repetitive:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>users.where(\n  field(computer_count : Int32) &gt; 30\n)\n<\/code><\/pre><\/div><\/div>\n\n<p>You have to repeat the type of <code>computer_count<\/code>, which just isn\u2019t good enough. Thankfully there\u2019s a solution:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Source(T)\n  def where(&amp;)\n    {% begin %}\n      b = WhereBlock(NamedTuple(\n        {% for name, type in T %}\n          {{ name }}: VarExpr(NamedTuple({{ name }}: {{ type }}), {{ type }}),\n        {% end %}\n      )).new({\n        {% for name, type in T %}\n          {{ name }}: VarExpr(NamedTuple({{ name }}: {{ type }}), {{ type }}).new,\n        {% end %}\n      })\n      cond = with b yield\n      WhereExpr(T).new(self, cond)\n    {% end %}\n  end\nend\n\nclass WhereBlock(T)\n  def initialize(@data : T)\n  end\n\n  macro method_missing(call)\n    @data[:{{ call.name }}]\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>It\u2019s surprisingly simple, but it took a little bit of work to get there. <code>WhereBlock<\/code> is simply a wrapper that provides <code>method_missing<\/code> delegation to the fields in a <code>NamedTuple<\/code>, returning an appropriate <code>VarExpr<\/code> with the right type. This simplifies the call down to:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>users.where { computer_count &gt; 5 }\n<\/code><\/pre><\/div><\/div>\n\n<p>Without losing any type safety. If you try to access a variable that doesn\u2019t exist, you\u2019ll get an error, as expected.<\/p>\n\n<p>Interestingly I wasn\u2019t able to access <code>T<\/code> in <code>method_missing<\/code> or in a <code>finished<\/code> macro to generate the methods more explicitly. Using a named tuple here seems to just kick the type-checking can down the road long enough to let this code compile.<\/p>\n\n<p>The other syntactic sugar I added was a <code>fields<\/code> macro to make calling <code>select<\/code> easier:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro fields(*args, **kwargs)\n  {\n    {% for arg in args %}\n      {{ arg }}: Passthrough.new,\n    {% end %}\n    {% for name, type in kwargs %}\n      {{ name }}: {{ type }},\n    {% end %}\n  }\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The call site is still a bit noisy, but you can remove some type annotations:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>users.select(\n  **fields(name, many_computers: field(computer_count : Int32) &gt; 5))\n<\/code><\/pre><\/div><\/div>\n\n<p>To be honest I could probably extend this macro to wrap the value of the named arguments in a block, and then use the same <code>WhereBlock<\/code> trick with <code>method_missing<\/code>. Hang on a second, that seems doable\u2026<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Source(T)\n  def select(&amp;)\n    {% begin %}\n      s = SelectBlock(NamedTuple(\n        {% for name, type in T %}\n          {{ name }}: VarExpr(NamedTuple({{ name }}: {{ type }}), {{ type }}),\n        {% end %}\n      )).new({\n        {% for name, type in T %}\n          {{ name }}: VarExpr(NamedTuple({{ name }}: {{ type }}), {{ type }}).new,\n        {% end %}\n      })\n      sel = with s yield\n      select_impl(sel)\n    {% end %}\n  end\nend\n\nclass SelectBlock(T)\n  def initialize(@data : T)\n  end\n\n  macro method_missing(call)\n    @data[:{{ call.name }}]\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>This works basically the same way as using a block for <code>where<\/code>. The <code>SelectBlock<\/code> class implementation is actually identical, so they could be shared. The block passed to <code>select<\/code> just needs to return a <code>NamedTuple<\/code>, and it can access the existing fields as variables with the same <code>method_missing<\/code> trick. The call site looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>User.query.select do\n  {\n    name: name,\n    many_computers: computer_count &gt; 5\n  }\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>You could do a similar trick where you return a <code>Tuple<\/code> of fields instead of a <code>NamedTuple<\/code>, and autogenerate the column names, like most databases do with normal SQL.<\/p>\n\n<p>I did implement a basic <code>JOIN<\/code>, which is just a method that takes two <code>Source<\/code> objects and an expression, and returns a <code>Source<\/code> with the union of the two sets of fields. A lot of this is just really messy macro programming, rather than any new tricks, so I won\u2019t go into depth on that one. If you\u2019re interested you can see all the code <a href=\"https:\/\/codeberg.org\/willhbr\/crystal-sql-type-checker\">on Codeberg<\/a>.<\/p>\n\n<p>This is absolutely all just a proof of concept, I don\u2019t expect anyone to use this in an actual application. The type-checking is pretty low effort, and I haven\u2019t tested it. It is of course a testament to the <a href=\"\/2026\/01\/31\/crystal-dependency-injection\/\">weird and wonderful things<\/a> you can do with Crystal\u2019s macro system. This process would be a little easier if I could introspect on types\u2019 conformance to certain interfaces, and if the type variable was accessible in more places. Although I don\u2019t know if there are good reasons or limitations that make these impossible.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/08\/15\/crystal-macro-sql-type-checking\/\">Permalink<\/a>\n&bull; August 15, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Type-Checking%20SQL%20Queries%20With%20Crystal%20Macros\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/08\/15\/crystal-macro-sql-type-checking\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["languages","crystal"],"date_published":"2026-08-15T00:00:00+10:00","date_modified":"2026-08-15T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/07\/19\/backups-with-restic\/","title":"Backups With Restic","content_html":"<p>Every year on March 31st I have a sense of minor guilt, anxiety, and sheepishness. It\u2019s <a href=\"https:\/\/www.worldbackupday.com\/en\/\">World Backup Day<\/a> and I don\u2019t have good backups. The purpose of the day is to serve as a reminder to check that your backup system is functioning, that you can restore from your backups, and that all your data is included in the backup system.<\/p>\n\n<p>It\u2019s not like I don\u2019t have backups of my data, it\u2019s just they\u2019re not <em>backup<\/em> backups, you know? I could probably find a second copy of the most important stuff, or anything I\u2019d lose isn\u2019t that hard to reproduce. I\u2019ve never had a computer fail or catastrophic accident, so I\u2019ve never had to test this theory. The only significant piece of data I self-host is <a href=\"\/2024\/02\/21\/a-successful-experiment-in-self-hosted-rss-reading\/\">my RSS subscriptions<\/a>, and that data is synced to the client on my phone, so I can just re-upload the OPML file.<\/p>\n\n<p>You see what I\u2019m like? I\u2019m skirting around having a real system based on somewhat vague recovery assumptions. Well that changes today. Actually that changed two months ago, but I\u2019m only writing about it now.<\/p>\n\n<p>I\u2019d like to be able to say I\u2019ve got a solid system and explain how it fits together, but this is much more of a work in progress. I\u2019m hoping that by writing out all my problems it\u2019ll make it easier to see what the best solution is.<\/p>\n\n<h1 id=\"wills-backup-history\">Will\u2019s Backup History<\/h1>\n\n<p>I\u2019ve written about this before when I <a href=\"\/2023\/07\/03\/picking-a-synology\/\">explained how I picked my Synology<\/a> a few years ago, but I\u2019ll forgive you for not remembering. I didn\u2019t even remember that it was in that post.<\/p>\n\n<p>My existing backup system was absolutely rickety. It basically revolved around everything running <code>rsync<\/code> to get files onto the Synology, and then <a href=\"\/2023\/03\/07\/installing-rsnapshot-on-synology-ds420j\/\">running <code>rsnapshot<\/code> on the Synology<\/a> to create a daily snapshot of all those files. Some things would run <code>rsync<\/code> to get files onto my \u201cmain\u201d home server, so that when <em>that<\/em> synced, the files would be included.<\/p>\n\n<p>In theory this means I can go to any of the snapshots and see the state my computer was in for that day. In reality there was no guarantee that the <code>rsync<\/code> command on the server had run, so the <code>rsnapshot<\/code> command on the Synology might be creating meaningless copies. Or the <code>rsync<\/code> command could have failed part way, so <code>rsnapshot<\/code> could instead be propagating a state that never actually existed.<\/p>\n\n<p>The furthest these backups got was my Synology, which sits right next to my other servers. It does have 1-disk redundancy, so it\u2019s a fair bit more resilient to hardware failures, but it\u2019s still living in my apartment. If a micrometeorite crashed into my apartment and collided with that bit of shelf, I\u2019d be out of luck.<\/p>\n\n<h1 id=\"restic\">Restic<\/h1>\n\n<p>The tool I\u2019ve decided to use is <a href=\"https:\/\/restic.net\/\">Restic<\/a>. It\u2019s a command-line tool written in Go, available in all major package managers, and available on all major platforms. This is great because it means backups on my Mac could be restored onto a Linux machine, or vice versa. If I\u2019m dealing with catastrophic data loss, I\u2019d rather not be worrying about finding the right type of hardware to restore onto.<\/p>\n\n<p>Restic chunks your data up and stores each backup run as a snapshot with a unique identifier. When a chunk of data isn\u2019t referenced by any snapshot, it can be deleted. New snapshots only have to store chunks that have changed, so the incremental data storage and transfer is only whatever has changed since the previous snapshot. Since the data is chunked, if you only alter one byte in a 10GB file you don\u2019t have to copy the whole file, just the chunk that\u2019s changed. Already a bunch of improvements over using <code>rsync<\/code>.<\/p>\n\n<p>I think Restic is a great backup tool, but it\u2019s not a <em>complete<\/em> backup tool. It handles taking your files and putting them in a backup. That backup can be on the local disk, somewhere over SFTP, or through a myriad of cloud storage systems via <a href=\"https:\/\/rclone.org\">rclone<\/a>. Once you\u2019ve got backups, Restic will let you inspect them, pull out single files, or restore the whole backup into the local filesystem. You can even <a href=\"https:\/\/restic.readthedocs.io\/en\/latest\/050_restore.html#restoring-using-mount\">make a FUSE mount of a snapshot<\/a>. Restic also supports managing the snapshots; removing old ones, downsampling the number that you retain as they get older. The options for removing snapshots make it easy to <a href=\"https:\/\/restic.readthedocs.io\/en\/latest\/060_forget.html#removing-snapshots-according-to-a-policy\">declare a policy<\/a> of how many restore points you\u2019d like to keep.<\/p>\n\n<p>As a brief aside, the Restic docs are exceptional. Basically every question I had about how things fit together was answered and easy to find in their documentation. It\u2019s great stuff.<\/p>\n\n<p>A slightly more niche feature that Restic supports is the ability to copy snapshots between backup locations (\u201crepositories\u201d). So to have backups in a NAS and in a cloud provider, you don\u2019t have to run the backup process twice, you can backup to the NAS and then copy that backup to the cloud provider using <code>restic copy<\/code>.<\/p>\n\n<h1 id=\"scheduling\">Scheduling<\/h1>\n\n<p>The feature that Restic doesn\u2019t have is scheduling. They\u2019ve drawn a very clear line that they\u2019ll support all the other stuff, but you need to tell them when to do it.<\/p>\n\n<p>Scheduling on servers is easy. I dump a script in <code>cron<\/code> and because the server is on all the time, the script runs exactly on schedule. A laptop is more difficult. Take a moment to think about all the annoying things you\u2019ll have to worry about with a laptop. It\u2019s a long list.<\/p>\n\n<p>The main one is that my personal laptop isn\u2019t used for long uninterrupted periods on a regular basis. If I scheduled backups to run every hour, I could easily end up with no backups. If I\u2019m not using it on the hour, the backup just won\u2019t get run. I assumed that someone would have made a MacOS app that took this kind of sporadic usage into account. The best I could find was <a href=\"https:\/\/github.com\/sergeymakinen\/ResticScheduler\">Restic Scheduler<\/a> which shows the backup status in the menu bar, and runs backups on a schedule, but it still just runs a fixed schedule. If your laptop isn\u2019t on at the scheduled time, you get no backup.<\/p>\n\n<p>What I want is a rules-based system for when to run the backups. Every few minutes, check how long it\u2019s been since the last backup, and if it\u2019s more than a few hours, seize the day and make a backup. You could get more advanced by taking into account the network connectivity and battery level. You could even measure how long it takes to do a backup and alter the frequency based on how much it differs from the expected backup speed.<\/p>\n\n<p>Naturally, nothing really ticked all the boxes I was looking for so I wrote my own scheduler. It\u2019s called Rest Up, and you can find it <a href=\"https:\/\/codeberg.org\/willhbr\/rest-up\">on Codeberg<\/a>. It\u2019s designed to be run regularly\u2014by some periodic scheduler like <code>cron<\/code>, <code>launchd<\/code>, or a systemd timer\u2014and it keeps state on when the last backup was in order to only run a new backup after a configurable waiting period.<\/p>\n\n<p>Writing my own tool also meant I could add some status reporting that you wouldn\u2019t get if you just ran <code>restic<\/code> through <code>cron<\/code>. Rest Up can show the backup status in the shell, tmux status line, or via <a href=\"https:\/\/swiftbar.app\">SwiftBar<\/a>. Since I\u2019m virtually always using tmux, I can see how long ago the last backup was, when the next one should start, and any errors.<\/p>\n\n<p>This way I get a little tick in my Mac\u2019s menu bar and in the tmux status line saying that my computer is backed up as expected. If there\u2019s a failure, I\u2019ll see it the next time I use my computer and can fix it immediately.<\/p>\n\n<h1 id=\"podman\">Podman<\/h1>\n\n<p>My \u201cproduction\u201d server (the one that <a href=\"\/2025\/03\/09\/a-slim-home-server-with-alpine-linux\/\">runs Alpine<\/a> with everything in containers) has all of its data in Podman volumes. There are a few different ways I could back these up. The \u201ceasiest\u201d would be including <code>~\/.local\/share\/containers<\/code> in the snapshot and capturing absolutely all my Podman state\u2014containers, images, volumes, etc. I don\u2019t want to back up gigabytes of images and temporary container state, I just want to back up volumes.<\/p>\n\n<p>You can export volumes as Tar files with <code>podman volume export<\/code>. Restic can <a href=\"https:\/\/restic.readthedocs.io\/en\/stable\/040_backup.html#reading-data-from-a-command\">backup data that\u2019s output by a command<\/a>, rather than just the filesystem. You could pair these two together and dump the archive directly into the backup.<\/p>\n\n<p>The other option, what I ended up doing, is to run Restic in a container and simply mount the volumes to that container. Restic just sees them as part of the filesystem, and they get backed up normally. This also has the advantage of keeping Restic in a container itself, so my containers-only computer can continue to just run containers.<\/p>\n\n<h1 id=\"replication\">Replication<\/h1>\n\n<p>Initially I only set out to back up my computers to my Synology. Having an offsite copy wasn\u2019t something I was too worried about, since a lot of my important data was already stored somewhere off site (like all my code being on Codeberg, etc).<\/p>\n\n<p>However, given that everything was in Restic, it wasn\u2019t too hard to start pushing snapshots between different locations with <code>restic copy<\/code>. I started by setting up Restic repositories in Google Drive with Rclone (since I have unused storage there) making sure to <a href=\"https:\/\/restic.readthedocs.io\/en\/latest\/045_working_with_repos.html#copying-snapshots-between-repositories\">copy the chunker params<\/a> from the repositories on the Synology.<\/p>\n\n<p>Setting up Rclone was fairly straightforward, I just <a href=\"https:\/\/rclone.org\/drive\/\">followed the documentation<\/a>, and chose the <code>drive.file<\/code> permission scope (Rclone can manage files it creates, but nothing else). I tried using the default Rclone client ID, but this effectively didn\u2019t work\u2014as the documentation warns\u2014so I got my own keys by creating a GCP project, <a href=\"https:\/\/rclone.org\/drive\/#making-your-own-client-id\">again following the documentation<\/a>.<\/p>\n\n<p>For a while I just had a shell script run via <code>cron<\/code> that would <code>restic copy<\/code> between the repos, which was <em>fine<\/em>. Perfectly serviceable. I do however crave complexity, so I have written a little server that does this for me, while also exporting Prometheus metrics about my backup state. You can <a href=\"https:\/\/codeberg.org\/willhbr\/restic-replicator\">find the code for that on Codeberg<\/a> as well.<\/p>\n\n<p>Since I\u2019ve got a server managing the replication, I can use that to handle pruning too. This means each client only has to do <code>restic backup<\/code>. I\u2019ll probably remove the pruning logic from Rest Up.<\/p>\n\n<h1 id=\"future\">Future<\/h1>\n\n<p>As much as I like building little tools, what I\u2019d really like is a combination of my replication server and the <a href=\"https:\/\/github.com\/restic\/rest-server\">Restic <em>Rest Server<\/em><\/a>. It provides an HTTP API that the Restic client can use, and it has an append-only mode that ensures that the client only adds new data, preventing it from deleting existing snapshots. This would let me backup from less-trusted computers (like a VPS) without giving SFTP access to my Synology. If I could then configure that server to prune itself periodically, and copy its data to an offsite repository, that would be fewer moving parts to manage.<\/p>\n\n<p>The <em>Rest Server<\/em> is slightly faster than using SFTP. I did some tests and found that SFTP would copy about 40GB per hour, whereas copying to Rest Server did about 52GB per hour\u2014both on my home wifi copying to a device on the same network. Both were copying the same 160GB contents of my home directory on my laptop.<\/p>\n\n<p>An extra 12GB per hour is not insignificant, but I still haven\u2019t used Restic to backup my full photo library. It\u2019s backing up my Pixelmator\/Photomator documents, but not the actual library. I\u2019m still in a bit of <a href=\"\/2025\/12\/26\/stuck-in-a-photo-management-factory\/\">a photo management rut<\/a>, so this isn\u2019t really a knock on Restic.<\/p>\n\n<p>I\u2019ve still got some work to do, Rest Up and the replicator server can be tweaked and improved. I need to automate or document my process for getting a new computer set up. Overall I\u2019m really glad I\u2019ve spent the time to set this up. I\u2019m already just a little bit more relaxed knowing that I can just leave a file on my computer and know that it\u2019ll soon be absorbed safely into the backup vortex. If you don\u2019t have good backups, don\u2019t wait until next March, just setup Restic now.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/07\/19\/backups-with-restic\/\">Permalink<\/a>\n&bull; July 19, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Backups%20With%20Restic\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/07\/19\/backups-with-restic\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-07-19T00:00:00+10:00","date_modified":"2026-07-19T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/07\/12\/all-buttons-could-be-action-buttons\/","title":"All Buttons Could Be Action Buttons","content_html":"<p>My iPhone 15 Pro has four physical buttons. The two volume buttons, the sleep\/wake button, and the Action Button, that replaced the silence switch in the iPhone 15 generation above the volume buttons. Since I never took my phone out of silent mode, I was a big fan of the swap to the action button, which <a href=\"\/2024\/12\/02\/appreciating-the-fine-art-of-phone-photography\/\">I have used as a camera shortcut<\/a> since getting the phone.<\/p>\n\n<p>The iPhone 15 Pro was the only phone to have the action button and <em>not<\/em> have <a href=\"https:\/\/support.apple.com\/en-au\/guide\/iphone\/iph0c397b154\/ios\">the \u201ccamera control\u201d<\/a> button and touch-sensitive thing. On subsequent iPhones, the action button is the quick utility button, and the camera control is the camera launcher, which makes sense. It would be weird to have those around the other way.<\/p>\n\n<p>However, since I\u2019m still living the mono-button lifestyle\u2014at least the mono-customisable-button lifestyle\u2014I yearn for more options. I tooted on Mastodon the other day that I realised I could set the action button to a shortcut that checked if the device was locked, and multiplexed between opening the camera or creating a quick note<sup id=\"fnref:quick-note\"><a href=\"#fn:quick-note\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup>. The camera shortcut is most useful to press while I\u2019m fishing my phone out of my pocket, so that it can be ready to capture a photo by the time I\u2019ve got it pointed in the right direction. Creating a note quickly is most useful when I\u2019m looking at something on my phone. So splitting the two actions based on whether the phone is locked is convenient.<\/p>\n\n<p>Sadly Shortcuts on iOS is still not trustworthy. I <a href=\"\/2022\/04\/22\/shortcuts-is-a-cursed-minefield\/\">wrote four years ago<\/a> about how I struggled to get a simple image resize to work. The width and height of an image would be reported as zero if the variable was read as \u201cphoto media\u201d instead of \u201cimage\u201d. Reading the properties as \u201cphoto media\u201d would work, but only after swapping to \u201cimage\u201d and back again.<\/p>\n\n<p>It\u2019s this kind of inconsist behaviour that has mostly stopped me from using Shortcuts (despite having <a href=\"\/2018\/12\/26\/compiling-for-shortcuts\/\">used it quite substantially in the past<\/a>). I thought that a single conditional statement with two actions would work reliably. Sadly a lot of the time I\u2019d press the action button, the shortcut would run, and I would get a camera, a note, or even an error message. I\u2019ve gone back to using the built-in \u201claunch camera\u201d action for the button, and creating notes from the share sheet.<\/p>\n\n<p>This got me thinking about how many physical buttons I\u2019ve got on my phone, and how many customisable actions I could have access to. So let\u2019s go through it.<\/p>\n\n<p>A short press on the sleep\/wake button either sleeps or wakes the phone. Probably not a good idea to change that one.<\/p>\n\n<p>Two short presses opens wallet\/Apple Pay. This is frequently used enough for me that I appreciate it being easily accessible.<\/p>\n\n<p>A long press activates Siri. I don\u2019t really use voice assistants much as I\u2019m embarrassed by talking to a computer, so this could be replaced with something more useful. Maybe taking a screenshot, or to create a note.<\/p>\n\n<p>The shortcut for screenshots is sleep\/wake and volume up, but there\u2019s no pairing for volume down, or the action button. These shortcuts are a little fiddly, which is why I\u2019d rather take screenshots by long-pressing the sleep\/wake button.<\/p>\n\n<p>Pressing the volume buttons change the volume, long press changes the volumes more, and double-click changes it twice. There\u2019s not a lot of ground for customisation here, and that\u2019s probably sensible.<\/p>\n\n<p>Next is the action button. It\u2019s the only one that has significant customisation, but only for its single medium-length press. At the very least it would be nice to have a secondary action for double-press (with the same cadence you use for opening wallet from the sleep\/wake button). This would solve my desire to have two different actions with only one button to use.<\/p>\n\n<p>The action button only triggers after a fairly intentional press. Not quite a long press, but definitely not a singular click. That\u2019s understandable to avoid accidental presses, but you could have a third action (perhaps that only works when the screen is on) that activates on a quick press. I can see that this would be confusing, so I understand why you wouldn\u2019t do it, but that doesn\u2019t stop me from wanting it for myself.<\/p>\n\n<p>There\u2019s also triple-click on the sleep\/wake button to activate the accessibility menu, and whatever the incantation is to get your phone to lock down to require a password instead of Face ID.<\/p>\n\n<p>Fairly conservatively, I think it would be great if the wallet (sleep\/wake double-click) and Siri (sleep\/wake long press) shortcuts could be customised, and a second double-click action added to the action button. For me that would give two additional free actions to play around with.<\/p>\n\n<p>It would also be great to have a native action selector, so I could double-click the action button and get something like a touch version of a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Pie_menu\">pie menu<\/a> showing my selected actions. Imagine if I could customise what actions were shown based on context. I usually make notes from web pages, so maybe that should only be shown there. Maybe if I\u2019m in a messaging app, I could get actions to share a recent photo or something. The opportunities could be endless.<\/p>\n\n<p>Ultimately this will mostly be moot by the end of this year, as I plan on getting a new phone\u2014on my three-year schedule. I\u2019ll likely have a camera control button which will free up the action button for whatever nonsense I feel like. However, adding a whole new button to free up capabilities that could be unlocked entirely in software with the existing hardware feels wasteful.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:quick-note\">\n      <p>\u201cQuick Note\u201d is an iOS feature where you get a somewhat context-aware compose window for a note, with options to add links to the current web page, etc.\u00a0<a href=\"#fnref:quick-note\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/07\/12\/all-buttons-could-be-action-buttons\/\">Permalink<\/a>\n&bull; July 12, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20All%20Buttons%20Could%20Be%20Action%20Buttons\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/07\/12\/all-buttons-could-be-action-buttons\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-07-12T00:00:00+10:00","date_modified":"2026-07-12T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/06\/09\/language-models-for-programming\/","title":"Language Models for Programming","content_html":"<p>The other day I wrote about the <a href=\"\/2026\/06\/03\/from-vim-to-helix\/\">new tools that developers are using<\/a> to get work done. Another topic I see discussed is different language models as part of the development process. I like to use and think about different programming languages. So I thought it would be interesting to go through some of the neat features in different languages that I\u2019ve used, and how that changes your mental model of a program.<\/p>\n\n<h1 id=\"static-vs-dynamic-typing-and-compilation\">Static vs Dynamic Typing and Compilation<\/h1>\n\n<p>I started programming in Java and then learnt Ruby a few years later. I was completely blown away by how easy it was to write code in Ruby when you didn\u2019t have to spell out all the types.<\/p>\n\n<p>The thing worth remembering here is that you often think of dynamic typing as being intrinsically part of interpreted scripting languages (like Ruby, Python, or JavaScript) but that\u2019s just a convenient pairing. There\u2019s nothing stopping you having a compiled dynamically typed language, or an interpreted statically typed language.<\/p>\n\n<p>Elixir is a compiled, dynamically typed language (although they\u2019ve <a href=\"https:\/\/elixir-lang.org\/blog\/2026\/06\/03\/elixir-v1-20-0-released\/\">just moved to being gradually typed<\/a>), and <a href=\"https:\/\/codeberg.org\/NLnetLabs\/roto\">Roto<\/a> is a statically typed scripting language. Compilation is just a good time to check types, and if you\u2019re compiling code you can use the type information to generate more efficient instructions.<\/p>\n\n<h1 id=\"just-in-time-compilation\">Just-in-Time Compilation<\/h1>\n\n<p>It\u2019s easy to think of interpreted versus compiled as a simple binary, but like many things it\u2019s more of a continuous spectrum. Most of the mature scripting languages actually compile to bytecode before execution, instead of evaluating the code as they read it.<\/p>\n\n<p>Java is a compiled language that gets compiled even harder while you\u2019re running it. The JVM will run bytecode similarly to how a scripting language would, but then it\u2019ll recompile hot sections into more efficient code as it\u2019s going.<\/p>\n\n<h1 id=\"null-safety\">Null Safety<\/h1>\n\n<p>Since I started programming with Java and Ruby, it was quite a while before I came across null safety. For me it was just a fact of life that any value could be <code>null<\/code> or <code>nil<\/code> and you just had to accept that. I was blown away by the idea that the type system could track this, and integrate with the control flow of the program to ensure values were available in certain parts of the program:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>if let value = self.maybeMissingValue {\n  print(\"I've got a \\(value)\")\n} else {\n  print(\"I don't have any value\")\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This is definitely more common now, if you\u2019re doing mobile or web development you\u2019ll be using Kotlin,  Swift, or TypeScript, which all have null safety.<\/p>\n\n<h1 id=\"immutability\">Immutability<\/h1>\n\n<p>Similarly to null safety, I hadn\u2019t considered the fact that the language could stop you from being able to change values. In Java pretty much everything is mutable. You can define something as <code>final<\/code> but that doesn\u2019t stop you from calling a method that changes the internal state of the <code>final<\/code> object, it just stops you from reassigning it completely.<\/p>\n\n<p>Swift and Rust both have strict mutability controls. If you declare a variable as immutable, you can\u2019t reassign it or call any method on it that changes its internal state. This means that you need to annotate methods with whether they will change the state of the object, or if they\u2019re simply read-only.<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Person {\n  name: String,\n}\n\nimpl Person {\n  fn rename(&amp;mut self, new_name: String) {\n    self.name = new_name;\n  }\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>In this code, if I don\u2019t have mutable access to a <code>Person<\/code>, I can\u2019t call the <code>rename<\/code> method:<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>let me = Person { name: \"William\" };\n\/\/ compiler error since `me` is immutable\nme.rename(\"Will\");\n<\/code><\/pre><\/div><\/div>\n\n<h1 id=\"immutable-data-structures\">Immutable Data Structures<\/h1>\n\n<p>On a similar note, some languages make everything immutable. All the main data structures in Clojure are immutable, and instead of mutating them in-place, you make a copy with the alteration. This is made efficient by sharing the parts that haven\u2019t changed instead of blindly copying them, and it\u2019s safe to do that since you know no one will alter them.<\/p>\n\n<p>Immutable data is inherently thread-safe since if no thread can mutate it, you can\u2019t have data races.<\/p>\n\n<h1 id=\"process-orientation\">Process Orientation<\/h1>\n\n<p>Elixir (and Erlang) work similarly to Clojure in that the data structures can\u2019t be altered. Instead, any kind of mutability is handled through message-passing between lightweight processes. A \u201cmutation\u201d is actually a process moving from one part of its execution into another.<\/p>\n\n<p>The real benefit comes from the ability to swap out failing processes with new ones, knowing that there can\u2019t be interconnected data between processes since it\u2019s immutable.<\/p>\n\n<p>I really like this model of having multiple components of a program all working together in parallel, but it\u2019s hard to make the same fault-tolerance guarantees in another language without the same memory model.<\/p>\n\n<h1 id=\"named-arguments\">Named Arguments<\/h1>\n\n<p>This is less of a live-changing feature, but convenient nonetheless. Many languages offer method overloading, where you can have multiple methods with the same name but different types or counts of arguments. It\u2019s great when you\u2019ve got a single operation to do but multiple possible entry points.<\/p>\n\n<p>This is less convenient when you\u2019ve got overlapping types. This is often the case with drawing APIs, where there are lots of widths, heights, rotations, and coordinates. In that case it\u2019s really convenient to be able to provide the name of the argument at the call site, and have that checked by the compiler.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code># booo, unclear\ndraw_rect(12, 24, 50, 20)\n# amazing\ndraw_rect(x: 12, y: 24, width: 50, height: 20)\n<\/code><\/pre><\/div><\/div>\n\n<p>This is also really convenient for APIs that have a lot of possible parameters, but only some of them need to be set.<\/p>\n\n<p>Named arguments also means that the arguments can be listed in any order, since they\u2019re matched by name and not by position. Somehow Swift manages to get the worst of both worlds here, where all arguments are named by default, but they also must be supplied in the order they\u2019re listed in the function declaration.<\/p>\n\n<h1 id=\"union-types\">Union Types<\/h1>\n\n<p>This is another language feature that I didn\u2019t realise I was missing out on coming from Java. If I had something that could be one of two types, I just had two variables and made sure that I didn\u2019t set both at the same time. It\u2019s another case where you <em>can<\/em> just do it yourself and try not to make any mistakes, but why do that when the compiler can check your working.<\/p>\n\n<p>I use unions a lot in <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">pod<\/a> since a lot of the time I\u2019m tracking things that can be in one of a handful of states. Ensuring these states stay consistent is really useful.<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>enum FlagsDifference {\n  NoChange,\n  New(Vec&lt;String&gt;),\n  Updated(Diff),\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>Like many features I find this easy to overuse and run into a wall where you\u2019ve overfit on one model and have to refactor.<\/p>\n\n<h1 id=\"pattern-matching\">Pattern Matching<\/h1>\n\n<p>Pattern matching goes along with union types as you\u2019ll want to do different things based on the type, and pull out the associated information:<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>match flags_difference {\n  NoChange =&gt; println!(\"no change\"),\n  New(flags) =&gt; println!(\"new flags: {flags:?}\"),\n  Updated(updated) =&gt; println!(\"changed flags: {updated}\"),\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>Like with <a href=\"#null-safety\">null safety<\/a>, the compiler ensures that the data we have access to in each branch is the data appropriate for that branch. If you wanted to do a similar thing in Java you could use an enum and store the data as an <code>Object<\/code>, casting it to the type you know it to be. Or each case could be a separate subclass, which is much more verbose.<\/p>\n\n<h1 id=\"receiver-blocks\">Receiver Blocks<\/h1>\n\n<p>I\u2019m not sure what the best name for this is in general. Kotlin calls them \u201creceiver blocks\u201d so I\u2019ll stick with that, but you can extend the idea a little more broadly. What they do is modify the normal lookup path for resolving variable, method, or class names. Most languages have a fairly predictable algorithm to map an identifier to a particular variable, method, or type. If it\u2019s not predictable, then the programmer is at risk of getting confused. It usually moves outwards from the smallest, closest scope, working its way until there is a match. If there\u2019s no match, then that\u2019s an error.<\/p>\n\n<p>Receiver blocks just insert a new layer in that outwards search. Conceptually it\u2019s not that complicated, but it allows for some really neat tricks. The most common use case is creating declarative, type-safe builders:<\/p>\n\n<div class=\"language-kotlin highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>html {\n  body {\n    p(\"This is type-safe!\")\n  }\n}\n<\/code><\/pre><\/div><\/div>\n\n<p><code>html<\/code> and <code>body<\/code> and just function calls, but the blocks that are passed to them are evaluated in a different context from the call site. For example, the <code>html<\/code> function could create an <code>HTMLBuilder<\/code> object and call the block inside the context of that class. The class provides the <code>body<\/code> method which would in turn create a <code>BodyBuilder<\/code> object that provides <code>p<\/code>. These methods are only in scope in the place that they can be added to the HTML document, so you\u2019re using the Kotlin compiler to enforce HTML correctness.<\/p>\n\n<h1 id=\"extension-methods\">Extension Methods<\/h1>\n\n<p>In a similar vein to receiver blocks, Ruby allows you to define a method that will be called if a method couldn\u2019t be found. You can then take that method call and apply it to another object, or mutate it and retry, or a whole host of other things. This lets you do naughty things like this:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def method_missing(name, *args)\n  puts \"you tried to call #{name}!\"\n  self.send(name.to_s.reverse.to_sym, *args.reverse)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>That\u2019s all very good for dynamic languages, but you can get similar behaviour in static ones as well. Swift allows you to define methods on existing types:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>extension String {\n  func frobulated() -&gt; String {\n    \/\/ frobulation implementation left to the reader\n  }\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This is a really convenient way to make types you don\u2019t own fit better into your codebase. In Swift it also allows you to make those types conform to protocols that they otherwise wouldn\u2019t, which saves having to wrap the type in another class that you own. Interestingly, while Kotlin supports extensions, they can\u2019t implement interfaces as they\u2019re just syntactic sugar for static methods.<\/p>\n\n<h1 id=\"object-lifetimes\">Object Lifetimes<\/h1>\n\n<p>I won\u2019t go on about this too much as <a href=\"\/2024\/09\/05\/implicit-lifetimes-and-undroppable-types\/\">I\u2019ve already done that<\/a> too much. I\u2019m always baffled by the people who wish they had Rust without the borrow checker, because to me that\u2019s the whole point. Differentiating the place that has control over a particular piece of data and a place that\u2019s just temporarily using it is really powerful. Tracking the lifetime of objects makes reasoning about behaviour much simpler, as you don\u2019t have to guess whether something will be kept around for longer than you expect. This comes with the cost of having to tell the compiler about all this, which is a lot of extra work.<\/p>\n\n<h1 id=\"macros\">Macros<\/h1>\n\n<p>Compilers are just fancy code generation machines, so why not let people add their own code generation in there too? I\u2019m <a href=\"\/2026\/01\/31\/crystal-dependency-injection\/\">a big fan of macros<\/a> since they combine my love of programming language features with my hatred of boilerplate.<\/p>\n\n<p>There are different flavours of macros depending on what type of input they get. The weakest just get the literal text and have to process it themselves, others get the tokens but no structural information, and the most powerful get the actual syntax tree that represents how the program is understood by the compiler.<\/p>\n\n<p>The macro can then take the input and translate it into a different form that would be annoying or cumbersome to type manually. This means you can define your own semantics and have code that breaks the established rules of the language, which makes macros an easy tool to misuse.<\/p>\n\n<h1 id=\"but-why\">But Why?<\/h1>\n\n<p>Hopefully this wasn\u2019t just a walkthrough of a few languages that I\u2019m a fan of. I think it\u2019s useful to know about these sorts of things to keep your mind open to different ways of structuring programs and solving problems. It can even be useful to know about esoteric features so you know what you might need to emulate to get the same behaviour in a language that doesn\u2019t support them.<\/p>\n\n<p>The original inspiration for this post came from the idea of \u201cimitation language features\u201d: ways that you can hack around the lack of a certain feature in your language of choice. My classic example would be promises, which are a way to work around a lack of <code>async<\/code>\/<code>await<\/code> by using callbacks. Although <code>async<\/code>\/<code>await<\/code> is itself a hack around <a href=\"\/2026\/03\/02\/async-inject-and-effects\/\">a lack of effects in the type system<\/a>.<\/p>\n\n<p>I thought that might end up a bit negative, so I\u2019ve left it up to the reader to work out which languages are missing which features, and what effect that has on the code.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/06\/09\/language-models-for-programming\/\">Permalink<\/a>\n&bull; June 9, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Language%20Models%20for%20Programming\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/06\/09\/language-models-for-programming\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-06-09T00:00:00+10:00","date_modified":"2026-06-09T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/06\/03\/from-vim-to-helix\/","title":"From Vim to Helix","content_html":"<p>The last year seems to have been the biggest change in developer tools ever. If you\u2019re reading <em>the discourse<\/em> you can\u2019t go more than 5 minutes without seeing someone talking about their new development environment, new ways of editing code, and the huge productivity gains the tools they use are affording them.<\/p>\n\n<p>A recurring theme of these posts is that anyone who doesn\u2019t pick up the very latest tools will be outpaced by those that have adopted them.<\/p>\n\n<p>Up until this point my go-to editor has been whatever version of Vim was installed on my system. I\u2019d been doing this for about 9 years, and it was comfortable. For the last three months I\u2019ve been using <a href=\"https:\/\/helix-editor.com\/\">Helix<\/a>, and it\u2019s been working quite well.<\/p>\n\n<p>The quick overview of Helix is that it\u2019s a modern implementation of a modal editor. It is heavily inspired by Vim, but isn\u2019t aiming to be backwards compatible (unlike <a href=\"https:\/\/neovim.io\">Neovim<\/a>). It has LSP (language server protocol) support built-in (like Neovim) which makes it easy to get IDE-like features for a variety of languages (unlike Vim).<\/p>\n\n<p><img loading=\"lazy\" src=\"\/images\/2026\/helix.webp\" alt=\"screenshot of Helix in split view showing Rust code for Pod\" \/><\/p>\n\n<p class=\"caption\">Helix with <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">Pod<\/a> open in split view, showing an LSP hover action.<\/p>\n\n<h1 id=\"install-and-setup\">Install and Setup<\/h1>\n\n<p>You can probably install Helix from your favourite package manager, which is nice. Something I missed is that you need to download and install the language grammars to get syntax highlighting and stuff:<\/p>\n\n<div class=\"language-shell highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ hx --grammar fetch\n$ hx --grammar build\n<\/code><\/pre><\/div><\/div>\n\n<p>You may also need to copy the runtime files (extracted from the repo or <a href=\"https:\/\/docs.helix-editor.com\/install.html\">downloaded alongside the binary<\/a>) to <code>~\/.config\/helix\/runtime<\/code>. I\u2019m only mentioning this here since I got caught out by it.<\/p>\n\n<p>My configuration is fairly minimal, mostly just some convenience key bindings, but you can find it <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/branch\/main\/helix\/config.toml\">on Codeberg<\/a> if you want inspiration. I used an LLM to translate my favourite Vim theme, <a href=\"https:\/\/github.com\/wadackel\/vim-dogrun\">Dogrun<\/a><sup id=\"fnref:dogrun\"><a href=\"#fn:dogrun\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> into a <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/branch\/main\/helix\/themes\/dogrun.toml\">simple ANSI-only Helix version<\/a>. Is this an indicator that I\u2019m stuck in my ways? Probably.<\/p>\n\n<h1 id=\"keymap\">Keymap<\/h1>\n\n<p>Helix\u2019s keymap is different to Vim\u2019s, which is a right pain because I\u2019ve got years of Vim muscle memory. Thankfully it\u2019s heavily inspired by Vim, and so a lot of my instincts still work, or work with slight alterations.<\/p>\n\n<p>In Vim the action precedes the subject. To delete a word you first press <code>d<\/code> (the action), then <code>w<\/code> (the subject). If you want to delete a paragraph you press <code>d<\/code> and then <code>ip<\/code> (inner paragraph). Helix inverts this, so you first select what you want to operate on, and then do an operation. This has the advantage that you see what you\u2019re going to affect before you do anything. If the paragraph break isn\u2019t where you expected it to be, you don\u2019t just delete the wrong thing, you see that your selection is wrong before anything is changed.<\/p>\n\n<p>In Vim I would heavily use visual mode (with <code>v<\/code>) to work this way anyway, so this is honestly a welcome change.<\/p>\n\n<p>It did still take me a few days to get familiar with the keymap, and then a week or two before I broke the stickiest of habits. I didn\u2019t realise that I used <code>x<\/code> to delete single characters as often as I do, but that\u2019s how you select a whole line in Helix. I would also use <code>V<\/code> in Vim to begin a visual line selection, which doesn\u2019t have an equivalent in Helix as far as I can see.<\/p>\n\n<p>You could add custom key bindings for these things, but I wanted to learn to use Helix, rather than an unholy custom mix of Vim and Helix key bindings with no real logic to them.<\/p>\n\n<p>That being said, there are a few operations that I think are too verbose in Helix that I rebound. I found the default bindings for <code>goto_next_paragraph<\/code> and <code>goto_prev_paragraph<\/code> to be really fiddly: <code>]p<\/code> and <code>[p<\/code> rely on your pinky finger, and can\u2019t be easily pressed repeatedly to jump up or down by multiple paragraphs. I rebound these to <code>}<\/code> and <code>{<\/code>.<\/p>\n\n<p>I made a few other minor customisations (that you can find in <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/branch\/main\/helix\/config.toml\">my Helix config<\/a>):<\/p>\n\n<ul>\n  <li><code>H<\/code> and <code>L<\/code> to jump to the start and end of the line (instead of <code>gh<\/code> and <code>gl<\/code>)<\/li>\n  <li><code>D<\/code> to jump to the definition using LSP (instead of <code>gd<\/code>)<\/li>\n  <li><code>K<\/code> for hover (usually to show the type information and documentation) instead of <code>&lt;space&gt;k<\/code><\/li>\n  <li><code>C-n<\/code> and <code>C-p<\/code> for next and previous buffer (instead of <code>gn<\/code> and <code>gp<\/code>)<\/li>\n  <li><code>jk<\/code>, <code>jK<\/code>, <code>Jk<\/code>, and <code>JK<\/code> for exiting insert mode (instead of pressing <code>esc<\/code> like an animal)<\/li>\n<\/ul>\n\n<p>The problem is now that I\u2019m used to using Helix, but I still use Vim key bindings in Zsh. This means I\u2019ll go from editing a file to editing a shell command and start stumbling over the difference in bindings. I tried the Zsh integrations (<a href=\"https:\/\/docs.helix-editor.com\/master\/other-software.html\">listed in the Helix docs<\/a>) but they weren\u2019t reliable enough for my day-to-day use. I\u2019m now mostly used to the difference and making a few mistakes isn\u2019t the end of the world.<\/p>\n\n<h1 id=\"some-random-nice-stuff\">Some Random Nice Stuff<\/h1>\n\n<p>I really like <code>R<\/code> which pastes and replaces the current selection. Since in Vim (and Helix) deleted text goes in the paste register, the natural pattern here would be to paste before or after what you wanted to replace, then delete the original. The alternative is to delete it and then paste from a numbered register, but I find that much fiddlier. Pasting directly over some content is convenient.<\/p>\n\n<p>In Helix <code>*<\/code> doesn\u2019t search for the identifier under the cursor, it just moves the current selection into the search register. On the surface this seems more cumbersome, as you first have to select the word with <code>miw<\/code>, put it in the register with <code>*<\/code>, then jump to the next occurrence with <code>n<\/code>. However, it gives more flexibility, as you can much more easily search for something that\u2019s not a single identifier. For example, if I want to find usages of a particularly hairy generic type, I can just select the generic (with <code>vwwww<\/code> or something), then <code>*<\/code>, and finally <code>n<\/code> and I\u2019m searching. In Vim I would probably just not do this, or work around it by selecting the text in my terminal emulator<sup id=\"fnref:no-mouse-mode\"><a href=\"#fn:no-mouse-mode\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">2<\/a><\/sup> and pasting that into Vim\u2019s search mode.<\/p>\n\n<p>Helix has features built-in that you\u2019d otherwise need plugins for in Vim. Surrounding the selection with brackets or changing the types of brackets can be done with <code>ms(<\/code> or <code>mr(<\/code>. In Vim this would require <a href=\"https:\/\/github.com\/tpope\/vim-surround\"><code>vim-surround<\/code><\/a>.<\/p>\n\n<h1 id=\"multiple-cursors\">Multiple Cursors<\/h1>\n\n<p>Back in the day, using multiple cursors in TextMate used to be my text-manipulation party trick. I think I migrated a whole application from Rails 2 to Rails 3 just by putting cursors in the right places.<sup id=\"fnref:multi-cursors\"><a href=\"#fn:multi-cursors\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">3<\/a><\/sup><\/p>\n\n<p>In Vim this was basically replaced with macros. If I wanted to do some rote mutation across a bunch of lines or call sites, I would craft a macro that would do the mutation then search for the next occurrence, and that would do the trick.<\/p>\n\n<p>You can do the same thing with Helix, but you can also create multiple cursors and be applying the same edit in multiple places with immediate visual feedback. I haven\u2019t needed to use this that much, and I\u2019m still getting my head around the various ways that you can place your cursors, but so far it\u2019s been a nice change.<\/p>\n\n<p>The simplest thing you can do is press <code>C<\/code> to create a cursor on the line below in the same column. I\u2019d use this the same way I\u2019d use visual-block mode in Vim to add something to the start or end of a line. When you\u2019re done, you press <code>,<\/code> to merge all the cursors back into one.<\/p>\n\n<p>The other thing you can do is create cursors that match a search. I used this to make all of these fields optional:<\/p>\n\n<div class=\"language-rust highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>pub struct KeepConfig {\n  pub hourly: u32,\n  pub daily: u32,\n  pub weekly: u32,\n  pub monthly: u32,\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>I selected the struct definition (<code>mip<\/code> to select the paragraph, <code>vjjjjj<\/code> or <code>xxxxxx<\/code> to brute-force it, or <code>v}<\/code> using my next paragraph shortcut) and then pressed <code>s<\/code> (<code>select_regex<\/code>) and entered <code>:<\/code> to create a new cursor on each colon character. I could then use normal navigation to jump to the <code>u32<\/code>, <code>miw<\/code> to select that, <code>ms&lt;<\/code> to wrap it in angle brackets, then just <code>iOption<\/code> to prepend \u201cOption\u201d in front of them all.<\/p>\n\n<h1 id=\"plugins\">Plugins<\/h1>\n\n<p>Over the years I have accrued a fair collection of Vim plugins. They cover a variety of different functionalities:<\/p>\n\n<ul>\n  <li><code>ctrlp<\/code> to quickly open files<\/li>\n  <li><code>editorconfig-vim<\/code> to autoconfigure the editor options<\/li>\n  <li><code>supertab<\/code> to do word-based autocomplete<\/li>\n  <li><code>lightline.vim<\/code> to put some nicer info in the status line<\/li>\n  <li><code>lightline-bufferline<\/code> to do that with the open buffers<\/li>\n  <li><code>auto-pairs<\/code> to insert closing brackets<\/li>\n  <li><code>vim-interestingwords<\/code> to highlight words (that are interesting)<\/li>\n  <li><code>syntastic<\/code> for compiler errors and warnings<\/li>\n  <li><code>vim-tmux-navigator<\/code> to swap seamlessly between Vim and tmux splits<\/li>\n<\/ul>\n\n<p>I then also have syntax definitions for Swift, JJ, Elixir, Caddy, Crystal, Rust, and Kotlin. Overall this is 84,814 lines of Vim script. Admittedly a lot of that is Syntastic support for languages that I don\u2019t use.<\/p>\n\n<p>To Helix\u2019s credit, most of this is built-in functionality. I don\u2019t need a plugin to show the files that I have open along the top of the screen or search for files in the current directory. This does put a limit on what you can do with Helix though, and there are a few places where I wish I could smooth off some rough edges with a custom script.<\/p>\n\n<p>If I\u2019m working in <a href=\"https:\/\/research.google\/pubs\/why-google-stores-billions-of-lines-of-code-in-a-single-repository\/\">a large repository<\/a>, then opening a file picker that just shows every single available file isn\u2019t helpful. I\u2019d much rather have a custom picker that lets me select from just the files I\u2019ve edited in version control, or apply some other filtering.<\/p>\n\n<p>I don\u2019t think there\u2019s a way for me to replicate <a href=\"https:\/\/github.com\/christoomey\/vim-tmux-navigator\"><code>vim-tmux-navigator<\/code><\/a> with Helix. For now I\u2019ve just been living without, but I do end up using the wrong key combination to swap between tabs and I\u2019d rather just have it be consistent.<\/p>\n\n<p>There are also some interactions that I think would be useful, and would like to experiment with via a plugin. It would be useful to have a \u201cjump to next reference in file\u201d shortcut. You can show all references with <code>gr<\/code>, but I would like to restrict that down to just the references in the current file, and jump between them like search results. This would be really great if there\u2019s a somewhat-generically-named function, and you need to make changes to a specific implementation or overload. Searching for the method name will bring up the wrong methods, but with an LSP you can get the exact right methods.<\/p>\n\n<p>Another missing plugin is any VCS integration for <a href=\"https:\/\/www.jj-vcs.dev\/\">JJ<\/a>. It works with git-backed repos since it can just read from <code>.git<\/code>, but if you\u2019re using a <a href=\"https:\/\/www.jj-vcs.dev\/latest\/technical\/architecture\/#storage-independent-apis\">different JJ backend<\/a> then there\u2019s no support. I didn\u2019t have any support in Vim, and so this isn\u2019t something I really expect or rely on. This is an example of something where a plugin system could provide this integration without relying on the main project to build or maintain it.<\/p>\n\n<p>Ultimately, the current Helix feature set is enough for me. It does mean that if a new tool comes out, or if I want to adapt Helix in a particular way, I\u2019m limited in the ways that I can do it. Development on Vim could stall completely and I could still grab new plugins to add language definitions or even whole new features to Vim.<\/p>\n\n<p>Adding new languages into Vim is typically very easy, you search for \u201c$LANGUAGE vim plugin\u201d, find a reputable-looking repository, clone it, and shove it in the <code>runtimepath<\/code>. For me that just meant adding it to the list in <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/commit\/ab29b85e7eda9ef52fdc1e506b15171e2829e487\/install.rb\"><code>install.rb<\/code><\/a>.<\/p>\n\n<p><a href=\"https:\/\/ser1.net\/post\/adding-a-tree-sitter-to-helix\/\">It doesn\u2019t seem too difficult<\/a> to add a new grammar to Helix, but through laziness I haven\u2019t bothered trying yet. The only language I can think of that\u2019s missing is <a href=\"https:\/\/sass-lang.com\/\">Sass<\/a>.<\/p>\n\n<h1 id=\"lsp\">LSP<\/h1>\n\n<p>The LSP (Language Server Protocol) integration in Helix works so well it\u2019s boring. Unsurprisingly <code>rust-analyzer<\/code> works with no configuration or tinkering, and shows useful messages immediately. I <a href=\"\/2026\/03\/13\/language-servers-in-containers\/\">previously wrote<\/a> about some of the work needed to proxy the LSP connection to the inside of a container for <a href=\"https:\/\/github.com\/swiftlang\/sourcekit-lsp\">SourceKitLSP<\/a>.<\/p>\n\n<p>For languages with an LSP implementation, editing them with Helix is a breeze. For languages without an LSP (or an LSP that you don\u2019t have installed) the basic editor feels a bit worse than Vim. For example, in Vim I know that if I hit tab, <em>supertab<\/em> will give me an autocompletion simply based on the words in the document. In Helix, if I don\u2019t have an LSP active and there\u2019s nothing to complete, tab seems to jump the cursor down a block.<\/p>\n\n<h1 id=\"why-helix\">Why Helix?<\/h1>\n\n<p>There are a couple of other modern editors that could fill the same niche: <a href=\"https:\/\/zed.dev\">Zed<\/a>, <a href=\"https:\/\/neovim.io\/\">Neovim<\/a>, and <a href=\"https:\/\/kakoune.org\">Kakoune<\/a>. I didn\u2019t do any comparison before trying out Helix, a friend of mine was using it and that was enough of a signal for me to know it was worth investigating.<\/p>\n\n<p>Having used Vim for 9 years, I\u2019m pretty sold on modal editing, and I don\u2019t think I could go back to a non-modal editor for anything serious. I\u2019m lucky enough to have not had any wrist pains from typing, and I think modal editing helps here. Keeping your hands closer to a typing position instead of moving between typing and pressing keyboard shortcuts definitely makes my hands happier.<\/p>\n\n<p>If you\u2019re using Vim but want LSP features, I think Helix is a great move. I\u2019ve been pretty happy using it so far.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:dogrun\">\n      <p>My slightly modified version from 3 years ago.\u00a0<a href=\"#fnref:dogrun\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:no-mouse-mode\">\n      <p>I don\u2019t use mouse mode in any terminal programs, so no mouse actions get passed to them. This gives me the freedom to select text from anywhere in the terminal UI without changing its state.\u00a0<a href=\"#fnref:no-mouse-mode\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:multi-cursors\">\n      <p>Ok, maybe that\u2019s a slight exaggeration.\u00a0<a href=\"#fnref:multi-cursors\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/06\/03\/from-vim-to-helix\/\">Permalink<\/a>\n&bull; June 3, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20From%20Vim%20to%20Helix\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/06\/03\/from-vim-to-helix\/","image":"https:\/\/willhbr.net\/images\/2026\/helix.webp","date_published":"2026-06-03T00:00:00+10:00","date_modified":"2026-06-03T00:00:00+10:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/03\/13\/language-servers-in-containers\/","title":"Language Servers in Containers","content_html":"<p>The purpose of <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">my container-management tool <code>pod<\/code><\/a> is to make it easier to do development and deployment using containers, specifically with Podman. Read more about <a href=\"\/2023\/06\/08\/overcoming-a-fear-of-containerisation\/\">why I wrote it<\/a> and <a href=\"\/2023\/06\/08\/pod-the-container-manager\/\">what it does<\/a>.<\/p>\n\n<p>Recently I\u2019ve been trying out the <a href=\"https:\/\/helix-editor.com\">Helix editor<\/a> in place of Vim (more on that once I\u2019ve been using it some more). The standout feature of Helix for me is first-class <a href=\"https:\/\/microsoft.github.io\/language-server-protocol\/\">Language Server Protocol<\/a> (LSP) support. This isn\u2019t something I\u2019d set up in Vim. I have <a href=\"https:\/\/github.com\/vim-syntastic\/syntastic\">Syntastic<\/a> installed and it\u2019ll occasionally show me errors.<\/p>\n\n<p>I wanted to write Swift using <a href=\"https:\/\/github.com\/swiftlang\/sourcekit-lsp\">SourceKit LSP<\/a> in Helix, but sadly Swift only supports up to Ubuntu 24.04 and I\u2019m currently running 25.10. Trying to run the LSP on my newer version will fail as it <a href=\"https:\/\/forums.swift.org\/t\/ubuntu-25-10-and-libxml2\/83239\/4\">can\u2019t find <code>libxml2<\/code><\/a>. I could run a VM, run my whole editor in a container, or even downgrade my whole machine to the old Ubuntu version, but there\u2019s a better way.<\/p>\n\n<p>LSP works by the editor running a command (like <code>rust-analyzer<\/code>) which exposes a <a href=\"https:\/\/www.jsonrpc.org\/specification\">JSON RPC<\/a> connection using standard input and output to read and write requests and responses. This is great when the LSP command is installed directly on your system, especially because the default Helix config will point it to the right executable without you having to do anything.<\/p>\n\n<p>Since the LSP is just running an arbitrary command and looking at the input\/output streams, we can just change that command and run the LSP in a container ourselves. The editor doesn\u2019t have to know anything about containers. As long as both processes have access to the same files, they\u2019ll be happy.<\/p>\n\n<p>This was a little bit tricky to get working. If the SourceKit LSP gets input it\u2019s not expecting it will crash, and if Helix gets back a weird response it\u2019ll just do nothing. Thankfully you can debug this a little with the <code>:log-open<\/code> command in Helix, which will show standard error for the LSP command.<\/p>\n\n<p>Basically we can set the LSP to run something like this:<\/p>\n\n<div class=\"language-shell highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>$ podman run \\\n  --workdir=\/src \\\n  --interactive \\\n  --mount=type=bind,src=.,dst=\/src \\\n  '--entrypoint=[\"sourcekit-lsp\"]' \\\n  docker.io\/library\/swift:latest\n<\/code><\/pre><\/div><\/div>\n\n<p>The issue with this is that the editor and the LSP have to agree on the file paths.<sup id=\"fnref:remapping\"><a href=\"#fn:remapping\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> The editor will say \u201cI\u2019m opening <code>\/home\/will\/Projects\/some_file.swift<\/code>\u201d and then since the container has the code in <code>\/src<\/code> and has no idea what <code>\/home\/will\/Projects<\/code> is, it\u2019ll just fail to do anything. Eventually I got this working by setting the <code>--workdir<\/code> to match the current directory path, but that\u2019s finicky.<\/p>\n\n<p>In order to make this as easy as possible, I\u2019ve <a href=\"https:\/\/codeberg.org\/willhbr\/pod\/commit\/efabf9d4eaa9441327a2f8465a8112e5dd5e5c5e\">added a new <code>pod lsp<\/code> subcommand<\/a> that will manage running the server in a container. It looks at the configured bind mounts and rewrites the requests and responses so the host and container get the paths they\u2019re expecting.<\/p>\n\n<p>The LSP can be configured in the <code>pods.yaml<\/code> config file, either as a standard container:<\/p>\n\n<div class=\"language-yaml highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>defaults:\n  lsp: lsp-container\n\ncontainers:\n  lsp-container:\n    image: docker.io\/library\/swift:latest\n    bind_mounts:\n      .: \/src\n    entrypoint: [sourcekit-lsp]\n<\/code><\/pre><\/div><\/div>\n\n<p>This allows for multiple LSPs in the same project, which might be handy. However since this is a tool for me and I\u2019m usually using one language at a time, I added a shorthand LSP config. This will add bind mounts and set the entry point, similar to how development containers work.<\/p>\n\n<div class=\"language-yaml highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>lsp:\n  image: docker.io\/library\/swift:latest\n  command: [sourcekit-lsp]\n<\/code><\/pre><\/div><\/div>\n\n<p>This works for actions and jumping to definitions within your own code, but when you jump to the definition of a standard library type, SourceKit will write a temporary file for the editor to display. That file lives in <code>\/tmp\/sourcekit-lsp<\/code> inside the container, which the editor doesn\u2019t have access to. Of course you can add the appropriate <code>bind_mount<\/code> config, but instead I\u2019ve made a shorthand <code>expose_paths<\/code> field that will translate into temporary directories on the host that get bound to the paths in the container.<\/p>\n\n<div class=\"language-yaml highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>lsp:\n  image: docker.io\/library\/swift:latest\n  command: [sourcekit-lsp]\n  expose_paths:\n    - \/tmp\/sourcekit-lsp\n<\/code><\/pre><\/div><\/div>\n\n<p>Since the config for the LSP lives in <code>pods.yaml<\/code>, you just need one Helix config to point a certain language at Pod instead of a local command:<\/p>\n\n<div class=\"language-toml highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>[language-server.pod]\ncommand = \"pod\"\nargs = [\"lsp\"]\n\n[[language]]\nname = \"swift\"\nscope = \"source.swift\"\nfile-types = [\"swift\"]\nroots = [\"Package.swift\"]\nlanguage-servers = [\"pod\"]\n<\/code><\/pre><\/div><\/div>\n\n<p>I\u2019ve only just added this, so no doubt there will be changes to the config as I use it more and find the sharp edges. You can <a href=\"https:\/\/codeberg.org\/willhbr\/pod\/commit\/efabf9d4eaa9441327a2f8465a8112e5dd5e5c5e\">see the code for the feature<\/a> or <a href=\"https:\/\/codeberg.org\/willhbr\/pod\">read more about pod on Codeberg<\/a>.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:remapping\">\n      <p>Some editors support config to do this remapping themselves, but Helix does not.\u00a0<a href=\"#fnref:remapping\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/03\/13\/language-servers-in-containers\/\">Permalink<\/a>\n&bull; March 13, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Language%20Servers%20in%20Containers\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/03\/13\/language-servers-in-containers\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["tools","podman"],"date_published":"2026-03-13T00:00:00+11:00","date_modified":"2026-03-13T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/03\/02\/async-inject-and-effects\/","title":"Async Programming Is Just @Inject Time","content_html":"<p>All I really wanted to do was learn a little bit more about different models for error handling, but then I kept seeing \u201ceffects\u201d and \u201ceffect systems\u201d mentioned, and after reading about <a href=\"https:\/\/koka-lang.github.io\/\">Koka<\/a> and <a href=\"https:\/\/effekt-lang.org\/\">Effekt<\/a> I think I\u2019ve been converted. I want effects now. So here\u2019s what I wished I could have read a few weeks ago.<\/p>\n\n<p>To start with, you need to remember that functions don\u2019t exist. They\u2019re made up. They\u2019re a social construct.<\/p>\n\n<p>Your CPU doesn\u2019t know or care what functions are,<sup id=\"fnref:have-not-asked\"><a href=\"#fn:have-not-asked\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> they\u2019re purely a book-keeping abstraction that makes it easier for you to reason about your code, and for the compiler to give you some useful feedback about your code. It\u2019s the whole idea with <a href=\"https:\/\/en.wikipedia.org\/wiki\/Structured_programming\">structured programming<\/a>: build some abstractions and have a compiler that can make guarantees about them.<\/p>\n\n<p>I\u2019ve never really done much assembly so this wasn\u2019t something I\u2019d had to contend with too much, but functions are interesting because they\u2019re a fixed entry point with a dynamic return point. Let me show you what I mean with this C program:<\/p>\n\n<div class=\"language-c highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>int first_function() {\n  \/\/ ...\n  return 10;\n}\n\nint some_function() {\n  \/\/ ...\n  int number = first_function();\n  return 4 + number;\n}\n\nvoid main() {\n  first_function();\n  some_function();\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>When this program is compiled, the compiler knows exactly where the instruction pointer needs to jump to get to <code>first_function<\/code> and <code>some_function<\/code>, since it knows exactly where in the executable it put them. Chances are that if you looked at the assembly they would each just be a single instruction to jump a nice fixed offset.<\/p>\n\n<p>What happens when we get to the <code>return<\/code> statements? <code>first_function<\/code> is called from both <code>some_function<\/code> and <code>main<\/code>\u2014there isn\u2019t just a single place that we can jump back to. The compiler doesn\u2019t know when it\u2019s generating the code for <code>first_function<\/code> who\u2019s going to be calling it.<\/p>\n\n<p>How this works is that alongside any function arguments, there\u2019s an invisible argument<sup id=\"fnref:architecture\"><a href=\"#fn:architecture\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">2<\/a><\/sup> passed that contains the position of the instruction where it made the jump to the top of the function. The compiler knows what the instruction address is\u2014it\u2019s the one that puts it there\u2014and so for each function call site, that\u2019s just a static piece of information that gets passed in. At the end of each function, the compiler just has to generate some code to read that argument (usually stored in a CPU register somewhere, but it doesn\u2019t have to be), jump back to that location, and continue execution.<\/p>\n\n<p>You don\u2019t think about this complexity because the abstraction is so solid and yet gives immense flexibility to write complicated programs.<\/p>\n\n<p>The resolution of which function to call can get more complicated by taking into account the number of arguments and their types, instead of just the name of the function.<\/p>\n\n<p>That\u2019s the simplest case\u2014static dispatch that is known at compile time\u2014but higher-level languages introduce dynamic dispatch, where a function call could end up jumping to one of many different locations. A great example of this is Java:<\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class MyClass {\n  @Override\n  public String toString() {\n    return \"my class\";\n  }\n}\n\nObject someObject = new MyClass();\nsomeObject.toString();\n<\/code><\/pre><\/div><\/div>\n\n<p>The <code>toString<\/code> method that gets called depends on the type of the receiver object. This isn\u2019t determined at compile time, but instead a lookup that happens at runtime. The compiler effectively generates a <code>switch<\/code> statement that looks at the result of <code>getClass<\/code> and <em>then<\/em> calls the right method. It\u2019s smarter than that for performance I\u2019m sure, but conceptually that\u2019s what it\u2019s doing.<\/p>\n\n<p>This abstraction continues to work really well because if you\u2019ve developed in Java (or any of the many many languages that share this behaviour) you quickly internalise the behaviour of the method resolution algorithm, and it\u2019s almost never surprising which bit of code ends up being executed. The compiler might need a runtime lookup to check, but you can use your big human brain and work it out with deduction while you write the code.<\/p>\n\n<p>So in Java (and basically every other object-oriented language) we have dynamic function dispatch as well as a dynamic return jump at the end of each function. We can pass an object to a function, and call a method on that object. Since the receiving function doesn\u2019t know the type of the object at compile time, any method calls on it will be completely dynamic:<sup id=\"fnref:or-c\"><a href=\"#fn:or-c\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">3<\/a><\/sup><\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>String someMethod(Object object) {\n  return \"This could be anything: \" + object.toString();\n}\n<\/code><\/pre><\/div><\/div>\n\n<p><code>someMethod<\/code> might be statically dispatched, but the call to <code>toString<\/code> will have to be dynamically resolved depending on the type of <code>object<\/code>.<\/p>\n\n<p>In <code>someMethod<\/code>, the call to <code>toString<\/code> will end up jumping to code that is entirely controlled by the object that is passed in as an argument. The CPU (or in this case, JVM) will lookup the location of <code>toString<\/code> on whatever type of object it is, and jump there.<\/p>\n\n<p>Just like with the function resolution algorithm, this complexity is manageable both because of the function call abstraction\u2014we know that control will jump into the other function and then return back to our function\u2014as well as type safety\u2014we know the returned type will be a <code>String<\/code>, so we don\u2019t need to worry about how we got it.<\/p>\n\n<p>This is something that I find interesting in Rust; since there\u2019s no runtime dynamic dispatch \u201cby default\u201d you have to be very explicit by wrapping your type in <code>Box&lt;dyn MyTrait&gt;<\/code>, or if you want your dynamism at compile time you can use <code>impl MyTrait<\/code>.<\/p>\n\n<p>Now if we\u2019re going to jump to an arbitrary bit of code, why not put that bit of code at the call site? That\u2019s what happens when we create an anonymous subclass:<\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>someMethod(new Object() {\n  @Override\n  public String toString() {\n    return \"heh a new string\";\n  }\n});\n<\/code><\/pre><\/div><\/div>\n\n<p>The actual location in the source file doesn\u2019t really matter\u2014the compiler will end up putting it wherever it feels like\u2014but from a syntax point of view, we\u2019ve now got control flow that jumps into <code>someMethod<\/code>, then back into our <code>toString<\/code> method, returns to <code>someMethod<\/code>, and then finally back to the call site.<\/p>\n\n<p>This is such a useful pattern that most languages have dedicated syntax for this: closures! I love closures so much that <a href=\"\/2024\/06\/28\/a-critique-of-closure-syntaxes\/\">I wrote a review of the various closure syntaxes<\/a>. Let\u2019s jump out of the JVM for now and appreciate this lovely Swift closure:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>[1, 2, 3].map { number in\n  number * 3\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>Instead of all that boilerplate to make a new object, we basically just write a block of code that will be used by the function we\u2019re calling. What\u2019s interesting here is that we\u2019re not in complete control when that block of code is running. It might appear like it, but we can\u2019t do anything except give a value back to the function.<\/p>\n\n<p>This creates the limitation where you can\u2019t create custom control flow that integrates with control flow that\u2019s built into the language. Closures can provide values and have side effects, but they\u2019ve got limited ability to stop the function that called them from running.<\/p>\n\n<p>Both Ruby and Crystal work around this limitation in interesting ways, but that\u2019s getting a little bit ahead of ourselves.<\/p>\n\n<p>We\u2019re going to forget about closures for a minute and talk about error handling. I promise it\u2019ll make sense.<\/p>\n\n<h1 id=\"error-handling\">Error Handling<\/h1>\n\n<p>The most basic form of error handling is what you get in Go; if something didn\u2019t work, you return a value that says so. By convention the caller checks that value and typically just returns it to say that whatever it was trying to do also didn\u2019t work.<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>func getConfigPath() (string, error) {\n  path, set := os.LookupEnv(\"CONFIG_PATH\")\n  if !set {\n    \/\/ The variable isn't set, report an error\n    return \"\", fmt.Errorf(\"CONFIG_PATH not set\")\n  }\n  return path, nil\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This is conceptually very simple, it\u2019s building slightly on the function abstraction by allowing multiple return values, but little else. If a function can fail, you can see from its function signature that it will return an error, like in <code>getConfigPath<\/code> above.<\/p>\n\n<p>With this model we have to write out the <code>return nil, err<\/code>  after each function call, but semantically we can think of control flow \u201cjumping\u201d to the point where we do something other than immediately return the error.<\/p>\n\n<div class=\"language-go highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>func getConfig() (*conf.Config, error) {\n  path, err := getConfigPath()\n  if err != nil {\n    return nil, err\n  }\n  f, err := os.Open(path)\n  if err != nil {\n    return nil, err\n  }\n  config, err := configFromFile(f)\n  if err != nil {\n    return nil, err\n  }\n  return config, nil\n}\n\nconfig, err := getConfig()\nif err != nil {\n  panic(err)\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>In this example, any error in loading the path, reading the file, or parsing the config will all direct control flow back to the top-level code and to the <code>panic<\/code> call.<\/p>\n\n<p>Skipping over macros that make it more succinct to return an error, the next iteration of this pattern is checked exceptions in Java. Any function that can fail is annotated with what is effectively a second return value. The thing that\u2019s different is that there\u2019s nothing at the call site needed to return this value, it will be implicitly passed back up through the call stack (each one dynamically resolved, remember) until we hit a <code>catch<\/code> block, which is just a bit of code that takes that return value and does something with it, not that different to the Go example above.<\/p>\n\n<p>If we ignore the fact that exceptions in Java are typed, all that\u2019s actually happening here is that every time we enter a <code>try<\/code> block, the compiler records in memory the location of the instruction corresponding to the start of the <code>catch<\/code> block. As we keep calling more functions, some of them might have <code>try<\/code> blocks of their own, and those are added onto a stack\u2014a shorter stack than the actual call stack, since not all functions have a <code>try\/catch<\/code>. When an exception is thrown, instead of looking up the location the function is supposed to return to, we consult the stack to find the topmost <code>catch<\/code> block, and jump straight there. We\u2019ve just done a <code>return<\/code> that has skipped over multiple functions all in one go.<\/p>\n\n<p>Of course the actual behaviour is much more complicated as it has to worry about <code>finally<\/code> blocks and types and all that, but the core idea is the same.<\/p>\n\n<p>Have you got all that? This is where things get weird.<\/p>\n\n<p>When an exception is thrown, what if the compiler grabbed the instruction pointer and stored it somewhere before jumping out to the <code>catch<\/code> block? Then if you wanted, inside the <code>catch<\/code> you could choose to jump back\u2014multiple layers of function calls\u2014into the code that failed as though nothing had happened.<\/p>\n\n<p>Let\u2019s say that we could grab the current instruction pointer location\u2014which the compiler will know for every line of code, since it\u2019s the one generating the instructions\u2014with a special variable called <code>__instruction__<\/code>.<\/p>\n\n<p>Something like this (if C had <code>catch<\/code> \u2026 or <code>throw<\/code>):<sup id=\"fnref:ignoring-stacks\"><a href=\"#fn:ignoring-stacks\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">4<\/a><\/sup><\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>int some_function() {\n  print(\"At the start...\")\n  throw __location__;\n  print(\"I'm back!\");\n}\n\ntry {\n  some_function();\n} catch(error_location) {\n  print(\"Caught an exception!\");\n  goto error_location;\n}\nprint(\"Finished.\");\n<\/code><\/pre><\/div><\/div>\n\n<p>In <code>some_function<\/code> we <code>throw<\/code> and jump out to the nearest <code>try<\/code> in our call stack, passing the current instruction back. In the code up the call stack we can run some code and then <code>goto<\/code> back to where the <code>throw<\/code> happened, resuming the function where we left off.<\/p>\n\n<p>The output would look like this:<\/p>\n\n<pre><code>At the start...\nCaught an exception!\nI'm back!\nFinished.\n<\/code><\/pre>\n\n<p>Well, that\u2019s effects. Almost.<\/p>\n\n<h1 id=\"coroutines\">Coroutines<\/h1>\n\n<p>There is another feature similar to effects that is called \u201ccoroutines\u201d. This is confusing because that\u2019s what people often call lightweight threads, which are often implemented with some version of coroutines, even if you can\u2019t use them in the language for other stuff. Coroutines allow you to stop the execution of a function and then resume it later, usually passing values back and forth in those steps.<\/p>\n\n<p>I first came across coroutines in the <a href=\"https:\/\/wren.io\">Wren<\/a> programming language. I got very confused by its <a href=\"https:\/\/wren.io\/concurrency.html\">concurrency<\/a> since by default it\u2019s not the \u201cthrow stuff at the wall and it\u2019ll run at kinda the same time\u201d model that Go and Crystal have.<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>var fiber = Fiber.new {\n  System.print(\"Before yield\")\n  Fiber.yield()\n  System.print(\"Resumed\")\n}\n\nSystem.print(\"Before call\")\nfiber.call()\nSystem.print(\"Calling again\")\nfiber.call()\nSystem.print(\"All done\")\n<\/code><\/pre><\/div><\/div>\n\n<p>That gives this output:<\/p>\n\n<pre><code>Before call\nBefore yield\nCalling again\nResumed\nAll done\n<\/code><\/pre>\n\n<p>Instead of the fibre running in the background (or \u201cbackground\u201d depending on your scheduler) it runs until it hits <code>Fiber.yield()<\/code> then it stops and waits for someone to call <code>.call()<\/code> again.<\/p>\n\n<p>This is really powerful for writing a lexer and parser that work together without having complicated code, or by storing an entire intermediate result in memory before passing it to the next stage. The lexer can trundle along and once it\u2019s got a full token it can <code>yield()<\/code> that value. The parser just continually runs <code>.call()<\/code> whenever it needs a new token to process. They\u2019re passing off control between each other in a more complicated way than just calling a single function and getting back a single result. The code in the lexer and parser can be more freely structured as any function can <code>yield()<\/code> or <code>call()<\/code> whenever a value is found or needed.<\/p>\n\n<p>Remember how I wrote <a href=\"\/2023\/10\/31\/how-i-learned-to-stop-worrying-and-love-concurrency\/\">thousands of words about concurrent programming<\/a>? Well the secret to any language that has <code>async<\/code>\/<code>await<\/code> is basically that they can do this \u201cjump to <code>catch<\/code> and then resume again later\u201d trick.<\/p>\n\n<p>Ignore the fact that <code>catch<\/code> usually means exceptions which usually means some kind of failure. A piece of code is running and it just started some work that\u2019s going to take a long time in the background, there\u2019s no point waiting and the program can do something more useful while the stuff happens in the background. It \u201cthrows\u201d an exception that is caught by a scheduler multiple layers of function calls up the stack. The scheduler saves the return address into a list of pending work to get back to, and then goes to find something that it can make progress on. Eventually it completes the other work and is signalled that our background task is complete. It pops the return address off the list and jumps to it, continuing the function call exactly where it left off as though nothing happened.<\/p>\n\n<p>If you take nothing else from this post, just know that <code>async<\/code>\/<code>await<\/code> is just weird exceptions that you can undo.<\/p>\n\n<p>Now the problem that plagues both <code>async<\/code>\/<code>await<\/code> and exceptions is that they\u2019re typically not integrated into the rest of the type system. In Java you can\u2019t have a type or function that is generic over whether it will throw an exception.<\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>String readFileOrFail(String path) throws IOException, FileNotFoundException {\n  File file = new File(path);\n  if (file.exists()) {\n    return FileUtils.read(path);\n  } else {\n    throw new FileNotFoundException(\"file doesn't exist\");\n  }\n}\n\nList.of(\"one.txt\", \"two.txt\", \"three.txt\")\n  .stream()\n  \/\/ doesn't work!\n  .map(name -&gt; readFileOrFail(name))\n  .collect();\n<\/code><\/pre><\/div><\/div>\n\n<p>The <code>map<\/code> method only accepts a lambda that doesn\u2019t throw any checked exceptions, so we can\u2019t directly call our <code>readFileOrFail<\/code> method. Ideally it would be able to generically say \u201cI throw the same exceptions as the lambda I receive\u201d but you can\u2019t do that in the Java type system.<\/p>\n\n<p>This isn\u2019t helped by the fact that Java has mostly given up on checked exceptions and instead opted for purely unchecked, runtime exceptions that offer no compile-time guarantees.<\/p>\n\n<p>Swift is a little better in that it has the <code>rethrows<\/code> keyword that can mark a closure and function as failing with the same exceptions as the closure.<\/p>\n\n<p>You get the same story with <code>async<\/code> functions. Swift has a <a href=\"https:\/\/developer.apple.com\/documentation\/swift\/asyncsequence\">whole separate library<\/a> for dealing with async operations on collections, because the methods on the existing collections can\u2019t be generic to support both synchronous and asynchronous versions. There\u2019s no such thing as <code>re-async<\/code>.<\/p>\n\n<p>So here we go: all any of these things\u2014closures, exceptions, suspending functions\u2014are just ways of jumping forwards and backwards to different places, and some compiler guarantees to ensure that any jumping can happen in a structured, safe way. And that\u2019s what effects give you, and some more.<\/p>\n\n<h1 id=\"effekt\">Effekt<\/h1>\n\n<p><a href=\"https:\/\/effekt-lang.org\/\">Effekt<\/a> is a research language with effect handlers and effect polymorphism (it says so on the website!). I also read the docs on <a href=\"https:\/\/koka-lang.github.io\/\">Koka<\/a> but ended up writing the most code in Effekt.<\/p>\n\n<p>From the <a href=\"https:\/\/effekt-lang.org\/tour\/effects\">language tour on Effekt effects<\/a>, an effect is written with an <code>interface<\/code>:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>interface Exception {\n  def throw(msg: String): Nothing\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>In this case we\u2019ll <code>throw<\/code> with a <code>String<\/code> and then the effect handler will give us <code>Nothing<\/code> back. In this case that\u2019s a somewhat magical <code>Nothing<\/code> type that tells the compiler the function will never return, but it could be a real value, which we\u2019ll see in later examples.<\/p>\n\n<p>Then we have a function that uses the effect:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def div(a: Double, b: Double) =\n  if (b == 0.0) { do throw(\"division by zero\") }\n  else { a \/ b }\n<\/code><\/pre><\/div><\/div>\n\n<p>What\u2019s interesting here is how that <code>throw<\/code> changes the function signature of <code>div<\/code>. In this example it\u2019s elided since it will just be inferred by the compiler. We could write it as <code>Double \/ { Exception }<\/code>, which says we\u2019re returning a <code>Double<\/code> and we\u2019ll use the <code>Exception<\/code> effect. This means we can only call it from somewhere with an <code>Exception<\/code> effect handler, like this:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>try {\n  div(4, 0)\n} with Exception {\n  def throw(msg) = {\n    println(\"oh no the div failed: \" ++ msg)\n  }\n}\nprintln(\"finished\")\n<\/code><\/pre><\/div><\/div>\n\n<p>The control flow will start at <code>try<\/code>, then jump to the <code>div<\/code> function, since the <code>b<\/code> argument is <code>0<\/code>, <code>div<\/code> will invoke the <code>throw<\/code> effect. The effect will jump control flow back down into the <code>def throw<\/code> block, and we\u2019ll print the error. Since we didn\u2019t call <code>resume()<\/code> the control flow will continue after the <code>try<\/code> block and run the last <code>println<\/code>.<\/p>\n\n<p>Effekt effects get their power with the <code>resume<\/code> keyword. This swaps them from acting like exceptions and makes them act like <code>async<\/code>\/<code>await<\/code>. Control flow jumps to the effect handler, which can then do some work and call <code>resume<\/code> to continue from the point that triggered the effect.<\/p>\n\n<p>Let\u2019s continue with the <code>Exception<\/code> example, but make it possible to recover from errors. The effect would be a little more complicated:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>interface Exception[T] {\n  def throw(msg: String): [T]\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>Now we can throw an exception with a message, and the exception handler can give us back a value to use instead.<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>val result = try {\n  div(4, 0)\n} with Exception {\n  def throw(msg): Double = {\n    println(\"oh no the div failed: \" ++ msg)\n    resume(42.0)\n  }\n}\nprintln(\"finished: \" ++ result)\n<\/code><\/pre><\/div><\/div>\n\n<p>The <code>div<\/code> function will be called, and it\u2019ll again <code>throw<\/code> back to our exception handler. This time we print the error but then <code>resume<\/code> with a value. In <code>div<\/code> this is used as the result of the <code>do throw<\/code> expression.<\/p>\n\n<p>In Koka this can get even more wild <a href=\"https:\/\/koka-lang.github.io\/koka\/doc\/book.html#sec-multi-resume\">where <code>resume<\/code> can be called more than once<\/a>. This forks off the original function so there are two instances, each progressing with different results. This is absolutely wild.<\/p>\n\n<p>The key here is that you don\u2019t have to call <code>resume<\/code> immediately. Just like how you can store a closure to compute some result later, you can wrap <code>resume<\/code> in a closure and wait to call it some other time. The state of the function that triggered the effect will be stored with the closure just like any other data. You can see this in action in the <a href=\"https:\/\/effekt-lang.org\/examples\/async.html\">Effekt async example<\/a>.<\/p>\n\n<h1 id=\"effects-versus-yield\">Effects versus <code>yield<\/code><\/h1>\n\n<p>That\u2019s only just scratching the surface of how you can use effects for control flow. Something I found interesting while reading this is realising that Crystal\u2019s <code>yield<\/code> keyword is just like a little baby effect system.<\/p>\n\n<p>Crystal inherits the somewhat complicated block semantics from Ruby. This is exposed with the <code>Proc<\/code> type and the <code>yield<\/code> keyword. The simple example from the <a href=\"https:\/\/crystal-lang.org\/reference\/1.19\/syntax_and_semantics\/blocks_and_procs.html\">documentation<\/a>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def twice(&amp;)\n  yield\n  yield\nend\n\ntwice do\n  puts \"Hello!\"\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The <code>yield<\/code> keyword yields (aahh!) control back to the calling function. In this example the block of code \u201cpassed\u201d to <code>twice<\/code> is run two times. This is not too dissimilar to passing a <code>Runnable<\/code> to a Java method:<\/p>\n\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>void twice(Runnable block) {\n  block.run();\n  block.run();\n}\n\ntwice(() -&gt; {\n  System.out.println(\"Hello!\")\n});\n<\/code><\/pre><\/div><\/div>\n\n<p>Except the <code>yield<\/code> in Crystal is more powerful, because the caller can change the control flow in the function that accepts the block. You can <code>break<\/code> from within a block and cause an early return, or <code>return<\/code> from within the block and return from the method the block is in\u2014not the method it\u2019s calling.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def find_mod_2(items)\n  items.each do |i|\n    if i % 2 == 0\n      return i\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>That <code>return<\/code> statement will stop the execution of <code>each<\/code> <em>and<\/em> return from <code>find_mod_2<\/code>. If this was another language, or if <code>each<\/code> was implemented with a <code>Proc<\/code> rather than a <code>yield<\/code>, you would have to return a special value to indicate you wanted to stop, or raise an exception. This is how Crystal gets away with having no <code>for<\/code> loop in the language.<sup id=\"fnref:not-macros\"><a href=\"#fn:not-macros\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">5<\/a><\/sup> Otherwise the block would simply cede control to the method that called it.<\/p>\n\n<p>What\u2019s confusing is that you use the same syntax to create a <code>Proc<\/code> which <em>can\u2019t<\/em> affect the control flow of the function that called it, and has the same limitations as other languages like Java. If you think about the implementation it makes sense, a <code>yield<\/code> cannot be stored and run later, outside of the execution of the method it is in, whereas a <code>Proc<\/code> can be stored as an instance variable and executed much later. Like, how would this work?<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class Thingie\n  getter block : Proc(Nil)? = nil\n\n  def do_thing(&amp;block : Proc(Nil))\n    puts \"setting thing\"\n    @block = block\n  end\nend\n\ndef use_thingie(th : Thingie)\n  th.do_thing do\n    return \"this is a value!\"\n  end\n  puts \"Am I unreachable?\"\nend\n\nth = Thingie.new\nuse_thingie\nth.block.call # what should happen here?\n<\/code><\/pre><\/div><\/div>\n\n<p>How can <code>use_thingie<\/code> ever finish if the <code>return<\/code> statement is in the <code>Proc<\/code>? What should happen when the <code>Proc<\/code> is called? It can\u2019t return from <code>use_thingie<\/code> since that function will have already finished by the time it\u2019s called.<\/p>\n\n<p>The Crystal compiler knows this doesn\u2019t work and the program will fail to compile:<\/p>\n\n<pre><code>In test.cr:12:5\n\n 12 | return \"this is a value!\"\n      ^\nError: can't return from captured block, use next\n<\/code><\/pre>\n\n<p>This is the exact same distinction as <a href=\"https:\/\/docs.swift.org\/swift-book\/documentation\/the-swift-programming-language\/closures\/#Escaping-Closures\">Swift\u2019s <code>@escaping<\/code> closures<\/a>, except Swift doesn\u2019t allow control flow in non-escaping closures anyway.<\/p>\n\n<p><code>yield<\/code> in Crystal is a very simple version of effects, since it will only allow jumping up one layer in the call stack, if you want to forward a block you need to re-<code>yield<\/code> when you call another function. There\u2019s also only one possible receiver, the single block passed to the function will be used for all <code>yield<\/code> statements.<\/p>\n\n<h1 id=\"dependency-injection-is-just-effects\">Dependency injection is just effects<\/h1>\n\n<p>You can only use an effect if somewhere up the call stack there is a place where that effect will be handled. In Java you need a <code>catch<\/code> around every <code>throw<\/code>, even if for runtime exceptions you can skirt around this slightly. In languages with <code>async<\/code>\/<code>await<\/code> you must decorate a call to an <code>async<\/code> function with <code>await<\/code>, and the function you\u2019re calling <em>from<\/em> must be <code>async<\/code>. Eventually up the call stack you\u2019ll get to a call that adds the async work to a task queue, executor, or blocks waiting for it to complete. These are all examples of effect handlers for async programming. They provide the scheduling effects that the async code needs in order to run.<\/p>\n\n<p>This can define lexical scopes; no code outside of places where a certain effect handler is installed may use that effect. My mind is broken in just the right way that when I realised this, I thought \u201cthat\u2019s just dependency injection\u201d.<\/p>\n\n<p>The key of (<a href=\"https:\/\/dagger.dev\">Dagger<\/a>-style) dependency injection is that you can only access certain dependencies in certain parts of the application, and how those dependencies are constructed is separated from their actual use. I like this so much I <a href=\"\/2026\/01\/31\/crystal-dependency-injection\/\">implemented it with Crystal macros<\/a>.<\/p>\n\n<p>Since effects propagate up, they naturally support nested scopes. When an effect is triggered for a dependency provided by a wider scope, it will skip over the handler for the inner scope and jump straight to the outer handler to get the dependency.<\/p>\n\n<p>This code is still fairly verbose, you would likely want some code generation or macros to tidy it up and make it less of a pain to write. We start with an injection effect:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>interface Inject[A] {\n  def get(): A\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>As long as we have the right type annotations, we can <code>do get()<\/code> to defer to the effect handler to provide us with a value:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def functionWithDeps(): Unit \/ { Inject[Logger], Inject[Config] } = {\n  val logger: Logger = do get()\n  val config: Config = do get()\n  logger.log(\"Doing stuff, this config: \" ++ show(config))\n  doImportantStuff(config)\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This function can only be called in contexts where we can inject both a <code>Logger<\/code> and a <code>Config<\/code>. This is what the function call at the scope root would look like:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def doWithInjection() = {\n  val config = buildConfig()\n  val logger = getLogger()\n  try {\n    functionWithDeps()\n  } with Inject[Config] {\n    def get() = resume(config)\n  } with Inject[Logger] {\n    def get() = resume(logger)\n  }\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This would obviously be unwieldy with lots of dependencies, but that could either be handled by clever type-system trickery, macros, or code generation. You\u2019d also want to create the objects lazily, which I\u2019ve neglected to do here.<\/p>\n\n<p>What\u2019s neat about this is that it works on functions rather than objects, so you\u2019re not forced to indirect things through lots of different classes if you don\u2019t want to.<\/p>\n\n<h1 id=\"effect-syntax\">Effect syntax<\/h1>\n\n<p>Since many languages already have an effects-adjacent way of throwing and catching exceptions, the syntax changes required to support arbitrary effects are actually fairly minimal. Effects could slot quite nicely into the Swift syntax, at least the parts that I can think of. Since you want to stay as close to the existing <code>throws<\/code> and <code>async<\/code> keywords, I\u2019d propose listing the effects between the argument list and the <code>-&gt;<\/code> before the return type, like this:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>\/\/ No effects\nfunc foo() -&gt; String {}\n\/\/ One effect\nfunc foo() async -&gt; String {}\n\/\/ Two effects, one with a type parameter\nfunc foo() throws&lt;Error&gt;, async -&gt; String {}\n<\/code><\/pre><\/div><\/div>\n\n<p>It doesn\u2019t fit with other types in Swift, but I think the names of effects should be lowercase to appear more like \u201ctags\u201d than \u201ctypes\u201d, although I could be persuaded for consistency to uppercase them. Since an effect might have any number of generic parameters, you\u2019d have to specify those within angle brackets which is a little ugly but not terrible.<\/p>\n\n<p>Defining the effect would be similar to an enum definition:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>effect async {\n  case suspend\n  case cancel\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>This fits well because you\u2019re yielding to a particular case in the effect, and you can add associated data to each <code>case<\/code> in just the same way you do for enums:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>effect throws&lt;T: Error&gt; {\n  case throw(T)\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>Just like Effekt, I think the <code>do<\/code> keyword is nice to indicate that you\u2019re doing something with an effect. I think this would be required on any function call that has an effect, like this:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>func fetchUserInfo(id: Int) async -&gt; User {\n  let info = do userInfoLoader.load(id)\n  return User(from: info)\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>At a point that we want to handle the effects, you would put a block that will match on the effects used in the <code>do<\/code> expression. Currently in Swift this is the <code>catch<\/code> keyword, but since this has to be more general I think <code>when<\/code> is a better fit. It would read as \u201cdo that, and when this happens, do this other thing\u201d.<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>do {\n  do userInfoLoader.load(id)\n} when throws(error) {\n  Log.error(\"Unable to load user \\(id): \\(error)\")\n  return nil\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>If you need to handle multiple effects, you\u2019d tack on extra <code>when<\/code> blocks just like you can with <code>catch<\/code> blocks today.<\/p>\n\n<p>The case with <code>throws<\/code> would be\u2014like Effekt\u2014a special case for an effect with a single type. For effect handlers with multiple cases, the body of the <code>when<\/code> block would be equivalent to a <code>switch<\/code> statement:<\/p>\n\n<div class=\"language-swift highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>do {\n  do asyncScheduler.doSomeWork()\n} when async {\n  case suspend: {\n    self.pendingTasks.append {\n      resume\n    }\n  }\n  case cancel: {\n    self.onTaskCancelled()\n  }\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>What I think is interesting about this exercise is that from a syntactic point of view, there isn\u2019t really that much to change. Functions can already be tagged with a fixed set of effects, and there\u2019s already syntactic structures to handle them.<\/p>\n\n<h1 id=\"do-you-want-effects\">Do you want effects?<\/h1>\n\n<p>I got into this mess because I was reading about ways of handling errors and also ways of handling async programming.<\/p>\n\n<p>Much like generics, I don\u2019t think most code would have to worry about defining their own effects or effects handlers. Having exceptions and <code>async<\/code>\/<code>await<\/code> not be something that\u2019s built into the language and instead be something that\u2019s built <em>with<\/em> the language would be really cool. The language could be less prescriptive over how async code is written, perhaps allowing certain codepaths to have strict guarantees on how fibres can be cancelled, for example.<\/p>\n\n<p>This might be the way to get structured concurrency into a language without placing the entire burden on the language itself. It would allow library authors to dictate the contexts in which certain functions could be called, enforcing structure and correctness. In most garbage-collected languages many contracts are only enforced in documentation saying \u201cdon\u2019t hold onto a reference to this object\u201d, which I\u2019ve also <a href=\"\/2024\/09\/05\/implicit-lifetimes-and-undroppable-types\/\">written about before<\/a>.<\/p>\n\n<p>Effects would also be valuable in code that deals with deadlines or other scoped data that is typically stored in dependency injection, thread local variables, or passed through function calls manually. Instead of constantly checking the deadline, you could just augment the existing suspension effect to fail at any suspension point when a deadline has run out. Any code that needs to operate with a deadline simply couldn\u2019t be called from contexts without a deadline.<\/p>\n\n<p>I\u2019ve focussed mostly on how effects relate back to exceptions and async code, since those are control-flow constructs that I (and probably you) are most familiar with. I haven\u2019t given much thought to what it would be like to write code where all I\/O is handled through effects. If you had to annotate every single function and function call that you wanted to do I\/O, I imagine that would get really tedious. If the language had good type inference on the required effects, then it might not be so bad.<\/p>\n\n<p>When I <a href=\"\/2023\/10\/31\/how-i-learned-to-stop-worrying-and-love-concurrency\/\">wrote all about concurrency<\/a> I argued that all code should be async by default\u2014like Go or Crystal\u2014since there\u2019s already so much implicit behaviour going on in your typical program, you might as well get low-cost I\/O while you\u2019re at it. I do think there are contexts where it\u2019s useful to know that you aren\u2019t going to suspend for an arbitrarily long amount of time, like a UI handler, and having the ability to write APIs that require no effects would allow these kinds of guarantees.<\/p>\n\n<p>So there you go, I started out wanting to understand error handling and instead learnt that everything I know about programming could somehow be linked back to one language feature. If you want to read more, I\u2019d recommend starting with the <a href=\"https:\/\/effekt-lang.org\/\">Effekt<\/a> and <a href=\"https:\/\/koka-lang.github.io\/\">Koka<\/a> language tours (I just skipped straight to the good bits).<\/p>\n\n<p>Please take my explanations of how function calls, and exceptions work here as illustrative rather than literal. I wanted to give an example of the <em>kind<\/em> of thing the computer is doing without getting too bogged down in how the computer actually does it. The aim of this is to think more about how control flow works with different languages, rather than how you\u2019d actually implement it.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:have-not-asked\">\n      <p>Ok I haven\u2019t asked mine.\u00a0<a href=\"#fnref:have-not-asked\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:architecture\">\n      <p>More or less, depending on architecture I guess? I\u2019m not a CPU instruction set expert, but this is the general concept.\u00a0<a href=\"#fnref:architecture\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:or-c\">\n      <p>The original version of this post incorrectly stated that C had no dynamic dispatch, but this is possible with function pointers, which can even be used to implement an object system.\u00a0<a href=\"#fnref:or-c\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:ignoring-stacks\">\n      <p>Ignoring stack frames and suchlike and the fact <code>goto<\/code> can\u2019t jump across functions.\u00a0<a href=\"#fnref:ignoring-stacks\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:not-macros\">\n      <p>Well apart from the macro language, which is kinda separate.\u00a0<a href=\"#fnref:not-macros\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/03\/02\/async-inject-and-effects\/\">Permalink<\/a>\n&bull; March 2, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Async%20Programming%20Is%20Just%20@Inject%20Time\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/03\/02\/async-inject-and-effects\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-03-02T00:00:00+11:00","date_modified":"2026-03-02T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/02\/08\/ruby-scripting-utilities\/","title":"Ruby Scripting Utilities","content_html":"<p>I think I\u2019m pretty good at shell scripting: I quote my variables, I know the difference between <code>$@<\/code> and <code>$*<\/code>, I know about checking that variables are set with the <code>?<\/code> suffix. I\u2019ve spent a lot of time messing around with shell scripts, but I always feel like the script that I write is almost always dictated by what\u2019s easy or possible to do in the shell.<\/p>\n\n<p>The main reason I did this was for a self-inflicted concern for portability. If I only wrote shell scripts, I could have everything working on any platform, without having to install additional dependencies or build custom executables.<\/p>\n\n<p>Last year I decided that I\u2019d had enough, and I gave myself permission to assume that any computer I was actually using would have Ruby installed. This led me to create an easy way to <a href=\"\/2025\/06\/08\/using-ruby-in-shell-pipelines\/\">use Ruby expressions as replacements for <code>sed<\/code> or <code>awk<\/code><\/a>. I then <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/commit\/3dd076de57bf1bb29b4ab3018c70365623cebac5\">replaced the script<\/a> that installs all my Zsh, tmux, and Vim plugins with a simple Ruby script.<\/p>\n\n<p>Ruby has been my go-to scripting language for ages, but now I\u2019ll skip straight past a shell script and go right to Ruby instead. I\u2019ve been using it for one-off scripts as well as small utilities.<\/p>\n\n<p>The biggest problem is that I constantly end up writing this function:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def run(*args)\n  unless system *args\n    raise \"command failed: #{args.join ' '}\"\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>If you\u2019re not fluent in Ruby, <code>system<\/code> runs a subprocess that inherits the IO of the Ruby process, and returns <code>true<\/code> or <code>false<\/code> depending on the exit status of the program. The way I almost always want it to work is to just stop the whole program if something goes wrong, so I always write out this little helper.<\/p>\n\n<p>The next issue is that I\u2019m really used to <a href=\"https:\/\/crystal-lang.org\/api\/latest\/Process.html\">Crystal\u2019s <code>Process<\/code> class<\/a> that makes it really easy to manage subprocesses. Paired with Crystal\u2019s event loop and <code>IO<\/code> module, it\u2019s easy to read and write data to the program, or just spawn it and wait for it to finish.<\/p>\n\n<p>You can do lots of stuff with Crystal\u2019s <code>Process<\/code>, but in a script all I really want to do is:<\/p>\n\n<ul>\n  <li>Run a program and throw an exception if it fails<\/li>\n  <li>Run a program and capture its output (also throwing an exception if it fails)<\/li>\n<\/ul>\n\n<p>My <code>run<\/code> method does the first. The second can almost be done with the special backtick <code>`<\/code> method:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>files = `ls`\n<\/code><\/pre><\/div><\/div>\n\n<p>This is great until you want to pass some arguments in, because it only supports string interpolation, not passing in separate arguments. That\u2019s <em>fine<\/em> for a one-off script where I know the input, but I\u2019d rather not worry unnecessarily about shell injection problems.<\/p>\n\n<p>Ruby does have an alternative: <code>Open3.capture2e<\/code>. It\u2019s not exactly the kind of fluent API I\u2019d like:<\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>require \"open3\"\n\noutput, status = Open3.capture2e('jj', 'commit', '-m', message)\nif status.exitstatus != 0\n  raise \"jj command failed\"\nend\n# =&gt; do something with output\n<\/code><\/pre><\/div><\/div>\n\n<p>So what I\u2019ve done is make use of the <code>RUBYLIB<\/code> environment variable. It points to an additional place (or places) that Ruby will look when you <code>require<\/code> a file. Instead of having to bundle common code in a gem, or rely on writing out an absolute path to exactly where my common code is, I can just:<sup id=\"fnref:process\"><a href=\"#fn:process\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup><\/p>\n\n<div class=\"language-ruby highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>require \"process\"\n\noutput = Process.capture 'jj', 'commit', '-m', message\n<\/code><\/pre><\/div><\/div>\n\n<p>I\u2019ve added the two methods for calling external programs that I\u2019ve been wanting, and then of course added a little helper library for interacting with JJ repos. You can see them in <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/commit\/c013021466f53d000a07608f93d931f8f0311381\">this commit<\/a> in <a href=\"https:\/\/codeberg.org\/willhbr\/dotfiles\/src\/branch\/main\/rubylib\">my dotfiles repo<\/a>. The intention here isn\u2019t to create something to be used by other people, it\u2019s purely so I can write scripts more easily.<\/p>\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:process\">\n      <p>It\u2019s probably not the best idea to call this <code>process<\/code>, and chucking this in the <code>RUBYLIB<\/code> path could definitely cause a weird problem at some point. I just didn\u2019t want to have a non-obvious name.\u00a0<a href=\"#fnref:process\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/02\/08\/ruby-scripting-utilities\/\">Permalink<\/a>\n&bull; February 8, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Ruby%20Scripting%20Utilities\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/02\/08\/ruby-scripting-utilities\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","date_published":"2026-02-08T00:00:00+11:00","date_modified":"2026-02-08T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/01\/31\/crystal-dependency-injection\/","title":"Building Dependency Injection with Crystal Macros","content_html":"<p>When I first came across dependency injection I was a sceptic. Surely we could just create objects the normal way instead of worrying about modules and bindings? Eventually though I realised how you\u2019re actually just generating the boilerplate code that you\u2019d need to pass the dependencies around manually, and writing that code yourself is a huge waste of time.<\/p>\n\n<p>I then wondered how hard it would be to implement the whole thing using Crystal macros. The aim is to have all the dependency resolution happen at compile time, so any failures to find a dependency will result in a compilation failure, and you\u2019re not paying the price of a hash lookup or something similar to find each dependency during construction.<\/p>\n\n<h1 id=\"dependency-model\">Dependency Model<\/h1>\n\n<p>The model I\u2019ve implemented is based on <a href=\"https:\/\/dagger.dev\">Dagger<\/a> (and its cousin, Hilt) since that\u2019s what I\u2019ve used the most. How Dagger works is that every injectable type is \u201cinstalled\u201d in a component, and can access any dependency from that component or its parent component. In a Hilt Android app, this means that a dependency in the <code>ActivityComponent<\/code> can inject something from the <code>SingletonComponent<\/code>, but not the other way around.<\/p>\n\n<p>Each injectable type also has a policy of whether a new object should be created each time, or whether Dagger should hold on to the object and share it between dependent classes. In Dagger these are \u201cscopes\u201d which everyone gets confused about because <code>ActivityScope<\/code> and <code>ActivityComponent<\/code> seem like they should be the same thing, but <code>ActivityScope<\/code> just says to keep the object for the life of the activity, and can only be used on dependencies in the <code>ActivityComponent<\/code>. The equivalent for <code>SingletonComponent<\/code> is just <code>Singleton<\/code>, which is confusing because it is a scope, but it\u2019s not named that way.<\/p>\n\n<p>I decided to not match the nomenclature and invent my own terminology. Each collection of dependencies is a <em>scope<\/em>, which may have a parent scope (and the parent scope may also have its own parent). Every injectable type must have either a <code>@[Retain]<\/code> or <code>@[Recreate]<\/code> annotation that denotes whether it should be held onto or not.<\/p>\n\n<p>What I like about this model is that you are effectively adding some lifetimes to objects in a language that doesn\u2019t actually support them.<\/p>\n\n<h1 id=\"implementation\">Implementation<\/h1>\n\n<p>The first trick that makes this whole thing work is defining the scopes as classes. They could be defined by annotations or just instances of a single <code>Scope<\/code> class, but as you\u2019ll see later this lets us trick the compiler into validating our dependency resolution at compile time for us. Doing that would be much harder if the scopes were defined another way.<\/p>\n\n<p>In a simple HTTP server, we might have scopes that look like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class GlobalScope &lt; Scope\nend\n\nclass RequestScope &lt; SubScope(GlobalScope)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p><code>GlobalScope<\/code> holds everything that is accessible anywhere in the application and lives until the process exits, then <code>RequestScope<\/code> holds things that are only relevant to a single incoming request and will be discarded once it has been handled.<\/p>\n\n<p>Don\u2019t worry about <code>SubScope<\/code>\u2014we\u2019ll get to that later.<\/p>\n\n<p>Now the main thing we need is to generate the code that builds our object and its dependencies. There are a few ways of defining the macro to do this\u2014you could define a macro on a module and call that from inside the class\u2014but what I ended up doing was creating a generic module with <a href=\"https:\/\/crystal-lang.org\/reference\/latest\/syntax_and_semantics\/macros\/hooks.html\">an <code>included<\/code> hook<\/a>. The actual code looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class RequestProcessor\n  include Injectable(RequestScope)\n\n  ...\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Using a generic module means that at compile time we have access to <code>T<\/code>\u2014the type of the scope\u2014and <code>@type<\/code>\u2014the class we\u2019re building the injector for. Other approaches could get the same thing, but it fits really nicely with the generic module.<\/p>\n\n<p>In the module we define a hook:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Injectable(T)\n  macro included\n    ...\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The macro hook is invoked immediately on <code>include<\/code>, but we can do the classic trick of defining a <code>finished<\/code> macro <em>inside<\/em> that macro that calls another macro. That way we can run code after the whole class has been defined.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>macro included\n  {% verbatim do %}\n    macro finished\n      build_injector\n    end\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>I\u2019ve written so many macros that I don\u2019t even hesitate at the idea of a macro defining a macro that calls a macro. That\u2019s just how I write code.<\/p>\n\n<p>That <code>build_injector<\/code> macro does the actual work to generate the code. This happens in a few stages; I didn\u2019t want to be overly prescriptive on which method would be called for injection, so you have to annotate it with <code>@[Inject]<\/code>, which means we first need to find the right method. This is a bit clumsy in a macro:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>{% method = nil %}\n{% for m in @type.methods %}\n  {% if m.annotation(Inject)\n       unless method.nil?\n         method.raise \"multiple @[Inject] methods: #{m.name} and #{method.name}\"\n       end\n       method = m\n     end %}\n{% end %}\n\n{% if method.nil?\n     @type.raise \"no @[Inject] annotated method on #{@type}\"\n   end %}\n<\/code><\/pre><\/div><\/div>\n\n<p>After that we have <code>method<\/code>, which is a <a href=\"https:\/\/crystal-lang.org\/api\/latest\/Crystal\/Macros\/Def.html\"><code>Def<\/code><\/a> object. Looking at the arguments to a particular method is easier than trying to process instance variables, and only doing constructor injection instead of field injection (in Dagger parlance) gives a bit more flexibility to the class.<\/p>\n\n<p>The next trick is to use the unsafe <code>.allocate<\/code> method to grab some uninitialised memory where we can put our object. We then just call the right <code>initialize<\/code> method (as defined by <code>method<\/code>) which will set the instance variables. That\u2019s just a matter of generating a method call from the information in <code>method<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>instance = {{ @type }}.allocate\n\ninstance.{{ method.name }}(\n  {% for arg in method.args %}\n    {{ arg.restriction }}.inject(scope),\n  {% end %}\n)\n<\/code><\/pre><\/div><\/div>\n\n<p>This can be a bit hard to parse, so let\u2019s look at an example. If we have this class:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class RequestProcessor\n  include Injectable(RequestScope)\n\n  @[Inject]\n  def initialize(\n    @params : URI::Params,\n    @context : HTTP::Context,\n  )\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Then the generated <code>inject<\/code> method would look like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def inject(scope)\n  instance = RequestProcessor.allocate\n\n  instance.initialize(\n    URI::Params.inject(scope),\n    HTTP::Context.inject(scope),\n  )\n  return instance\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Note that <code>@type<\/code> is expanded to <code>RequestProcessor<\/code> in the macro.<\/p>\n\n<p>Now, this doesn\u2019t actually work because we need to be able to retain objects in the scope, so that if they\u2019re injected in two places, both will get the same instance. What we\u2019ve got currently will just make a new instance of every object every time anything is injected, which isn\u2019t very useful.<\/p>\n\n<p>In this <code>inject<\/code> method the initial change is quite simple; instead of calling the <code>inject<\/code> method on each class to create an argument, read it from the scope\u2014that\u2019s why we have the scope in the first place. We\u2019ll assume that the scope has a <code>.get<\/code> method, and the change is fairly simple:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>instance = {{ @type }}.allocate\n\ninstance.{{ method.name }}(\n  {% for arg in method.args %}\n    scope.get({{ arg.restriction }}),\n  {% end %}\n)\n<\/code><\/pre><\/div><\/div>\n\n<p>The problem is that we now have to go and write that <code>.get<\/code> method. Working out how to do this took some serious head scratching. The problem is that we need to generate some code that will look at the type that\u2019s passed in, find out if it should be recreated or retained (and whether there\u2019s an existing retained instance), then return the retained instance or create a new one.<\/p>\n\n<p>Perhaps the most na\u00efve way of doing this would be to have a <code>Hash(Class, Object)<\/code> that stores the objects, but Crystal doesn\u2019t support using <code>Class<\/code> <em>or<\/em> <code>Object<\/code> as type constraints for instance variables, so that\u2019s not an option.<\/p>\n\n<p>I fiddled around with trying to do horrible unsafe things with <code>pointerof()<\/code> but that didn\u2019t really get anywhere because even if I can store pointers to objects, I still need to know if I even need to store them in the first place.<\/p>\n\n<p>I even thought about calling a specially-formatted method that would be handled by <a href=\"https:\/\/crystal-lang.org\/reference\/latest\/syntax_and_semantics\/macros\/hooks.html\"><code>method_missing<\/code><\/a>, parsed back into a type, and somehow worked it out from there.<\/p>\n\n<p>In the end the solution was much simpler; all it took was a realisation of how redefining classes and namespaces work.<\/p>\n\n<p>If you do this in Crystal, you will add a new method to the <code>String<\/code> class:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class String\n  def sup\n    \"Sup, #{self}\"\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>But if you do this, you will define an entirely new class called <code>Geode::String<\/code> that is unrelated to the top-level <code>String<\/code> class:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>module Geode\n  class String\n    def sup\n      \"Sup, #{self}\"\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>That works the same if <code>Geode<\/code> is a module, class, or struct.<\/p>\n\n<p>I thought that because my macro was generating code that lived inside the to-be-injected class, I couldn\u2019t patch new methods into other classes, so I couldn\u2019t define a new field on <code>RequestScope<\/code> from within that macro.<\/p>\n\n<p>In Crystal every type is resolved relative to the current module or class, so within <code>Geode<\/code> if you wrote <code>String<\/code> you\u2019d get your custom class, not the actual string class. If you want to be unambiguous, you can prefix the type with double colons to turn it into an absolute path (just like in C++). So in <code>Geode<\/code> you can use <code>::String<\/code> to refer to the actual string class.<\/p>\n\n<p>What I didn\u2019t realise is that you can do this same thing when you\u2019re patching a class. So from within one class, you can patch a class in an outer module just by passing an absolute path. Since we have the type of the scope in our generic module as <code>T<\/code>, we can patch the class like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class ::{{ T }}\n  {% if @type.annotation(::Retain) %}\n    @var_{{ @type.id }} : {{ @type }}? = nil\n\n    def get_{{ @type.id }} : {{ @type }}\n      @var_{{ @type.id }} ||= {{ @type }}.inject(self)\n    end\n  {% else %}\n    def get_{{ @type.id }}\n      {{ @type }}.inject(self)\n    end\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>This checks whether our type needs to be retained, then either generates an instance variable and getter method, or just a getter method.<\/p>\n\n<p>The getter method will be named something like <code>get_RequestProcessor<\/code>. I didn\u2019t include it in the example, but since we can have generic types or types nested in modules, we actually need to strip any special characters out of the type name, like this: <code>@type.stringify.gsub(\/[():]\/, \"_\").id<\/code>. Since Crystal macros don\u2019t have methods, every time we want to access the specially-named getter, we have to duplicate that snippet.<\/p>\n\n<p>Now we\u2019re able to store the object, and we\u2019ve got a method to access it, but we still don\u2019t have our <code>.get<\/code> method. This requires another few tricks that will interact with our specially-named method.<\/p>\n\n<p><a href=\"https:\/\/crystal-lang.org\/reference\/latest\/syntax_and_semantics\/macros\/macro_methods.html\">Macro methods<\/a> get instantiated separately for every type that calls them\u2014at least conceptually. We can capture that type in a generic parameter and then call <code>.get_{{ T.id }}<\/code> to either get the retained instance or a new object:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get(cls : T.class) : T forall T\n  {% begin %}\n    {% name = T.stringify.gsub(\/[():]\/, \"_\") %}\n\n    {% if @type.has_method? \"get_#{name.id}\" %}\n      self.get_{{ name.id }}\n    {% else %}\n      {% T.raise \"#{T} not registered in #{@type}\" %}\n    {% end %}\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>I\u2019m actually combining this with <code>has_method?<\/code> in order to fail with a more sensible error message. This is how the compiler is tricked into doing our dependency resolution at compile time: it needs to generate all the instantiations of this <code>.get<\/code> method, and if it can\u2019t call the right getter, then we\u2019ve got an object that can\u2019t be constructed through dependency injection.<\/p>\n\n<p>Although that\u2019s still only half the story. I promised earlier that I\u2019d get to <code>SubScope(T)<\/code>, and this is where that comes in. Since scopes are organised in a hierarchy, in order to have the compiler do type checking, that hierarchy needs to be represented in the type system. By making <code>SubScope(T)<\/code> a generic class, the child scope can have a concrete reference to its parent type, and the fallback <code>.get<\/code> method call is directly on the parent scope type, rather than being a dynamic dispatch on the <code>Scope<\/code> superclass.<\/p>\n\n<p>That\u2019s a lot to take in, so here\u2019s the code then we can go through an example.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get(cls : T.class) : T forall T\n  {% begin %}\n    {% name = T.stringify.gsub(\/[():]\/, \"_\") %}\n\n    {% if @type.has_method? \"get_#{name.id}\" %}\n      self.get_{{ name.id }}\n    {% else %}\n      @parent.get(cls)\n    {% end %}\n  {% end %}\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Let\u2019s say we have <code>RequestLogger<\/code> which is in <code>RequestScope<\/code>, and <code>Logger<\/code> which is in <code>GlobalScope<\/code>. <code>RequestLogger<\/code> injects the <code>Logger<\/code>. How does that dependency get resolved?<\/p>\n\n<p>The <code>Injectable(T)<\/code> module macro will generate the <code>inject<\/code> method, which will build the call to <code>initialize<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def inject(scope)\n  instance = RequestLogger.allocate\n\n  instance.initialize(\n    scope.get(Logger),\n  )\n  return instance\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>In this method, <code>scope<\/code> is a <code>RequestScope<\/code>. The Crystal compiler sees that we\u2019ve called <code>.get<\/code> with a parameter of type <code>Class(Logger)<\/code>, and it generates a new specialisation of that method for us, and runs our macro code in that method.<\/p>\n\n<p>The <code>@type.has_method?<\/code> check returns <code>false<\/code>, since <code>Logger<\/code> is registered in the <code>GlobalScope<\/code>, and so there\u2019s no <code>get_Logger<\/code> method patched into the <code>RequestScope<\/code>. The code generated for <code>.get<\/code> looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>def get(cls : Logger.class) : Logger\n  @parent.get(Logger)\nend\n<\/code><\/pre><\/div><\/div>\n\n<p><code>@parent<\/code> is defined in the initialiser for <code>SubScope(S)<\/code> as being of type <code>S<\/code>:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class SubScope(S) &lt; Scope\n  def initialize(@parent : S)\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Since <code>RequestScope<\/code> inherits from <code>SubScope(GlobalScope)<\/code>, the compiler knows that <code>@parent<\/code> <em>must<\/em> be a <code>GlobalScope<\/code>, and so it knows it needs to create a specialisation on that type to satisfy this <code>.get(Logger)<\/code> call.<\/p>\n\n<p>In this case, <code>GlobalScope<\/code> is a regular <code>Scope<\/code> and so the generated method is slightly different. It does the check for whether there\u2019s a <code>get_Logger<\/code> method defined\u2014in this case there is, so it will delegate to that. If there wasn\u2019t, then it will raise an exception and compilation will fail.<\/p>\n\n<p>If we put enough <code>@[AlwaysInline]<\/code> annotations on these methods, then the <code>get(Logger)<\/code> call in <code>RequestLogger<\/code> <em>should<\/em> be able to skip right to reading the field from whichever scope holds the logger, without doing any method dispatches. Talk about zero-cost abstraction.<\/p>\n\n<h1 id=\"provider-and-lazy\"><code>Provider<\/code> and <code>Lazy<\/code><\/h1>\n\n<p>Any good dependency injector will know you can\u2019t inject dependencies without deferring their construction in some cases. This lets you do something like:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class MyFeature\n  include Injectable(GlobalScope)\n\n  @database : Database\n\n  @[Inject]\n  def initialize(\n    config : Config,\n    old_database : Provider(OldDatabase, GlobalScope),\n    new_database : Provider(NewDatabase, GlobalScope)\n  )\n    if config.use_new_database?\n      @database = new_database.get\n    else\n      @database = old_database.get\n    end\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The implementation for these is fairly straightforward:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>struct Provider(T, S)\n  def self.inject(scope : S)\n    new(scope)\n  end\n\n  def initialize(@scope : S)\n  end\n\n  def get\n    @scope.get(T)\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>The biggest challenge here was that originally I didn\u2019t have them being generic over the scope, which meant the type of <code>@scope<\/code> was <code>Scope+<\/code> (any <code>Scope<\/code> subclass), and when the <code>get(T)<\/code> method was instantiated, it would be instantiated on the top-level class, which wouldn\u2019t have the special getter method defined, and the dependency resolution would fail. Making them generic on the scope adds a bit of complexity, but it\u2019s necessary to have the resolution work at compile time.<\/p>\n\n<p>Both of these classes have to be special-cased into the construction of the objects, which is a little messy. The actual call to the <code>initialize<\/code> method looks like this:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>instance.{{ method.name }}(\n  {% for arg in method.args %}\n    {% if arg.restriction.nil?\n         arg.raise \"needs restriction on #{arg}\"\n       end %}\n    {% if arg.restriction.resolve?.nil?\n         arg.raise \"Unable to resolve #{arg.restriction}\"\n       end %}\n\n    {% if arg.restriction.resolve? &lt; Provider %}\n      {{ arg.restriction }}.inject(scope),\n    {% elsif arg.restriction.resolve? &lt; Lazy %}\n      {{ arg.restriction }}.inject(scope),\n    {% else %}\n      scope.get({{ arg.restriction }}),\n    {% end %}\n  {% end %}\n)\n<\/code><\/pre><\/div><\/div>\n\n<p>This will always create a new <code>Provider<\/code> or <code>Lazy<\/code> instance (neither wrapper type should be retained) and then the actual object creation is done in <code>Provider#get<\/code> and <code>Lazy#get<\/code>, which call <code>@scope.get(T)<\/code>.<\/p>\n\n<h1 id=\"partialinjectable\"><code>PartialInjectable<\/code><\/h1>\n\n<p>The other classic dependency injection pattern is a class that has some fields injected, and some fields passed in explicitly. Usually this is done by generating a factory class, which is exactly what I did. It was quite satisfying to be able to generate code that would invoke the macro that I\u2019d just written to then generate more code, and have it all fit together.<\/p>\n\n<p>The macros are fairly similar to the rest, it just generates an inner struct named <code>Factory<\/code> and uses the <a href=\"https:\/\/crystal-lang.org\/api\/latest\/Crystal\/Macros\/Def.html#splat_index:NumberLiteral%7CNilLiteral-instance-method\"><code>splat_index<\/code><\/a> to differentiate between injected arguments and regular arguments. The injected arguments are each automatically wrapped in a <code>Provider<\/code>, so that the dependencies are only resolved when <code>new<\/code> is called on the factory.<\/p>\n\n<h1 id=\"qualifiers\">Qualifiers<\/h1>\n\n<p>If you want to inject two objects of the same type in Dagger <a href=\"https:\/\/dagger.dev\/semantics\/#keys\">you can use annotations<\/a> to differentiate them. I thought about using annotations in Crystal to do the same thing, but decided against it as it would be a bunch more work and complexity. Instead you can implement a single-field struct that wraps the type you want to duplicate\u2014I even made a convenient macro for it.<\/p>\n\n<h1 id=\"scope-parameters\">Scope Parameters<\/h1>\n\n<p>For subscopes that correspond to a particular action (like an HTTP request) you need to be able to put values into the dependency graph. In terms of code, this is as simple as defining the right method on the scope so that the <code>has_method?<\/code> check in the <code>get<\/code> macro method will find it.<\/p>\n\n<p>I made a macro that helps defining these, since writing them manually would be messy.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class RequestScope &lt; SubScope(GlobalScope)\n  params [\n    context : HTTP::Server::Context\n  ]\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Then when you make the scope, you pass in the parameters: <code>global.new_request_scope(context: context)<\/code>. These will then be available to inject to any class in that scope.<\/p>\n\n<h1 id=\"using-it\">Using it<\/h1>\n\n<p>Here\u2019s a somewhat contrived, overly simple example of where this might be useful. We\u2019ve got two scopes just like the rest of the post, a global config, and a processor that is only used for one request.<\/p>\n\n<p>Here are the scopes and config:<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>class AppConfig\n  getter do_stuff : Bool\nend\n\nclass GlobalScope &lt; Scope\n  params [\n    config : AppConfig\n  ]\nend\n\nclass RequestScope &lt; SubScope(GlobalScope)\n  params [\n    context : HTTP::Server::Context\n  ]\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Here\u2019s the actual interesting stuff. What\u2019s neat is that we don\u2019t have to plumb <code>Logger<\/code> or <code>AppConfig<\/code> into the <code>Handler<\/code>, and if we decide that <code>Logger<\/code> should be request-scoped in order to log with embedded request information, we can just move it into that scope and not have to do all the rewiring.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>@[Retain]\nclass RequestProcessor\n  @[Inject]\n  def initialize(\n    @context : HTTP::Server::Context,\n    @logger : Logger,\n    @config : AppConfig\n  )\n  end\n\n  def process\n    @logger.log { \"Processing request!\" }\n    ...\n    if @config.do_stuff\n      write_data(@context)\n    end\n  end\nend\n\n@[Retain]\nclass Handler\n  include HTTP::Handler\n\n  @[Inject]\n  def initialize(@global : GlobalScope)\n  end\n\n  def call(context)\n    req_scope = @global.new_request_scope(context: context)\n    processor = req_scope.get(RequestProcessor)\n    processor.process\n  end\nend\n<\/code><\/pre><\/div><\/div>\n\n<p>Now we just need to set up the application by loading the config, creating the root scope (and passing the config in), and starting our server. The server could also be constructed by dependency injection if we really wanted.<\/p>\n\n<div class=\"language-crystal highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>config = Config.load_from_file\n\nglobal_scope = GlobalScope.new(config: config)\nserver = HTTP::Server.new [global_scope.get(Handler)]\nserver.bind_tcp \"0\", 80\nserver.listen\n<\/code><\/pre><\/div><\/div>\n\n<h1 id=\"but-why\">But Why<\/h1>\n\n<p>Surprisingly I didn\u2019t do this <em>entirely<\/em> for my own amusement, I did actually have a use case that dependency injection would have made easier. I made some changes to <a href=\"https:\/\/codeberg.org\/willhbr\/ssh-honeypot\">my SSH honeypot<\/a> that I wrote years ago so that instead of just logging the commands, it would run them in a container. It would hash the username, password, and remote address to create a container name so that repeated connections would be run in the same container.<\/p>\n\n<p>I then wanted to change this so that I could optionally share containers based on some logic. I would usually do this by having a <code>ContainerDispatcher<\/code> or something that would be owned by the SSH server, and pass a reference to it to each <code>PodmanConnection<\/code> when a client was connected. The <code>PodmanConnection<\/code> would ask the dispatcher for a container, and since it would have visibility into all running containers, it could return an existing one or create a new one.<\/p>\n\n<p>This is a tiny microcosm of where dependency injection is useful. The connection should exist in its own scope, and request a dispatcher from <em>somewhere<\/em>. It doesn\u2019t care if that dispatcher is in the same scope or in the parent scope\u2014it just says \u201cgive me the thing that will let me get containers\u201d. The SSH server doesn\u2019t really need to know that the dispatcher should be shared among all connections, it doesn\u2019t even really need to <em>know<\/em> about dispatching between containers at all.<\/p>\n\n<p>I know dependency injection is a hallmark of over-architected enterprise software, but in cases like these I think it\u2019s a useful tool.<\/p>\n\n<p>You can see the <a href=\"https:\/\/codeberg.org\/willhbr\/geode\/src\/branch\/main\/src\/geode\/dependency_injector.cr\">full implementation<\/a> in <a href=\"https:\/\/codeberg.org\/willhbr\/geode\">Geode<\/a>. If I end up using this in my projects, no doubt I\u2019ll make some changes as I find pain points and other shortcomings.<\/p>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/01\/31\/crystal-dependency-injection\/\">Permalink<\/a>\n&bull; January 31, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Building%20Dependency%20Injection%20with%20Crystal%20Macros\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/01\/31\/crystal-dependency-injection\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["crystal","languages"],"date_published":"2026-01-31T00:00:00+11:00","date_modified":"2026-01-31T00:00:00+11:00","authors":[{"name":"Will Richardson"}]},{"id":"https:\/\/willhbr.net\/2026\/01\/15\/why-containers\/","title":"Why Containers?","content_html":"<p>There seems to be a recurring sentiment that pops up every now and again on Mastodon: \u201cthis project looks interesting, but the installation instructions say to use Docker, so I\u2019m not interested anymore\u201d. Now I totally understand the sentiment. If I came across a project and the instructions said to install it I\u2019d need <a href=\"https:\/\/nixos.org\">Nix<\/a>, I would also do a quick 180.<\/p>\n\n<p>However, I\u2019ve been using containers for development and for the services I run at home for a few years now, and I quite like it. So I thought it might be interesting to explain what I get out of containers, some of the bad bits, and right at the end some feelings about the mismatch between container enthusiasts and container skeptics.<\/p>\n\n<h1 id=\"use-podman\">Use <code>podman<\/code><\/h1>\n\n<p>I\u2019ll get this out of the way: I don\u2019t actually use Docker, I use Podman. Aside from being more permissively licensed, it\u2019s also much easier to install on basically any Linux system as it\u2019s available in most distros\u2019 package repository. On Ubuntu I can just <code>apt install podman<\/code> and on Alpine I can <code>apk add podman<\/code>. The <a href=\"https:\/\/docs.docker.com\/engine\/install\/ubuntu\/\">Docker installation instructions<\/a> are <em>much<\/em> more involved.<\/p>\n\n<p>This is the main reason I would recommend Podman, maybe second only to the fact that Podman runs rootless by default, which reduces the chances of a rogue container stomping over something on your machine that it shouldn\u2019t.<\/p>\n\n<h1 id=\"process-isolation\">Process isolation<\/h1>\n\n<p>By far the biggest benefit of using containers for me is low-effort process isolation. I don\u2019t like the fact that if I run something myself it\u2019ll have access to all the data on my system and be able to read and upload it, or simply just corrupt or delete it.<\/p>\n\n<p>You can of course get this same benefit by running services as different users, which most well-behaved services installed by system packages should be doing anyway.<\/p>\n\n<p>Running services as different users does make sharing data between services more difficult, and I\u2019m not very good at managing groups. Being able to just restrict the paths that the container has access to is really simple both to do and conceptually. I don\u2019t have to think about who is a member of which group and what access that grants them, I just say \u201cyou can access this folder\u201d and that works really well for me.<\/p>\n\n<p>The biggest benefit of container isolation is that when the container is gone, everything else goes with it. If the process was writing logs, config, temporary files, whatever, it\u2019s all constrained into the container. Once I\u2019ve done <code>podman rm<\/code> I know that everything belonging to that container has been purged.<\/p>\n\n<p>This makes trying new software a lot more like apps on a phone; you know that the risk of installing is very limited, and when you uninstall you know that everything gets removed. The exact opposite of installing software on Windows XP, where you\u2019d have to go through a wizard, it would require full admin access, and it could make any change to your machine it wanted.<\/p>\n\n<p>This isolation can also flip who is in control of the program. For example, some program might only support listening on a particular port or saving its data to a particular directory. This is of course bad software. Nevertheless I have the power to say \u201cno thanks\u201d and re-map the port and filesystem locations so from my perspective the program is working the way I want.<\/p>\n\n<h1 id=\"opaque-storage\">Opaque storage<\/h1>\n\n<p>Since I\u2019m in full control of what data in the container gets persisted, I have much more control about where it actually lives on my system, and thus how it gets backed up.<\/p>\n\n<p>All the containers that actually store data\u2014most important being <a href=\"https:\/\/www.freshrss.org\">FreshRSS<\/a>\u2014I map their data into a Podman <a href=\"https:\/\/docs.podman.io\/en\/v4.4\/volume.html\">volume<\/a>, which I can treat as an opaque blob. Currently I have a script that will take these volumes, export them to TAR files, and upload them to my NAS.<\/p>\n\n<p>I\u2019m definitely missing out on incremental backup here, as the TAR file requires a full upload each time. This is not perfect.<\/p>\n\n<h1 id=\"processes-versus-programs\">Processes versus programs<\/h1>\n\n<p>I like the fact that I can think of my programs more like programs instead of having to deal with OS processes. Perhaps I\u2019d get this same benefit if I was good with systemd, but I\u2019m not, so here we are. Instead of haphazardly calling <code>kill<\/code> with copy-pasted process IDs, I can just <code>podman stop<\/code> or <code>podman restart<\/code> with the container name\u2014and it\u2019s a name that I can choose myself.<\/p>\n\n<p>This grouping of processes also exposes better monitoring\u2014on Ubuntu, at least. I use <a href=\"https:\/\/github.com\/containers\/prometheus-podman-exporter\"><code>prometheus-podman-exporter<\/code><\/a> to grab metrics for each container, so I can see where I\u2019m spending my RAM. Annoyingly, due to <a href=\"https:\/\/github.com\/containers\/podman\/issues\/9502\">some cgroups issue on Alpine<\/a> you just get aggregated stats, not per-container stats. So I can\u2019t actually take advantage of this for containers on my Alpine servers.<\/p>\n\n<h1 id=\"remote-management\">Remote management<\/h1>\n\n<p>Something I like about Podman specifically is <a href=\"https:\/\/docs.podman.io\/en\/latest\/markdown\/podman-remote.1.html\">podman-remote<\/a>. I\u2019ve <a href=\"\/2023\/05\/05\/setting-up-podman-remote\/\">written about this before<\/a>, it\u2019s the secret behind <a href=\"\/2025\/03\/10\/endash-a-lightweight-container-dashboard\/\">my container dashboard<\/a>.<\/p>\n\n<p>Since I can interact with the containers on my local machine in just the same way as I do the ones on my other servers, it is really easy to write scripts that deal with both transparently. Endash merges containers running on my two home servers and a VPS into one interface, even with a mix of Ubuntu and Alpine between them.<\/p>\n\n<p>Even just for local containers, having an interface to get details about what\u2019s running in a computer-readable JSON format is really convenient. With Endash I can just list the currently running containers and get the ports that they\u2019re listening on to include as links in the dashboard. I can introspect the volumes they have access to, how long they\u2019ve been running, and more all from one API.<\/p>\n\n<h1 id=\"the-rule-of-two\">The rule of two<\/h1>\n\n<p>This is more geared towards development, but it is helpful for any kind of debugging. Since the process running in the container has no idea about what\u2019s happening in the real world, it\u2019s really quick and easy to run a second instance of some service.<\/p>\n\n<p>All I have to do is assign it a different port and mount a different directory\u2014or mount no directory to get a fully clean environment\u2014and then I can have both running in parallel.<\/p>\n\n<p>Paired with the fact that all the data can be isolated to a particular volume, I could duplicate the volume, run a new container pointing to the second copy of my data, and experiment with some alternative configuration or a major version upgrade. All with the peace of mind that if it doesn\u2019t work out, I haven\u2019t actually done anything to my actual service.<\/p>\n\n<h1 id=\"dependency-heaven\">Dependency Heaven<\/h1>\n\n<p>Dependency hell isn\u2019t particularly likely if you\u2019re installing the mainstream versions of packages from the package manager that comes with your distro. People have <a href=\"https:\/\/unnamed.website\/posts\/installing-every-arch-package\/\">managed to install a lot of packages at once<\/a>.<\/p>\n\n<p>I don\u2019t think I actually run enough services for this to be a serious issue, but in theory you could have services that require mutually incompatible versions of shared libraries, command-line tools, or suchlike. Being able to run these without messing with load paths or <code>$PATH<\/code> is convenient.<\/p>\n\n<p>The biggest advantage of this dependency isolation is development, where you can hack around with the system safe in the knowledge that you won\u2019t break something important.<\/p>\n\n<h1 id=\"development\">Development<\/h1>\n\n<p>I <a href=\"\/2023\/06\/08\/overcoming-a-fear-of-containerisation\/\">originally came to containerisation<\/a> as a way to control my development environment, rather than a way to run things on my home server. For development, using <code>podman<\/code> directly kinda stinks, the commands are exceptionally verbose and easy to get wrong. So much so that I <a href=\"\/2023\/06\/08\/pod-the-container-manager\/\">wrote my own program to make this easier<\/a>.<\/p>\n\n<p>Over two years later and I\u2019m still mostly working this way, but I did walk it back a little. I use <code>cargo<\/code> directly on the system and I gave up on using containers for one-off scripts as it was just too much friction. But containers have made it exceptionally easy for me to write a little server, package it up, and keep it running on my home server. I\u2019ve currently got 6 of my own containers running across 3 different servers. Running, deploying, and monitoring them is straightforward.<\/p>\n\n<p>The other development advantage is being able to hack around in a safe sandbox to try and get something working. I try not to install too much weird stuff onto my development machine, especially old tools that might conflict with a more recent version that I rely on. If I containerise this, I can do almost anything without affecting my actual machine.<\/p>\n\n<p>As a concrete example, I recently wanted to find out why <a href=\"https:\/\/jekyll.github.io\/jekyll-admin\/\">jekyll-admin<\/a> would show an error on basically every page load. To do this I needed to build the project, it\u2019s built with React which means installing <a href=\"https:\/\/nodejs.org\/en\">node.js<\/a> and <a href=\"https:\/\/yarnpkg.com\">Yarn<\/a>. Some part of this build process requires a Python interpreter, and the versions that jekyll-admin requires are old enough that it would only work with Python 2.<sup id=\"fnref:jekyll-end\"><a href=\"#fn:jekyll-end\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">1<\/a><\/sup> Now there\u2019s no way that I\u2019d pollute my computer with a Python 2 install, but in a container I can hack around with whatever I want, knowing that it can all just disappear once I\u2019m done.<\/p>\n\n<p>I did the same thing while trying to work out <a href=\"\/2025\/10\/13\/the-6-2nd-stage-of-swift-on-linux\/\">why I still couldn\u2019t use websockets in Swift<\/a>. Firstly Swift only supports a few Linux distros,<sup id=\"fnref:linux-swift-support\"><a href=\"#fn:linux-swift-support\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">2<\/a><\/sup> so being able to fake Ubuntu from within Alpine is a useful trick, but also the availability of the libcurl version depended on the underlying Ubuntu version, and I could just swap between two versions\u2014or even run both at the same time\u2014trivially.<\/p>\n\n<p>Running code in containers also forces you to understand what implicit dependencies you\u2019re pulling in, usually development headers for some library, the <code>build-essential<\/code> package, or maybe just <code>tzdata<\/code>. Usually these are things that you install and forget about, then when you go to help someone else it\u2019s really hard to remember what you need to do, or even to know what you need in the first place. Having a containerfile doesn\u2019t guarantee reproducibility\u2014it might reference an image that changes\u2014but at least there\u2019s some intention there that can be reverse-engineered.<\/p>\n\n<h1 id=\"the-bad-bits\">The bad bits<\/h1>\n\n<p>If you use containers, then you need to trust whichever registry you pull from just like you trust the system package manager. I don\u2019t know much on the relative security tradeoffs, but you\u2019re probably running a newer version if you pull from a registry, which might have unfound flaws. The package manager maintainers might be altering or re-building packages in a way that you find valuable, but they also might be doing something you disagree with.<\/p>\n\n<p>Trust is definitely something I have in the back of my mind. I don\u2019t have a particularly robust approach here, but if there isn\u2019t a prebuilt image that I feel comfortable with, I\u2019ll just build my own from a standard OS image (probably Alpine) and install the package using <code>apk<\/code> or <code>apt<\/code>. That way I\u2019m still getting a container, but using the package from the distro.<\/p>\n\n<p>The <code>podman<\/code> CLI is complicated. Somewhat necessarily so, given the amount of stuff it can do, but nonetheless it is really an interface best used by computers, not by people\u2014which I\u2019ll get to more at the end.<\/p>\n\n<p>Podman networking (or container networking in general) is terrible. I\u2019ve spent ages trying to understand what you can and cannot do, only to run into dead ends and <a href=\"\/2025\/11\/30\/alpine-containers-forget-tailnet\/\">hard-to-debug problems<\/a>. The key to a happy life is to set <code>ufw<\/code> to block all incoming connections outside of port 22, 80, and 443, have containers bind to particular known ports, and use <a href=\"https:\/\/caddyserver.com\">Caddy<\/a> as a proxy.<\/p>\n\n<p>The opacity you get from using volumes as storage can turn around and bite you when you want to quickly grab something from a volume. The experience is about as good as trying to <code>scp<\/code> something without knowing the exact path. The less I have to do this the better, and if I\u2019ll need to look at the files with any regularity I\u2019ll use <a href=\"https:\/\/docs.podman.io\/en\/v4.4\/markdown\/options\/mount.html\">a bind mount instead<\/a>.<\/p>\n\n<h1 id=\"im-definitely-over-invested\">I\u2019m definitely over-invested<\/h1>\n\n<p>You\u2019ve probably realised now that I\u2019m over-invested. I\u2019ve picked containers as the backbone of how I use computers and there\u2019s no going back now. I\u2019ve <a href=\"\/2023\/06\/08\/pod-the-container-manager\/\">written a tool for managing them<\/a> and then <a href=\"\/2025\/07\/25\/rewriting-pod-with-wisdom\/\">rewritten it in Rust<\/a> and <a href=\"\/2025\/03\/10\/endash-a-lightweight-container-dashboard\/\">written a custom web interface to view my containers<\/a>. Without this, I\u2019m lost.<\/p>\n\n<p>This has definitely given me an appreciation for what you can do with containers, moreso than if I\u2019d pasted in a few <code>podman run<\/code> commands to get something working. A large part of the reason why I wrote these tools was because I <em>didn\u2019t<\/em> understand containers, and the way I get an understanding is to get right down into the weeds. I wouldn\u2019t be as comfortable using containers as heavily as I do without having my own system around them.<\/p>\n\n<h1 id=\"putting-it-all-together\">Putting it all together<\/h1>\n\n<p>Just to make it super clear, I have a custom tool to build, run, deploy, and update containers, just because I didn\u2019t like any of the existing tools. In the shipping container analogy, I\u2019ve built my own boat, harbour, dock, and crane system. So if you find yourself thinking that a particular podman command is hard to remember or complicated, just know that I\u2019ve spent hours writing thousands of lines of code to manage that complexity.<\/p>\n\n<p>Physical shipping containers aren\u2019t very useful if you don\u2019t have a ship that\u2019s built to transport them. In fact it\u2019s more difficult to cram shipping containers onto a pre-containerisation vessel than it would be to just carry the cargo directly.<\/p>\n\n<p>That\u2019s the key really, I\u2019ve built a whole system with containers as the foundation, which has made it really easy for me to use containers. But podman doesn\u2019t come with a system, it\u2019s just a box you can put stuff in, and that\u2019s only half the answer.<\/p>\n\n<p>To get real value out of containers you need a vessel, whether that\u2019s <a href=\"https:\/\/docs.podman.io\/en\/latest\/markdown\/podman-compose.1.html\"><code>podman-compose<\/code><\/a> or <a href=\"https:\/\/kubernetes.io\">Kubernetes<\/a>, you need something that will let you take advantage of everything being the same shape.<\/p>\n\n<p>For someone that just wants to run something on their server that they administer themselves, these tools are a whole new system to the way they\u2019re used to working. When a project says \u201crun this with Docker\u201d what they\u2019re doing is asking you to fit a 40 foot container onto a dinghy.<\/p>\n\n<p>I think that containers at this scale should be treated as a tool instead of a whole system; developers can package their application and its dependencies in a standard way across all distros, and have it run in the same environment without needing to adapt to the actual machine it\u2019s running on. It\u2019s then up to the distro to provide a way for the user to manage the application <em>without<\/em> knowing it\u2019s backed by a container. Let the container be a packaging tool.<\/p>\n\n<p>With that in mind, if you\u2019re still reading, the tool that gets as close to this as possible is <a href=\"https:\/\/docs.podman.io\/en\/latest\/markdown\/podman-quadlet.1.html\">podman quadlets<\/a>, which let you run containers as systemd services. You still have to know they\u2019re backed by a container, but it can be managed the same way as other services on your system.<sup id=\"fnref:quadlet-reading\"><a href=\"#fn:quadlet-reading\" class=\"footnote\" rel=\"footnote\" role=\"doc-noteref\">3<\/a><\/sup><\/p>\n\n<div class=\"footnotes\" role=\"doc-endnotes\">\n  <ol>\n    <li id=\"fn:jekyll-end\">\n      <p>The end result was that I tried updating some of the dependencies to work with the current version of Node, realised it would be a serious effort, then gave up. That would have happened with or without containers though.\u00a0<a href=\"#fnref:jekyll-end\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:linux-swift-support\">\n      <p><a href=\"https:\/\/www.swift.org\/platform-support\/\">Ubuntu, Debian, Fedora, RHEL, and Amazon Linux<\/a> at the time of writing.\u00a0<a href=\"#fnref:linux-swift-support\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n    <li id=\"fn:quadlet-reading\">\n      <p>I\u2019d <a href=\"https:\/\/matduggan.com\/replace-compose-with-quadlet\/\">read this<\/a> as a nice overview of how and why to use quadlets.\u00a0<a href=\"#fnref:quadlet-reading\" class=\"reversefootnote\" role=\"doc-backlink\">&uarr;<\/a><\/p>\n    <\/li>\n  <\/ol>\n<\/div>\n\n\n<a href=\"https:\/\/willhbr.net\/2026\/01\/15\/why-containers\/\">Permalink<\/a>\n&bull; January 15, 2026\n&bull; Send feedback via\n  <a href=\"https:\/\/ruby.social\/@willhbr\" target=_blank>mastodon<\/a> or\n  \n  <a href=\"mailto:feedback@willhbr.net?subject=Feedback:%20Why%20Containers?\">email<\/a>.\n","url":"https:\/\/willhbr.net\/2026\/01\/15\/why-containers\/","image":"https:\/\/willhbr.net\/images\/opengraph.webp","tags":["homelab","opinion","podman"],"date_published":"2026-01-15T00:00:00+11:00","date_modified":"2026-01-15T00:00:00+11:00","authors":[{"name":"Will Richardson"}]}]}