Supervision with ensemble

jlt-commons/ensemble brings Erlang's processes, gen_server and supervisors to Jolt. plumeria.ensemble lets a plumeria server sit in an ensemble supervision tree, and gives handlers a supervised pool of workers that keep state, such as one database connection each.

ensemble isn't a dependency of plumeria. An app that requires plumeria.ensemble adds it:

{:deps {io.github.jlt-commons/ensemble
        {:git/url "https://github.com/jlt-commons/ensemble"
         :git/sha "b3accee747667f79396c6fa7f8115adfbcd37b69"}}}

examples/ensemble_server.clj is the whole thing in one file; run it with jolt -A:test -m ensemble-server from this repo.

The shape of an app

flowchart TD
    app["your app's supervisor<br/>:rest-for-one"]
    pool["pool supervisor<br/>(pool-spec db), :one-for-one"]
    w0["worker 0<br/>gen_server, its own state"]
    w1["worker 1"]
    w2["worker 2"]
    web["server child<br/>(server-spec handler opts)<br/>a gen_server holding the run-server handle"]
    conns["accept loop and one fiber per connection<br/>(plain plumeria, outside any actor)"]
    app --> pool
    app --> web
    pool --> w0
    pool --> w1
    pool --> w2
    web -.->|run-server| conns
    conns -.->|pool-call!| w0
    conns -.->|pool-call!| w1
    conns -.->|pool-call!| w2
(require '[ensemble.supervisor :as sup]
         '[plumeria.ensemble :as ens])

(def db (ens/pool {:name :app/db :size 4 :worker ->DbWorker}))

(defn handler [req]
  (let [row (ens/pool-call! db [:get-user (:uri req)])]
    {:status 200 :body (pr-str row)}))

(sup/start {:strategy :rest-for-one}
           [(ens/pool-spec db)
            (ens/server-spec handler {:port 8080 :name :app/web})])

Order the children by what depends on what. The supervisor starts them in order, so the pool is up before the server takes its first request. It stops them in reverse, so the server drains its requests while the workers they call are still there. With :rest-for-one, a pool that has to start over takes the server down and back up with it.

The server as a child

(server-spec handler opts) takes run-server's options plus:

keydefault
:id:plumeria.ensemble/serverthe child's id in its supervisor
:namenoneregister the server's actor, for server-handle
:restart:permanent:transient or :temporary as in OTP
:shutdown:drain-ms + 5000how long the supervisor waits for the stop

The child is a gen_server. Its init runs run-server, so the child is up once the server has bound, and a bad option fails the supervisor's start with run-server's own message. Its terminate runs the draining stop:

sequenceDiagram
    participant S as supervisor
    participant G as server child
    participant P as plumeria
    S->>G: start
    G->>P: run-server handler opts
    P-->>G: handle {:port :stop}
    Note over S,P: serving
    S->>G: exit :shutdown
    G->>P: (stop drain-ms)
    P->>P: close the listener, finish requests in flight
    P-->>G: drained
    G-->>S: exited

The default :shutdown gives the drain 5 seconds of slack, for the stop's own steps after it (a redirect listener, TLS contexts, the ACME task). A shorter one lets the supervisor kill the child mid-stop, and whatever the stop hadn't closed yet (connections, the disk pool) stays open until another child from the same spec starts.

(server-handle :app/web) answers the map run-server answered (:port, :host, :stop and the rest). It's how a test reads the port when :port is 0, and it works with server-stats.

A plumeria server doesn't crash on its own, so restarts mostly matter when something outside kills the child. A child killed with :kill never runs its terminate, so its listener stays open. The restart closes that leftover server before it binds, which is what lets it take the same port.

Handlers run outside any actor. ensemble keeps the current actor in a dynamic var and Jolt's fibers inherit bindings, so without this, every connection fiber would think it was the server child, and a handler's gen-server/call! would wait on the child's mailbox and time out. The child starts plumeria with that binding cleared.

One spec can start several children, in two trees or as a :simple-one-for-one template. Each runs a server of its own, and a new child closes only the servers whose child is dead.

The worker pool

(defrecord DbWorker [i]
  gs/Server
  (init [_] [:ok (open-connection)])
  (handle-call [_ [op & args] _from conn] [:reply (run-query conn op args) conn])
  (handle-cast [_ _ conn] [:noreply conn])
  (handle-info [_ _ conn] [:noreply conn])
  (handle-timeout [_ conn] [:noreply conn])
  (handle-continue [_ _ conn] [:noreply conn])
  (terminate [_ _ conn] (close-connection conn)))

(def db (ens/pool {:name :app/db :size 4 :worker ->DbWorker}))
key
:namerequireda keyword; worker i registers as <name>.<i>, so :app/db gives :app/db.0 and on
:sizerequiredhow many workers
:workerrequired(fn [i] server), called again for every restart
:intensity:sizerestarts allowed in :period before the pool gives up
:period5seconds

pool-spec makes it a child of your tree; start-pool and stop-pool run it on its own (scripts, tests).

(pool-call! db request) (or with a timeout in ms, default 5000) goes to the worker with the fewest calls in flight, ties taken in turn. Each worker handles one call at a time, so a worker busy with a slow query is passed over while another is free:

sequenceDiagram
    participant H1 as handler A
    participant H2 as handler B
    participant Pool as pool-call!
    participant W0 as worker 0
    participant W1 as worker 1
    H1->>Pool: [:report ...]
    Pool->>W0: call (worker 0 now has 1 in flight)
    H2->>Pool: [:get-user 7]
    Pool->>W1: call (worker 0 is busy)
    W1-->>H2: reply
    W0-->>H1: reply, some time later

(pool-cast! db request) sends without waiting, in turn, since a cast has no reply to count. It skips a worker that isn't running, and when none is, the cast is dropped, as ensemble drops a cast to a name nobody holds.

When a worker crashes, the pool's supervisor restarts that worker alone, with fresh state from :worker; the others keep theirs:

sequenceDiagram
    participant H as handler
    participant W1 as worker 1
    participant PS as pool supervisor
    H->>W1: pool-call! [:crash]
    W1--xPS: exits with the throwable
    W1-->>H: call throws (ex-data :reason is the throwable)
    PS->>W1: start a new worker 1 (init again)
    Note over W1: fresh state, same name

The call that crashed the worker throws. A call that finds a worker not running at all, between its exit and its restart, skips to the next one and never tries the same worker twice; when every live worker is busy it queues on one of them, and only when every worker is down does it throw, with :reason :noproc. A timeout throws as gen-server/call! does (:reason :timeout), and the handler decides what to answer: uncaught, plumeria answers 500 and reports :handler-threw.

Some limits of the pool: there's no checkout, so a handler can't hold one worker across several calls (send one request that does all of it instead), and calls queue in each worker's mailbox with nothing bounding the queue but the call timeout.