Core@rhythmjs/rhythm
The core pipeline
Compose behavior around a typed input and a shared context.
Create an instance#
Rhythm<S, I, D> tracks three kinds of context. S is the startup context, added with register. I is the input the caller supplies on every call. D is what request-time derive steps add. You rarely write them out: S and D grow as you chain, and I is inferred from what you mount. An optional name (and type, which defaults to "module") labels errors from mounted and included modules.
import { Rhythm, decorate, derive } from "@rhythmjs/rhythm";
const app = new Rhythm({ name: "jobs" })
.register(decorate(() => ({ service: "worker" })))
.use(derive(() => ({ requestId: crypto.randomUUID() })))
.use((ctx) => console.log(ctx.service, ctx.requestId));Reading a field that was never added is a compile error, and a field is only visible to the steps after the one that added it. To add a field, use decorate or derive; plain assignment to an unknown field is rejected on purpose.
Run and reuse#
callback() returns the reusable async handler. It builds a shallow context from the startup values plus the input, runs it through the chain, and resolves with the final context. The input is required when I has required fields and optional otherwise. See Startup context.
Finish configuring the pipeline before obtaining a handler: it is built from the middleware registered so far.
const handle = app.callback();
const ctx = await handle();
console.log(ctx.service); // worker
const greet = new Rhythm<{}, { name: string }>().use((ctx) => console.log(ctx.name)).callback();
await greet({ name: "Ada" });When you are done, await app.stop() runs the cleanups registered with register. Rhythm is also AsyncDisposable, so await using app = new Rhythm()... stops it for you.
Understand state#
Every call gets a new top-level context object, so a derive or a plain assignment never leaks into the next call. Startup values are shared references, though: mutating an object you added with decorate is visible to every call. Avoid mutable shared request state in the startup context.
Choose a composition boundary#
Two functions compose pipelines, and the difference is when they run:
mount(plugin)runs another pipeline (aRhythm, a router, a cron, a cli) on every call. Use it for request-time work.include(module, pick)runs aRhythmmodule once at startup and copies selected fields into the parent's startup context. Use it for long-lived dependencies.
A mounted Rhythm module gets a copy of the context, so what it derives stays sealed inside it. Routers and clis work on the request context itself, so what they write (the response, the exit code) is visible to the host. Either way, the plugin's derived fields never appear in the host's type. See Encapsulated modules.