Capstone: Relay's worker
Relay’s worker is the part that runs all day. It takes a job from the queue, tells the notifier about it, records the outcome and acknowledges the job. When the deploy script sends SIGTERM it must stop quickly, and it must not leave a lease held or a store connection open, or the next worker cannot start for a minute.
This lesson joins the module into that loop. runWorker(deps, signal) is one function. Its
signature says what it needs, what can fail, and how to stop it.
What the worker does
Section titled “What the worker does”- If the signal is already aborted, return at once. Nothing is acquired.
- Acquire the lease, then open the store connection. Both are released when the function exits, in reverse order, whatever the reason.
- Before each job, check the signal. Take a job.
nullmeans the queue is closed or the wait was interrupted, so stop. - Handle the job. Success is saved as
doneand acknowledged. A bad payload is saved asinvalidand acknowledged, because it will never get better. A failed notification is saved and not acknowledged, so the queue delivers it again. - A failing queue is fatal. Return the error. The resources still close.
How the pieces fit
Section titled “How the pieces fit”- Lesson 1:
WorkerDepsis the intersection of six ports. The test passes a fake for each, and removing one is a compile error you can see in the test file. - Lesson 2:
handleJobreturnsInvalidPayload | NotifyFailed.takeJobandackJobturn a thrown queue error into aQueueUnavailablevalue, once, at the edge.runWorkerreturnsResult<Summary, QueueUnavailable>: the only failure that stops the worker. - Lesson 3:
await usingon the lease and the connection. Disposal runs onreturn, onbreakand onthrow, in reverse order of declaration. - Lesson 4: the same
signalgoes totakeand tosend, and the loop checkssignal.abortedbetween jobs. A job in progress finishes. A job is never half done.
The shape of the function
Section titled “The shape of the function”interface Lease extends AsyncDisposable { readonly name: string}interface StoreConn extends AsyncDisposable { save(jobId: string, outcome: string, at: number): Promise<void>}interface LeasePort { readonly leases: { acquire(name: string): Promise<Lease> }}interface StorePort { readonly store: { open(): Promise<StoreConn> }}
async function runWorker(deps: LeasePort & StorePort, signal: AbortSignal): Promise<number> { if (signal.aborted) return 0 await using _lease = await deps.leases.acquire("worker") await using conn = await deps.store.open() await conn.save("start", "ok", 0) return 1}If deps.store.open() throws, the lease is still released, because it was already declared.
If conn.save throws, both are released, connection first. No try/finally is needed, and none
can be forgotten.
Testing with an event log
Section titled “Testing with an event log”Every fake appends a line to one shared array. The test then compares the whole log with the order you expect:
const log: string[] = []
const lease = { name: "worker", async [Symbol.asyncDispose]() { log.push("lease release") },}
async function run() { await using _lease = lease log.push("work")}
await run()// log is now ["work", "lease release"]A single toEqual on the log checks order, completeness and cleanup together. To stop the loop,
a test creates an AbortController, starts the worker, and calls abort(). A fake take that
waits on the signal returns null at that moment. No test sleeps, so the whole file runs in
milliseconds.
Exercise
Section titled “Exercise”The starter gives you the ports, handleJob, takeJob and ackJob. Its runWorker handles a
single job, holds no resources, and ignores the outcome. You write the loop, the await using
lines and the three outcomes. The rules at the top state the exact log lines and saved outcomes.
Run it locally
Section titled “Run it locally”In the Relay project, the composition root builds the real deps once and starts the worker with a signal tied to the process:
interface Job { readonly id: string}interface Lease extends AsyncDisposable { readonly name: string}interface WorkerDeps { readonly queue: { take(signal: AbortSignal): Promise<Job | null> } readonly leases: { acquire(name: string): Promise<Lease> }}
declare function runWorker(deps: WorkerDeps, signal: AbortSignal): Promise<{ ok: boolean }>declare const deps: WorkerDeps
const controller = new AbortController()process.on("SIGTERM", () => controller.abort(new Error("SIGTERM")))process.on("SIGINT", () => controller.abort(new Error("SIGINT")))
const result = await runWorker(deps, controller.signal)process.exit(result.ok ? 0 : 1)Replace the declares with imports of your own runWorker and a deps object backed by a real queue,
database and notifier. The process exits with a non-zero code only when the queue itself failed.
WorkerDepsis the intersection of the portsrunWorkeruses. A missing port is a compile error.- Errors from each layer are values. Per-job failures are recorded and the loop continues. Only a queue failure stops the worker.
await usingreleases the lease and the connection in reverse order on every exit path.- The same
AbortSignalreachestakeandsend. The loop checks it between jobs, so a job is finished, never abandoned. - Tests use fakes and one event log. They assert order and cleanup without any waiting.
Further reading
Section titled “Further reading”- TypeScript 5.2:
usingandawait using. - AbortSignal:
timeout(),throwIfAborted()and the abort event. - strictFunctionTypes: what the flag checks, and why methods stay bivariant.