Skip to content

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.

  1. If the signal is already aborted, return at once. Nothing is acquired.
  2. Acquire the lease, then open the store connection. Both are released when the function exits, in reverse order, whatever the reason.
  3. Before each job, check the signal. Take a job. null means the queue is closed or the wait was interrupted, so stop.
  4. Handle the job. Success is saved as done and acknowledged. A bad payload is saved as invalid and acknowledged, because it will never get better. A failed notification is saved and not acknowledged, so the queue delivers it again.
  5. A failing queue is fatal. Return the error. The resources still close.
  • Lesson 1: WorkerDeps is 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: handleJob returns InvalidPayload | NotifyFailed. takeJob and ackJob turn a thrown queue error into a QueueUnavailable value, once, at the edge. runWorker returns Result<Summary, QueueUnavailable>: the only failure that stops the worker.
  • Lesson 3: await using on the lease and the connection. Disposal runs on return, on break and on throw, in reverse order of declaration.
  • Lesson 4: the same signal goes to take and to send, and the loop checks signal.aborted between jobs. A job in progress finishes. A job is never half done.
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.

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.

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.

In the Relay project, the composition root builds the real deps once and starts the worker with a signal tied to the process:

src/main.ts
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.

  • WorkerDeps is the intersection of the ports runWorker uses. 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 using releases the lease and the connection in reverse order on every exit path.
  • The same AbortSignal reaches take and send. 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.