Skip to content

Parsing at the boundary

Relay gets webhooks from a CI system and from a cron runner. They describe the same thing, a job changing state, in different words: CI says build.finished with a conclusion, cron says state: "ok". Inside Relay there is one vocabulary, the JobEvent union from lesson 2.

The body arrives as unknown. The rule is parse, don’t validate: check the body once, at the edge, and produce a JobEvent. Code after the edge takes a JobEvent and never looks at raw data again. For unknown and isRecord, see M1 lesson 10.

A validator that returns boolean throws away what it learned:

declare function looksLikeCiBody(body: unknown): boolean
function handle(body: unknown) {
if (!looksLikeCiBody(body)) throw new Error("bad body")
// @ts-expect-error: 'body' is still unknown, the check left no trace in the type
return body.build.id
}

The usual fix is a cast, body as CiBody. That moves the risk to the cast: if the validator and the type drift apart, nothing notices. A parser returns the precise type, so the knowledge can’t be lost:

type JobEvent = { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number }
declare function parseCi(body: unknown): JobEvent
declare const body: unknown
const event = parseCi(body) // JobEvent: the proof is the return type

A parser is built from tiny readers. Each takes an object and a key, and either returns the right type or throws with the path in the message, so the log says which field was wrong:

type Obj = Record<string, unknown>
function readString(obj: Obj, key: string, source: string, path: string = key): string {
const value = obj[key]
if (typeof value !== "string") throw new Error(`${source}: ${path} must be a string`)
return value
}
function readNumber(obj: Obj, key: string, source: string, path: string = key): number {
const value = obj[key]
if (typeof value !== "number") throw new Error(`${source}: ${path} must be a number`)
return value
}

noUncheckedIndexedAccess makes obj[key] possibly undefined, and Record<string, unknown> already holds unknown, so the typeof check is the only thing between the data and your types.

A bad webhook is the sender’s mistake, so throwing is fine for now. Lesson 6 turns these throws into values.

Each source gets its own parser. It maps the foreign shape to JobEvent and normalizes the vocabulary, so CI’s "build.finished" plus "success" becomes JobSucceeded:

type JobEvent =
| { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number }
| { readonly _tag: "JobStarted"; readonly jobId: string; readonly worker: string; readonly at: number }
| { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string; readonly at: number }
| { readonly _tag: "JobSucceeded"; readonly jobId: string; readonly at: number }
declare function readString(obj: Record<string, unknown>, key: string, source: string): string
declare function readNumber(obj: Record<string, unknown>, key: string, source: string): number
export function parseCron(root: Record<string, unknown>): JobEvent {
const jobId = readString(root, "job", "cron")
const at = readNumber(root, "at", "cron")
const state = readString(root, "state", "cron")
switch (state) {
case "queued":
return { _tag: "JobQueued", jobId, at }
case "running":
return { _tag: "JobStarted", jobId, worker: readString(root, "host", "cron"), at }
case "ok":
return { _tag: "JobSucceeded", jobId, at }
case "error":
return { _tag: "JobFailed", jobId, reason: "failed", at }
default:
throw new Error(`cron: unknown state ${state}`)
}
}

The default branch matters. A sender can add a state tomorrow, and the parser must refuse it instead of passing it along. state is a plain string here because that is what the wire gives you, so never exhaustiveness doesn’t apply. The default throw is the check.

Sources map to parsers, so a table is neater than an if chain. satisfies checks that every entry has the right shape and keeps the exact keys:

type JobEvent = { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number }
declare function parseCi(body: unknown): JobEvent
declare function parseCron(body: unknown): JobEvent
const parsers = { ci: parseCi, cron: parseCron } satisfies Record<string, (body: unknown) => JobEvent>
parsers.ci // ok
// @ts-expect-error: Property 'github' does not exist
parsers.github

The source name comes from the URL, so it’s an arbitrary string. Indexing with it fails:

declare const parsers: { readonly ci: () => void; readonly cron: () => void }
declare const source: string
// @ts-expect-error: 'string' can't be used to index the table (implicit any)
parsers[source]

Two ways to get a safe key. The first is the M1 lesson 2 pattern: a list of valid names as const, and find, which returns the typed element or undefined:

declare const parsers: { readonly ci: () => void; readonly cron: () => void }
declare const source: string
const SOURCES = ["ci", "cron"] as const
const known = SOURCES.find((s) => s === source) // "ci" | "cron" | undefined
if (known !== undefined) parsers[known]()

The second is Object.hasOwn inside a type predicate. It checks the table itself, and it ignores inherited names like "toString":

declare const parsers: { readonly ci: () => void; readonly cron: () => void }
function isSource(name: string): name is "ci" | "cron" {
return Object.hasOwn(parsers, name)
}

parseWebhook takes any and casts. It handles CI sloppily and returns the cron body untouched. Make it take unknown, parse both sources into JobEvent, and throw the exact messages in the comment at the top.

  • Parse, don’t validate: return the precise type, so the knowledge stays in the types.
  • Small readers check one field and throw with the source and path in the message.
  • One parser per source maps its words to JobEvent, and its default refuses unknown values.
  • A table of parsers uses satisfies. Look up a string key through find or Object.hasOwn, never in or a bare index.
  • After the edge, Relay holds a JobEvent and never re-checks it.