• A Fluid Framework server in Gleam with beryl

    In What if we applied the Elm Architecture to Web Sockets?, I described beryl’s socket API. Each socket has its own private state. You handle an input and return the next state, plus effects that describe what should go out over the wire.

    What I didn’t mention there is that beryl was a side quest. The real goal was Floodgate, a Fluid Framework server written in Gleam.

    I already had a Fluid server, Levee, but it was split between Gleam and Elixir. Floodgate replaces it with a stack that’s Gleam all the way down. (My Fluid projects all get water names, and if you’re replacing a levee, you might as well open the floodgates.) I think the BEAM fits Fluid’s needs particularly well, and Gleam is a fun language to work with.

    A Fluid server lives on real-time sockets, though, and when I started, I couldn’t find a solid Gleam WebSocket library with an abstraction I liked. So I wrote beryl.

    That left me with something to prove. The live poll in my earlier post was fine for explaining the API, but it couldn’t show whether beryl could handle everything Floodgate needs without turning into a Fluid library. If beryl can’t stay out of Floodgate’s way, it probably won’t stay out of yours either.

    Floodgate started out speaking Phoenix Channels. Levee is built on Elixir and Phoenix, so its driver already spoke that protocol, and beryl is modeled on Phoenix Channels — Phoenix framing is its native wire format. But I also wanted to explore compatibility with Fluid’s official driver, and that one speaks Socket.IO. So I added Socket.IO support, and now a Socket.IO client and a Phoenix Channels client can edit the same document on one Floodgate server.

    Floodgate does all of this through beryl’s public API. I supply a channel handler, give each connection the right codec, and return actions for beryl to deliver. Sequencing and storage belong to Floodgate. The socket library never has to learn what a Fluid document is.

    (The code below is trimmed from the server and its tests. I’ve dropped the setup and renamed a few things so they read better out of context.)

    A little Fluid background

    Fluid Framework is Microsoft’s set of JavaScript and TypeScript libraries for building applications with shared, editable state. You work with distributed data structures — maps, collaborative text, a structured tree — and Fluid handles the operations that keep everyone’s copy in sync (including the common case where people edit at the same time).

    The application code can look like an ordinary local mutation. Floodgate’s simplest example is a shared die; clicking Roll writes a number into a Fluid SharedMap:

    import type { ISharedMap } from "@fluidframework/map/legacy";
    function rollDice(diceMap: ISharedMap): void {
    diceMap.set("diceValue", Math.floor(Math.random() * 6) + 1);
    }

    If Alice rolls a five, Fluid sends an operation (an op) that means “set diceValue to 5.” When Bob’s client receives that op, it uses Alice’s five. It doesn’t roll the die again.

    The service has three responsibilities:

    1. Sequencing: put incoming ops in one order.
    2. Broadcasting: send the ordered ops to every client.
    3. Storing: keep the ops so clients can catch up later.

    Fluid calls the first two together total order broadcast. Every client applies the ops in that one order, so their data structures end up agreeing.

    Suppose Bob rolls a two at about the same time. Each of them sees their own roll right away, before the server weighs in. If Alice’s roll gets sequence number 41 and Bob’s gets 42, both screens show two once they’ve processed both ops. The server doesn’t need to know the rules of the game. It just needs to decide the order.

    That’s the role Floodgate plays. It also checks access and stores the ops and summaries that clients need to load a document.

    Here’s the wrinkle. Alice uses the official driver for Routerlicious, Fluid’s reference server, so she connects to Floodgate over Socket.IO. Bob uses Levee’s driver, which speaks Phoenix Channels. The two drivers frame their messages differently, but they still have to agree on one sequence for the die.

    Let beryl handle the sockets

    Floodgate uses beryl’s channel layer rather than raw dispatch, which gets it topic routing and private, typed state for each accepted join. A document makes a natural topic, so I register a handler for document:*:*, and Alice and Bob both join document:fluid:shared-die.

    Once the document session and presence handles exist, the setup looks like this:

    import beryl
    import beryl/channel
    import beryl/wire
    import floodgate/document_channel
    let socket_configuration =
    beryl.config(wire.phoenix_codec())
    |> beryl.with_pubsub(publish_subscribe_handle)
    |> beryl.with_max_inbound_frame_bytes(maximum_frame_bytes)
    let assert Ok(#(sockets, socket_child_specification)) =
    channel.child_spec(socket_configuration, handlers: [
    document_channel.new(
    document_session,
    document_registration,
    presence_worker.from_name(presence_worker_name),
    maximum_frame_bytes,
    ),
    ])

    document_channel.new returns a handler built with beryl’s channel API. channel.child_spec hands back a socket handle and a child spec that slots into Floodgate’s OTP supervision tree. beryl’s processes are supervised like the rest of the application — there’s no separate server to babysit.

    The handler makes the Fluid decisions: is this token valid, and should this op be accepted? beryl runs the channel workers and takes care of subscriptions and delivery. The handler’s state stays typed, and no Fluid types leak into beryl’s socket registry.

    The default codec is Phoenix framing, and the same sockets handle goes to both transports. Which brings us to codecs.

    A codec for each connection

    Alice and Bob connect through different endpoints:

    Endpoint Client
    /socket.io/ Official Fluid/Routerlicious drivers
    /socket/websocket Phoenix Channels clients, including levee-driver

    Bob’s side is easy. The stock beryl_mist adapter inherits the runtime’s codec, Phoenix V2 JSON framing. Alice’s side takes more work. Floodgate handles the Socket.IO handshake and pings itself, and it uses Dewdrop to translate Fluid events to and from beryl’s channel format.

    beryl’s shared transport API does the rest. It enforces connection limits, registers the connection, and processes frames. (Keeping those limits in force when the limiter crashes turned into its own project. More on that in a future post.) Floodgate passes the Dewdrop codec when it registers the connection:

    import beryl/transport/server as transport_server
    import dewdrop/server as fluid_server_codec
    let #(connection_state, message_selector) =
    transport_server.init_connection(
    sockets: sockets,
    seed: transport_server.connect_seed(request, metadata),
    connection_permit: connection_permit,
    base_selector: message_selector,
    config: transport_configuration,
    force_close: fn() { force_close(connection) },
    logger_name: "floodgate.socketio",
    telemetry: telemetry,
    codec: Some(fluid_server_codec.server_codec()),
    )

    (transport_server is beryl/transport/server, and fluid_server_codec is dewdrop/server.) Most of that call is plumbing. The last argument is the one that matters for our two players: the codec belongs to the connection. Alice gets Socket.IO framing, Bob gets Phoenix framing, and they share one runtime.

    The codec has real translating to do. The Routerlicious driver sends ops with a submitOp event, passing the client ID and the op batches as separate arguments. Dewdrop folds those into one payload with named fields. It also works out the document topic from the connection request and turns connect_document into a beryl join.

    After decoding, both clients reach the same application handler:

    Alice: Socket.IO Bob: Phoenix Channels
    | |
    Dewdrop codec Phoenix codec
    | |
    +--------- beryl ---------------+
    |
    document channel
    |
    shared document actor
    |
    storage

    The drivers don’t even connect the same way. Alice’s Routerlicious driver sends the full document connection request as part of the join. Bob’s Phoenix driver joins with just a token, then sends connect_document afterward.

    This is where beryl’s private channel state is useful. I pick its Gleam type, and beryl keeps a separate value on the server for each accepted join. Bob’s state comes back to my handler with his next message. It never goes to Bob’s browser, and Alice’s channel can’t see it, even though they’re editing the same die.

    Once Floodgate checks Bob’s token, his channel state records that his document connection is still pending, and Floodgate rejects his ops until connect_document succeeds. Alice reaches the same connected state during her join. Because the channel state tracks where each connection is in the handshake, the codec stays a pure translator: it converts frames and never needs to know whether a driver has finished connecting.

    One action, two clients

    Alice clicks Roll. Her Fluid runtime creates an operation, Dewdrop decodes the message, and beryl routes it to her document channel.

    Floodgate checks Alice’s connection and hands her op to the document actor. Both players’ channels talk to the same actor, even if they opened the document at the same moment — Floodgate’s registry starts exactly one actor per document. That actor reads one request at a time from its mailbox. For each accepted op, it bumps the document’s sequence number by one and stores the numbered op before replying. Alice gets 41 because the actor handled her roll when the count was 40. Whose mouse clicked first doesn’t enter into it.

    Alice’s channel gets the numbered op back and can return this action:

    channel.broadcast(
    events.op,
    json.preprocessed_array([
    session.stored_message_to_json(#(sequence_number, message)),
    ]),
    )

    submitOp was the driver asking for the edit to be sequenced. op is Floodgate’s answer: the edit plus its sequence number.

    That call just builds an action for the channel to return. beryl finds the subscribers and encodes the event with each recipient’s codec. Alice gets a Socket.IO event. Bob gets a Phoenix frame. Neither of them knows the other one speaks a different protocol.

    There’s no special case for Bob’s protocol anywhere in the op handler, and the handler never touches his WebSocket. It returns state and actions, Elm Architecture style, and beryl applies the actions in order for that channel.

    Notice that channel.broadcast doesn’t take a topic. Alice’s handler can’t send her roll to the wrong document because of a typo. If I really wanted to broadcast somewhere else, I’d have to call beryl.broadcast and name the topic explicitly. (This is the restriction I said I came around to last time.)

    The callback isn’t pure, I’ll admit. It verifies tokens and calls shared actors. But everything it wants to send to clients comes back as a list of actions I can read.

    One actor per document is also why, for now, Alice and Bob need to be on the same Floodgate instance. Each instance has its own actor registry and, by default, its own storage. If two instances both accepted rolls for the same die, they could both hand out 41, and broadcasting both rolls wouldn’t tell anyone which came first. beryl can already broadcast and track presence across BEAM nodes, but Floodgate doesn’t coordinate document edits across nodes yet.

    The server can send messages, too

    Not everything Floodgate sends is a reply. A presence worker needs to give Bob the current roster. A targeted signal needs to reach exactly one document connection.

    beryl gives each accepted join a typed sender. I can hang on to that sender and call channel.notify from another process to deliver a value to the join’s on_info callback. Floodgate’s notification type looks like this:

    pub type DocumentNotification {
    SignalPush(payload: json.Json)
    EventPush(event: String, payload: json.Json)
    }

    And the callback turns the notification into an action:

    channel.accept(channel_state)
    |> channel.on_info(fn(state, notification) {
    case notification {
    SignalPush(payload) ->
    channel.next(state, [channel.push(events.signal, payload)])
    EventPush(event, payload) ->
    channel.next(state, [channel.push(event, payload)])
    }
    })

    The presence worker sends a plain Floodgate value and doesn’t care how Bob connected. The compiler checks every message this callback handles. (Incoming JSON from clients still needs runtime validation — types only get you so far.)

    From Bob’s side, a roster update or signal arrives on the same connection as his ops. On the server, it goes through the same state-and-actions loop as a reply. If beryl only gave me a socket to write frames to, I’d have to build that loop myself, along with typed messages and lifecycle callbacks. Channels come with all three.

    Bob closes the tab

    Eventually Bob gets bored and closes the tab. Alice should stop seeing him in the audience, but the die should keep its value.

    Floodgate cleans up membership and presence in channel.on_terminate, which beryl calls when the channel ends. If Bob’s connection silently drops (thanks, hotel Wi-Fi), the server stops getting his heartbeats, evicts him, and ends up in the same callback.

    beryl detects the disconnect, and Floodgate decides what to do about it. It removes Bob’s membership and, if he was a writer, sequences a leave op. That’s not just about the audience list. Every writer reports how far through the op history it has read, and the lowest of those positions is the document’s minimum sequence number. Every connected writer has seen every op up to that number, so clients can drop the extra bookkeeping they keep for older ops. If Bob’s stale position stuck around, the minimum would stop moving, and that bookkeeping would pile up indefinitely.

    The stored history belongs to the document, so Bob leaving doesn’t delete it. Someone can open the document later, load a stored summary, and replay the ops that came after it.

    And there’s no separate cleanup path for Socket.IO and Phoenix. Both transports go through beryl’s lifecycle, so one callback handles the document work for both.

    Testing both protocols together

    A Socket.IO client and a Phoenix client both connecting isn’t enough. They need to see each other’s ops, or they aren’t really sharing a document.

    The cross-mode tests connect both drivers to one document. Once they’re connected, the core assertion is small:

    const marker = `cross-${Date.now()}`;
    const receivedOperation = waitForOperation(
    routerliciousConnection,
    (contents) => contents === marker,
    );
    submitOperation(phoenixConnection, marker);
    await expect(receivedOperation).resolves.toBe(marker);

    That sends an op through Phoenix and waits for the Routerlicious client to receive it. Another test goes the other direction. Same channel handler, same document state, two different codecs.

    There are Gleam tests for the channel lifecycle too, including heartbeat eviction and presence cleanup. But the cross-mode tests use the real Fluid drivers, so they catch frames that look right to me but don’t match what the drivers expect.

    What’s next

    The poll in the last post was a tidy little example of the state-transition loop. Floodgate gives the same loop a lot more to do — two wire protocols, server-originated messages, cleanup that changes shared state — and all of it fits through beryl’s public API. That means I can keep chasing Fluid compatibility in Floodgate without turning beryl into a Fluid library.

    There’s plenty left to do. Floodgate only sequences a document on one node today. If you want to poke at Floodgate, the README covers running it locally or in Docker. And if you’re building something real-time in Gleam, give beryl a look and let me know whether it stays out of your way.

    Permalink →

  • Fun with magnets!

    For most of my adult life I have been depressed. Over the past few years, as my family and I have endured a seemingly endless cavalcade of pain and suffering, my depression has gotten steadily worse. My sister’s death, our infertility, the loss of my cousin to cancer… it all takes its mental and emotional toll. My depression was recently supplemented by a new diagnosis — prolonged grief disorder. The Butlers have always been pioneers in various ways, so I suppose I’m proud to be the first Butler to be sporting a DSM-5-recognized diagnosis! A dubious honor, but it did help make sense of some of the things I’ve been feeling.

    I have not been alone in my fight against depression. My wife and family are with me. I have good mental health benefits which I take advantage of. I see a therapist. I also take medication, and the number and dosage of my medications have grown over the years as the fight has intensified. Sometimes it feels like I have to work incredibly hard just to stay afloat, let alone make any positive progress. I took three months of leave last year to try to get on top of it, and it helped. I’m glad I did it! But I’m still not in good shape.

    Which is what brought me to another treatment that sounds like hogwash but is real: treating depression with high-powered magnets. That’s basically what repetitive transcranial magnetic stimulation (rTMS) is. High-powered magnetic pulses are shot into my brain, where they induce a small electric current and help form new neural pathways. Pathways which, if all goes to plan, will help my brain better cope with the realities of depression. My goal is not to get off medication entirely, though that would of course be welcome. Rather, I just hope to reduce the need for so many meds, or make the meds more effective.

    What it’s like

    The science behind rTMS is pretty cool, and you can read more about it, but what you might not be able to find is a description of what the treatments are like. That’s what I hope this helps with. And note that I said treatments. This is not a one-time thing. rTMS is 8 weeks of 20-minute treatments at an office in Seattle. With the commute it’s about 80–90 minutes of commitment, every weekday. It’s a lot.

    Fortunately, the treatments aren’t uncomfortable for the most part. I don’t have to be strapped down or anything, but I do have to wear a skullcap that makes me look a little like a Mercury astronaut. Then the machine fits over my head and my head gets anchored in place. Having your head anchored to a beam isn’t really that bad as long as you don’t start to slouch or move your head too much. Then it becomes very apparent that your head is relatively immobile.

    Each session consists of three-second pulses of the magnet, spaced 20–30 seconds apart, for 20 minutes total. The pulses themselves are like a jackhammer — well, that implies pain, and it’s not really painful. So maybe a woodpecker? And it doesn’t feel like it’s hitting your skull directly. It’s more like it’s tapping on a helmet.

    There is an electric current being induced, though, and the pulses are going into my right forehead, so each pulse causes the right side of my face to seize up and my jaw to clench. The techs tell me that I am getting a relatively low power (which is good, because it means fewer side effects) and that some folks need to use a mouth guard because of the clenching. It sounds a lot worse than it is.

    At my first session, they also did a test where a single pulse was sent and they watched for movement in my thumb. They then adjusted the power of the magnet accordingly. This means that the first time you experience the magnet it’s not the full three-second woodpecker that is the standard experience.

    Trying to read without my glasses for 20 minutes is more annoying than the treatments themselves.

    Effects and side effects

    The biggest side effect I’ve had with rTMS is fatigue. They tell me that the treatments are essentially a brain workout, similar to a long night of hard studying. I get the treatments mid-afternoon because anything else would completely blow up my schedule, and afterwards it is often hard for me to get a lot done for the rest of the day. But I am an early riser anyway, and do my best work in the morning, so I manage OK. And one never grows too old to enjoy an afternoon nap!

    So far I haven’t noticed any miraculous healing or anything. Mental health rarely has quick fixes. That said, there are some signs that the dense fog of malaise is lifting. I have been enjoying video games to some extent again. Hades II and Outer Worlds 2 so far, but I am excited about Ocarina of Time as well. I have a little more natural curiosity about things, especially work-related things, than I have had in some time. I continue to work on a variety of side projects. All of this bodes well. If the trend continues, I should feel much better in a few months, and hopefully with less medication.

    Permalink →

  • Stop re-explaining your conventions in code review: Keeping a codebase coherent with repopo

    In her piece Test Coverage Won’t Save You, Jenn Cooper argues that coding agents spread incoherence across a codebase faster. One line stood out to me, because it’s proven true in my own projects:

    Every merged PR becomes a precedent.

    The natural outcome is a feedback loop. An agent copies whatever patterns it finds, and it can create and spread bad patterns all on its own.

    I’ve been building a tool called repopo that enforces repo policies: the conventions you’d otherwise explain in code review, PR after PR. I think it could also be useful for exploring the just-in-time agent coaching Jenn talks about: telling an agent what to fix, and what not to break, at the moment it’s working.

    Origins

    Repopo came out of my work on the Fluid Framework. We had a lot of rules we needed to enforce across the repo that didn’t belong to any particular linter. ESLint is great for code, but it’s not great for questions like, “Is this project set up properly?” “Does this package have a README?” “Does the README have the right sections?” Those rules are about the repo itself.

    So we built a policy check tool into our build tooling and made it flexible. It runs against files in the repo that match a regex, and it can fix many problems automatically. It worked well enough in Fluid that I wanted the same thing everywhere, but I didn’t want to bring Fluid’s build tools everywhere.

    The result is repopo: a lint tool for any file in your Git repo, with a straightforward way to write your own policies. It aims to be fast enough to run in your inner dev loop.

    Fitness functions

    Jenn recommends fitness functions: checks that protect properties of a system’s architecture rather than its behavior. Her examples include forbidding certain service calls and capping bundle growth. She also stresses what you tell an agent after a check fails — how to fix the violation and what it shouldn’t break.

    Now, you can write architectural checks in a test runner. Nothing stops a test from asserting import boundaries. But a passing test suite can’t tell you about something you never took the time to write a test for, and repo-wide tests take plumbing that most people won’t bother to build.

    Repopo makes those checks cheaper to write. Instead of writing a test that loads every file in the repo and checks each one, you define policies and repopo handles the common plumbing. You can write your own policies or use the bundled ones. A file policy matches paths with a regular expression and runs a handler for each matching file. The handler can return an error with instructions for a manual fix, or, if the change is mechanical, it can fix it.

    I use a bunch of the built-in policies for package metadata and scripts in my tools monorepo, but a repo-specific rule shows the connection to Jenn’s argument better.

    An example: one place for task config

    In my monorepo, each package’s package.json scripts hold the implementation commands, and nx.json holds shared Nx orchestration. Package-specific target settings go in package.json under nx.targets. But Nx also supports package-level project.json files, so a contributor — human or otherwise — could add one, configure a task, and pass every test.

    Sounds harmless, right? Except now there are two places to configure tasks, and the next person doesn’t know which one is right. With luck they’d follow the most common pattern, but they might follow the most recent one instead, and that sends them down the project.json path again. That’s the feedback loop I talked about earlier.

    So I banned it. In this repo, we don’t use project.json:

    const NoPackageProjectJson = {
    name: "NoPackageProjectJson",
    description:
    "Keeps Nx task orchestration centralized instead of adding package-level project.json files.",
    match: /^packages\/.*\/project\.json$/,
    handler: async () => [
    {
    message:
    "Package-level project.json files split task configuration across competing locations.",
    manualFix: [
    "Put implementation commands in the package's package.json scripts.",
    "Put shared orchestration and task defaults in root nx.json.",
    "Use package.json nx.targets for package-specific target settings.",
    "Follow packages/repopo/package.json and nx.json as examples.",
    "Preserve required tasks and caching settings when migrating; do not delete functionality to pass this check.",
    ].join("\n"),
    },
    ],
    } satisfies FilePolicyDefinition;

    There’s no auto-fix here. If repopo finds one of these files, something went wrong, and a person (or an agent) needs to fix it.

    You could also add a rule to your AGENTS.md that says, “Don’t add project.json; do it this way instead.” The problem is that agents, just like humans, don’t always follow the rules. You still need something deterministic to enforce them. Ideally your agents rarely break the rule, just like your humans rarely break it — but when they do, something reliable catches it.

    The manual fix steps describe what’s wrong and what’s right at the moment the contributor is paying attention, because they just made the change and the check runs in their inner loop.

    And don’t skip that last manual fix step: “Preserve required tasks and caching settings when migrating; do not delete functionality to pass this check.” Deleting the new project.json without moving its behavior would satisfy the path check and break the change. Jenn calls out this failure mode directly: an agent will optimize for a green check at the expense of the feature you asked for.

    Repository policies

    Some rules need more context than a single file. For those, repopo has repository policies, which run once after the file policies finish.

    The built-in SharedDependencyVersions policy is a good example — it checks that members of a Cargo workspace agree on dependency versions. It’s a Rust-specific policy, but the same API is there for your own cross-file rules.

    Could you use them for Jenn’s example of tool handlers calling AI services? Sure, but it’s harder than it sounds. Do you care about direct imports only, or calls through intermediate modules? What about import aliases? Dynamic imports? A text search for one import string will leave gaps. If your linter or a dependency-analysis tool already handles the boundary you need, use that. Repopo is useful for checks that don’t have a better home, but it’s not a general-purpose replacement for existing static analysis tools.

    Ratchets

    Jenn also describes ratchets for measurable things like bundle size: set a ceiling at the current value, then fail the check when a change increases it by too much.

    I wouldn’t use repopo for bundle size. You can’t measure a bundle until you build it, and a full build is too slow for a check you run in your inner loop. Bundle size checks should run in CI at minimum, and a dedicated bundle-size tool will do the job better than anything you write yourself. Those tools already handle compression, per-entry-point budgets, and reporting the change on each PR.

    Ratchets on source files are a different story. Repopo already walks the files in your repo, so a custom policy can count lines or find files that still use a deprecated pattern without waiting for a build. Have the policy compare the result against a limit in committed config and report both numbers when it fails.

    Pick the number with care, though. A file-length limit sounds reasonable until an agent splits one understandable module into four awkward ones to get under it. Put that in the manual fix, too: a split has to leave each module easier to read.

    What repopo won’t do

    There’s a lot repopo leaves up to you:

    • No built-in ratchets. There are no historical baselines. You write the measurement and comparison, and you own the review process.
    • It only sees what Git sees. The default file inventory comes from Git, so ignored build output won’t show up. That’s one more reason to leave bundle size to a dedicated tool.
    • It’s not a commit gate. Repopo exits nonzero when there are unresolved violations. Wiring that into CI or a local build is up to you.
    • It can’t judge design. It can reject a forbidden file. It can’t tell you whether two helpers express the same idea, or whether a new abstraction is worth the extra code.

    That last one is where the agent-based reviews Jenn describes come in, including reviews that flag tests preserving patterns the team wants to retire. I’d run those alongside deterministic checks. When a reviewer keeps flagging the same problem, ask whether the rule is precise enough to become a policy. If it is, write the policy and stop leaving the same review comment.

    Try it

    To try it, install repopo globally or, if you’re working on a TypeScript/JavaScript project, into your project as a dependency.

    Without a config file, repopo runs a small default set of policies. To use your own, create repopo.config.ts in the root of your repo and register them with makePolicy:

    import { type FilePolicyDefinition, makePolicy, type RepopoConfig } from "repopo";
    const NoPackageProjectJson = {
    // The policy from earlier in this post
    } satisfies FilePolicyDefinition;
    const config: RepopoConfig = {
    policies: [makePolicy(NoPackageProjectJson)],
    };
    export default config;

    Then run:

    Terminal window
    repopo check # report violations
    repopo check --fix # fix what can be fixed automatically

    If you installed repopo as a project dependency, prefix those commands with npx.

    I’d put the read-only check in CI and ask agents to run it before they declare a task done. The docs cover the rest, including partial checks.

    If you’ve got a convention you’re tired of re-explaining in code review, give repopo a try. If you write a policy other people could use, send a PR, or export it from your own package like I do with sort-tsconfig.

    Permalink →

  • Bundling Gleam dependencies with trellis 1.1

    Beryl is my library for type-safe channels over Web Sockets. I eventually want to publish it to Hex so that others can find and use it with as little friction as possible. Beryl as a whole targets the Erlang runtime, because it has hard dependencies on BEAM infrastructure and is primarily a server-side library.

    However, there is a piece of beryl that can target both JavaScript and Erlang — the state machine of the core protocol. I wanted to break that piece out so that I could find out whether a beryl-like runtime could run on Cloudflare Durable Objects. Spoiler alert: it can, but more on that in a future post.

    I broke out the core state machine into its own package, beryl_protocol, which you can think of as the pure rules for a connection. It tracks things like: Has this client joined this topic? Is a join still waiting for approval? Can this reply still be sent? Has the connection timed out?

    The rest of beryl does the actual work: it calls your code, sends data, and manages processes. All of that code remains in the beryl package, which is tightly coupled to the BEAM.

    This separation raised a question: what should I do with the beryl_protocol package when it comes time to publish to Hex? Right now, with Git-only releases, consumers can just use beryl directly without knowing that beryl_protocol exists. It is an implementation detail of how the code is structured, not something users should think about.

    I could publish beryl_protocol as a separate library. Maybe someone else would use it! (Hubris!) But I don’t want to create a separate release just because I found a useful separation within my project. Packages such as beryl_mist and beryl_ewe give users a choice of transport, which makes separate releases useful. There’s no compelling reason to offer the protocol package on its own, especially not just to satisfy a Durable Objects experiment, which can use a Git dependency instead.

    I wanted to keep beryl_protocol as a separate package in the repository so I could build and test it on both Erlang and JavaScript. For Hex, though, I wanted to ship its source inside beryl.

    Since I already use trellis to manage releases, I added source bundling in trellis 1.1. It’s specifically designed around beryl’s needs, but I think it will suit other similar cases where the package boundary makes sense inside a project but not outside it. My root gleam.toml includes:

    [tools.trellis.publish.bundle]
    beryl = ["beryl_protocol"]

    When I publish beryl, trellis creates a temporary package with both source trees. It preserves the module names and imports, removes the separate beryl_protocol dependency, and includes its external runtime requirements. It then validates and publishes the combined package without changing my checkout. Conflicts, such as duplicate module names or differing dependency requirements, stop publication. Those checks only cover the package I’m publishing. A consumer who installs beryl alongside a separate copy of beryl_protocol can still hit a module collision.

    Consumers will install beryl without a separate protocol release, and I keep a package boundary that holds the protocol honest about JavaScript support.

    The trellis source bundling docs cover the details, and the beryl workspace configuration is a working example.

    Permalink →