Skip to content

State machines

Relay’s job has four states, and the previous lessons gave each one its own type. Now the jobs have to move. A webhook says a worker started job j1, another says it failed. Some moves are legal and some are bugs: a succeeded job must never start again, and a queued job can’t fail because nothing ran.

This lesson types the moves. Where the compiler knows the state, an illegal move doesn’t compile. Where it can’t know, because the event just arrived from the network, the illegal move comes back as a value the caller has to look at.

queued -> running (JobStarted)
running -> failed (JobFailed)
running -> succeeded (JobSucceeded)
failed -> queued (JobQueued, a retry)

Every other pair is invalid. succeeded has no way out. Write this down before the types: each arrow becomes one function, and anything without an arrow gets no function.

interface JobBase {
readonly id: string
readonly queuedAt: number
}
interface Queued extends JobBase {
readonly status: "queued"
}
interface Running extends JobBase {
readonly status: "running"
readonly startedAt: number
readonly worker: string
}
interface Failed extends JobBase {
readonly status: "failed"
readonly startedAt: number
readonly worker: string
readonly finishedAt: number
readonly reason: string
}
interface Succeeded extends JobBase {
readonly status: "succeeded"
readonly startedAt: number
readonly worker: string
readonly finishedAt: number
}
function start(job: Queued, worker: string, at: number): Running {
return { id: job.id, queuedAt: job.queuedAt, status: "running", startedAt: at, worker }
}
function fail(job: Running, reason: string, at: number): Failed {
return {
id: job.id,
queuedAt: job.queuedAt,
status: "failed",
startedAt: job.startedAt,
worker: job.worker,
finishedAt: at,
reason,
}
}
declare const succeededJob: Succeeded
// @ts-expect-error: a succeeded job is not a Queued job
start(succeededJob, "w1", 1)

The parameter type is the precondition and the return type is the result. start accepts only a Queued job, so calling it on a finished one is a compile error, not a Tuesday-night incident.

Why not start(job: Job): Job? Because Job includes Succeeded, so start(succeededJob, ...) compiles, and the body can’t even read job.startedAt without checking the status first. The wide signature moves the rule from the compiler into your head.

Copying with a spread looks shorter:

interface Queued {
readonly id: string
readonly queuedAt: number
readonly status: "queued"
}
interface Failed {
readonly id: string
readonly queuedAt: number
readonly status: "failed"
readonly reason: string
}
declare const failed: Failed
// Compiles, but the value still has `reason` at runtime.
const sloppy: Queued = { ...failed, status: "queued" }
// Listing the fields is checked: an extra field is an error.
// @ts-expect-error: object literal may only specify known properties
const checked: Queued = { id: "j1", queuedAt: 1, status: "queued", reason: "timeout" }

The compiler does not run excess property checks on spread members, so sloppy type-checks. At runtime it is a queued job that still carries reason, and JSON.stringify will send it onward. Written out field by field, the same mistake is an error. Build each new state explicitly: the object literal is the only form where the compiler checks every key.

The narrow functions work when you already know the state. A webhook doesn’t tell you that. You have a Job and a JobEvent, and you must find out which combination you hold. That’s a nested switch: first on the event’s _tag, then on the job’s status.

interface Queued {
readonly id: string
readonly queuedAt: number
readonly status: "queued"
}
interface Running {
readonly id: string
readonly queuedAt: number
readonly status: "running"
readonly startedAt: number
readonly worker: string
}
type Job = Queued | Running
type JobStarted = { readonly _tag: "JobStarted"; readonly jobId: string; readonly worker: string; readonly at: number }
declare function start(job: Queued, worker: string, at: number): Running
declare const job: Job
declare const event: JobStarted
switch (job.status) {
case "queued":
start(job, event.worker, event.at) // job is Queued here
break
case "running":
// start(job, ...) would not compile here
break
}

Inside case "queued", job is narrowed to Queued, so the call to the narrow start compiles. The switch is the bridge from “some Job” to “a Queued job”.

What should transition do when a JobStarted event hits a succeeded job? That isn’t a bug in Relay, it’s a duplicate or reordered webhook, and it will happen. Throwing makes every caller remember a try. Instead return a result that says which case it is:

type Transition =
| { readonly ok: true; readonly job: { readonly id: string } }
| { readonly ok: false; readonly error: string }
function describe(result: Transition): string {
if (result.ok) return `now ${result.job.id}`
return result.error // only reachable on the failure branch
}

ok is the discriminant, so the caller can’t reach job without handling ok: false. This is a first look at errors as values. Lesson 6 does it properly.

The outer switch has four events. If someone adds a fifth, the handler must fail to compile, not fall through. Use absurd in the default (from M1’s never lesson):

type JobEvent =
| { readonly _tag: "JobQueued"; readonly jobId: string }
| { readonly _tag: "JobStarted"; readonly jobId: string }
function absurd(value: never): never {
throw new Error(`unreachable: ${JSON.stringify(value)}`)
}
function label(event: JobEvent): string {
switch (event._tag) {
case "JobQueued":
return "queued"
case "JobStarted":
return "started"
default:
return absurd(event) // error here if a tag is added and not handled
}
}

Adding JobFailed to the union turns event in default into a non-never type, and the call stops compiling at exactly the function that needs updating.

The starter types every function as (job: Job), so fail and succeed can’t read startedAt and retry(runningJob) would compile. Narrow the four signatures, then write transition for all event and state combinations, with the exact error strings in the header.

  • Draw the machine first. One function per arrow, with the source state as the parameter type and the target state as the return type.
  • Wide signatures like (job: Job): Job move the rules out of the compiler. Narrow ones make invalid calls fail to compile.
  • Spreading copies stale fields without a check. Build the next state by listing its fields.
  • For events that arrive at runtime, switch on the event, then on the status, and return { ok: false, error } for invalid moves instead of throwing.
  • End the event switch with absurd so a new event type can’t be forgotten.