The per-container monitor and its Unix socket
Relay’s first job runner was one long-lived process that spawned every job. It was a single point of failure: a
deploy restarted it, and every job in flight died with it. Worse, only that process knew which jobs were running, so
after a restart nobody could say what had been lost. A container tool has the same shape of problem. If tsbox run
starts a container and then exits (it must, it is a CLI), who waits for the container, collects its exit code and
keeps its log?
The usual answers are a daemon (Docker) or a small helper process per container (podman’s conmon). tsbox follows
podman: no daemon, and one monitor per container.
A monitor instead of a daemon
Section titled “A monitor instead of a daemon”A daemon is one process for all containers. It needs root or a service manager, it must be upgraded without losing state, and when it crashes everything on the machine is affected. A monitor is one process for one container, and that gives it a short list of jobs:
- start the container process and own its stdio;
- record state changes:
Created,Running,Exited; - write the container’s output to a log file;
- listen on a Unix socket, so other tsbox commands can ask about this one container.
tsbox run starts the monitor and exits. The monitor keeps running, because it was started in its own session. The
CLI is a short-lived client, and the monitor is the only process that knows the truth about its container.
const monitor = Bun.spawn([process.execPath, "monitor.ts", "--id", "web"], { detached: true, stdin: "ignore", stdout: "ignore", stderr: "ignore",})
monitor.unref()console.log(`monitor started, pid ${monitor.pid}`)detached: true calls setsid on POSIX, so the monitor leaves the CLI’s session and its terminal. Closing the
terminal or pressing Ctrl-C in the CLI no longer reaches it. unref() lets the CLI exit while the child is still
running, and the three ignores mean no pipe ties the two together. Leave one out and the CLI either waits or the
monitor dies on a broken pipe.
Core: state as a function
Section titled “Core: state as a function”The monitor’s state is the ContainerState union from the module intro. What it must never do is overwrite that
state freely. A late Exited event arriving for a container that was already restarted must not mark the new one
dead. So every change goes through one pure function that accepts only the legal moves:
type ContainerState = | { readonly _tag: "Created" } | { readonly _tag: "Running"; readonly pid: number; readonly startedAt: number } | { readonly _tag: "Exited"; readonly code: number; readonly finishedAt: number }
type MonitorEvent = | { readonly _tag: "Started"; readonly pid: number; readonly at: number } | { readonly _tag: "Exited"; readonly code: number; readonly at: number }
function transition(state: ContainerState, event: MonitorEvent): ContainerState | undefined { if (state._tag === "Created" && event._tag === "Started") { return { _tag: "Running", pid: event.pid, startedAt: event.at } } if (state._tag === "Running" && event._tag === "Exited") { return { _tag: "Exited", code: event.code, finishedAt: event.at } } return undefined}The exercise returns a Result with an error message instead of undefined, and adds a third event,
SpawnFailed, which takes Created straight to Exited with code 127, the shell’s “command not found”. Time comes
in as the event’s at, so a test uses plain numbers (time is an input). Exited is final: no
event leaves it. The shell treats an illegal transition as a bug in the monitor and throws, because it cannot happen
unless the shell wired the events wrongly.
Core: framing log lines
Section titled “Core: framing log lines”The container writes to a pipe, and the monitor reads it in chunks. A chunk boundary can fall anywhere, including in the middle of a word, so a chunk is not a line. The framer keeps the unfinished tail as a carry and joins it to the next chunk:
function frameLines(carry: string, chunk: string): { lines: string[]; carry: string } { const parts = (carry + chunk).split("\n") const rest = parts.pop() ?? "" return { lines: parts, carry: rest }}
const first = frameLines("", "started\nlistening on po")const second = frameLines(first.carry, "rt 8080\n")console.log(first.lines, second.lines)split("\n") always returns at least one piece. The last piece is whatever followed the final newline: empty if the
chunk ended on a newline, otherwise the unfinished line. When the pipe closes, whatever is left in the carry is a last
line without a newline, and it must still be logged. Dropping it is the bug that makes a crash message vanish, since
a dying program often prints without a trailing newline.
Each line goes to the log file with a time and its stream: 2025-01-02T03:04:05.006Z stderr disk full. One record
per line keeps tsbox logs simple, and the stream name lets it show stderr in another colour. The stream is decoded
with TextDecoder using { stream: true }, because a chunk can also end inside a multi-byte character.
Core: a path that fits, and a state message
Section titled “Core: a path that fits, and a state message”A Unix socket is a file whose path is stored in a small fixed field, sun_path: 104 bytes on macOS and 108 on Linux,
including the terminating zero byte. A longer path does not give a nice error, it gives ENAMETOOLONG or, worse, a
silently truncated name. Temp directories on macOS are already long (/var/folders/7h/.../T/), so a deep container
directory overflows easily. The core checks the path before anything is created, counts UTF-8 bytes (not
characters), and the tests use a short mkdtemp directory. In real tsbox the socket sits in a short runtime
directory for the same reason.
What goes over the socket is the state, as one JSON line. The reader of that line must treat it as unknown, even
though tsbox wrote it: a monitor from an older tsbox may be answering, and a file in the wrong place could be some
other program’s socket. decodeState checks the tag and the numbers by hand, the same way
the networking module does for a request body.
Shell: Bun.listen on a Unix socket
Section titled “Shell: Bun.listen on a Unix socket”Bun’s socket API has the same shape for TCP and Unix sockets. Bun.listen({ unix }) returns a listener, and handlers
receive each connection:
const listener = Bun.listen<undefined>({ unix: "/tmp/tsbox-web.sock", socket: { data(socket, data) { if (data.toString().trim() === "state") socket.write('{"_tag":"Created"}\n') socket.end() }, },})
const reply = Promise.withResolvers<string>()let text = ""const client = await Bun.connect<undefined>({ unix: "/tmp/tsbox-web.sock", socket: { data(_socket, data) { text += data.toString() }, close() { reply.resolve(text) }, },})client.write("state\n")console.log(await reply.promise)listener.stop(true)The type to know is Socket<Data>: write queues bytes, end flushes and closes, and the close handler on the
client tells it the reply is complete. listener.stop(true) also closes live connections. Two things differ from TCP.
Binding to a path that already exists fails, because the file of a crashed monitor is still there, so a real
monitor deletes a stale socket file before it listens (the exercise’s shell leaves that out, because its tests use a fresh directory). And the path is a file: its permissions decide who may talk to the monitor, which is what you
want for a per-user tool.
The monitor.ts file below is the whole shell. It checks the path, opens the socket first (so ps can ask about a
container that is still Created), spawns the child with piped output, pumps each stream through the framer into the
log file one write at a time, and applies Exited only after the child is gone and its output is written. When the
program cannot be started at all, Bun.spawn throws, and the monitor reports that as SpawnFailed, an exited
container with code 127, so the user sees a state and not a stack trace. The socket stays up after the exit so that
ps can still read the final state until close() is called.
Exercise
Section titled “Exercise”Local, because the second half of the tests spawns real children and opens a real Unix socket in a temporary
directory. Copy main.starter.ts into the Relay project from tooling as main.ts, copy monitor.ts
unchanged, add the test file, and run bun test.
You write the pure core in main.ts. The starter accepts every transition (and marks a failed spawn as code 1),
splits chunks with no carry, formats log lines with a raw number, accepts any socket path and trusts the state
message without checking it. The tests check each rule exactly, then run the real monitor on sh -c commands: both
streams reach the log with a partial last line kept, a second client reads the running state over the socket and
still reads the final state after the child ends, and a program that does not exist becomes an exited 127 container.
// tsbox has no daemon. Each container gets its own small monitor process that owns the child, writes// its output to a log file and answers questions on a Unix socket. monitor.ts (the shell, given: copy it// unchanged) does the I/O. You write the pure decisions it calls. The first draft kept the container// state in a plain `let` that any code could overwrite: a late "exited" event for a container that had// already been restarted marked the new one dead, and `tsbox ps` showed a running container as Exited.//// Rules:// - transition(state, event) returns Result. Allowed, and nothing else:// Created + Started{pid, at} -> Running{pid, startedAt: at}// Created + SpawnFailed{at} -> Exited{code: 127, finishedAt: at}// Running + Exited{code, at} -> Exited{code, finishedAt: at}// every other pair is the error `cannot apply <event tag> in state <state tag>`. Exited is final.// - frameLines(carry, chunk): text arrives in arbitrary chunks. Join carry + chunk, return the complete// lines (without "\n", and without a trailing "\r") and the unfinished rest as the new carry.// flushLine(carry) is [] for "" and [carry] otherwise (output without a final newline).// - formatLogLine(at, stream, line) = "<ISO time> <stdout|stderr> <line>". parseLogLine reverses it and// returns the error `bad log line: <text>` for anything else (unknown stream, bad time, no fields).// - checkSocketPath(path): the path must be absolute ("socket path must be absolute") and at most 103// UTF-8 bytes: `socket path too long (<bytes> bytes, max 103): <path>`.// - encodeState(state) is JSON plus "\n". parseState(line) parses JSON ("state: invalid json") and// decodeState checks `unknown`: "state: expected object", "state._tag: expected Created, Running or// Exited", and `state.<field>: expected number` for pid, startedAt, code, finishedAt (in that order).export type Result<T, E> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: E }
export type ContainerState = | { readonly _tag: "Created" } | { readonly _tag: "Running"; readonly pid: number; readonly startedAt: number } | { readonly _tag: "Exited"; readonly code: number; readonly finishedAt: number }
export type MonitorEvent = | { readonly _tag: "Started"; readonly pid: number; readonly at: number } | { readonly _tag: "SpawnFailed"; readonly at: number } | { readonly _tag: "Exited"; readonly code: number; readonly at: number }
export function transition(state: ContainerState, event: MonitorEvent): Result<ContainerState, string> { switch (event._tag) { case "Started": return { ok: true, value: { _tag: "Running", pid: event.pid, startedAt: event.at } } case "SpawnFailed": return { ok: true, value: { _tag: "Exited", code: 1, finishedAt: event.at } } case "Exited": return { ok: true, value: { _tag: "Exited", code: event.code, finishedAt: event.at } } }}
export interface Framed { readonly lines: readonly string[] readonly carry: string}
export function frameLines(_carry: string, chunk: string): Framed { return { lines: chunk.split("\n"), carry: "" }}
export const flushLine = (_carry: string): readonly string[] => []
export type Stream = "stdout" | "stderr"
export interface LogRecord { readonly at: number readonly stream: Stream readonly line: string}
export const formatLogLine = (at: number, stream: Stream, line: string): string => `${at} ${stream} ${line}`
export function parseLogLine(text: string): Result<LogRecord, string> { const [at, stream, ...line] = text.split(" ") return { ok: true, value: { at: Number(at), stream: stream === "stderr" ? "stderr" : "stdout", line: line.join(" ") } }}
export const MAX_SOCKET_PATH_BYTES = 103
export function checkSocketPath(path: string): Result<string, string> { return { ok: true, value: path }}
export const encodeState = (state: ContainerState): string => JSON.stringify(state)
export function decodeState(input: unknown): Result<ContainerState, string> { return { ok: true, value: input as ContainerState }}
export function parseState(line: string): Result<ContainerState, string> { return decodeState(JSON.parse(line))}import { appendFile, writeFile } from "node:fs/promises"import { checkSocketPath, encodeState, flushLine, formatLogLine, frameLines, parseState, transition } from "./main.ts"import type { ContainerState, MonitorEvent, Result, Stream } from "./main.ts"
export interface MonitorOptions { readonly cmd: readonly string[] readonly env?: Readonly<Record<string, string>> readonly logPath: string readonly socketPath: string readonly now: () => number}
export interface Monitor { state(): ContainerState kill(signal: "SIGTERM" | "SIGKILL"): void readonly done: Promise<ContainerState> close(): void}
export async function startMonitor(options: MonitorOptions): Promise<Result<Monitor, string>> { const path = checkSocketPath(options.socketPath) if (!path.ok) return path
let state: ContainerState = { _tag: "Created" } const apply = (event: MonitorEvent): void => { const next = transition(state, event) if (!next.ok) throw new Error(next.error) state = next.value }
await writeFile(options.logPath, "") let queue: Promise<void> = Promise.resolve() const log = (stream: Stream, line: string): void => { const text = `${formatLogLine(options.now(), stream, line)}\n` queue = queue.then(() => appendFile(options.logPath, text)) }
const listener = Bun.listen<undefined>({ unix: options.socketPath, socket: { data(socket, data) { if (data.toString().trim() === "state") socket.write(encodeState(state)) socket.end() }, }, })
let child: Bun.Subprocess<"ignore", "pipe", "pipe"> try { child = Bun.spawn([...options.cmd], { env: { ...options.env }, stdin: "ignore", stdout: "pipe", stderr: "pipe", }) } catch { apply({ _tag: "SpawnFailed", at: options.now() }) return { ok: true, value: { state: () => state, kill() {}, done: Promise.resolve(state), close: () => listener.stop(true) } } } apply({ _tag: "Started", pid: child.pid, at: options.now() })
async function pump(stream: Stream, source: ReadableStream<Uint8Array>): Promise<void> { const decoder = new TextDecoder() let carry = "" for await (const chunk of source) { const framed = frameLines(carry, decoder.decode(chunk, { stream: true })) carry = framed.carry for (const line of framed.lines) log(stream, line) } for (const line of flushLine(carry + decoder.decode())) log(stream, line) }
const done = (async (): Promise<ContainerState> => { const [code] = await Promise.all([child.exited, pump("stdout", child.stdout), pump("stderr", child.stderr)]) await queue apply({ _tag: "Exited", code, at: options.now() }) return state })()
return { ok: true, value: { state: () => state, kill: (signal) => child.kill(signal), done, close: () => listener.stop(true) }, }}
export async function askState(socketPath: string): Promise<Result<ContainerState, string>> { let reply = "" const closed = Promise.withResolvers<void>() try { const socket = await Bun.connect<undefined>({ unix: socketPath, socket: { data(_socket, data) { reply += data.toString() }, close() { closed.resolve() }, }, }) socket.write("state\n") await closed.promise } catch (cause) { return { ok: false, error: `cannot connect: ${cause instanceof Error ? cause.message : String(cause)}` } } return parseState(reply.trim())}import { afterEach, expect, test } from "bun:test"import { mkdtempSync, readFileSync, rmSync } from "node:fs"import { tmpdir } from "node:os"import { join } from "node:path"import { checkSocketPath, decodeState, encodeState, flushLine, formatLogLine, frameLines, parseLogLine, parseState, transition,} from "./main.ts"import type { ContainerState } from "./main.ts"import { askState, startMonitor } from "./monitor.ts"import type { Monitor } from "./monitor.ts"
const created: ContainerState = { _tag: "Created" }const running: ContainerState = { _tag: "Running", pid: 42, startedAt: 1000 }const exited: ContainerState = { _tag: "Exited", code: 3, finishedAt: 2000 }
test("a container is created, started, then exited", () => { const started = transition(created, { _tag: "Started", pid: 42, at: 1000 }) expect(started).toEqual({ ok: true, value: running }) expect(transition(running, { _tag: "Exited", code: 3, at: 2000 })).toEqual({ ok: true, value: exited })})
test("a failed spawn exits with 127 and never runs", () => { expect(transition(created, { _tag: "SpawnFailed", at: 5 })).toEqual({ ok: true, value: { _tag: "Exited", code: 127, finishedAt: 5 }, })})
test("transitions that do not exist are errors, and Exited is final", () => { expect(transition(running, { _tag: "Started", pid: 1, at: 1 })).toEqual({ ok: false, error: "cannot apply Started in state Running", }) expect(transition(created, { _tag: "Exited", code: 0, at: 1 })).toEqual({ ok: false, error: "cannot apply Exited in state Created", }) expect(transition(exited, { _tag: "Exited", code: 0, at: 9 })).toEqual({ ok: false, error: "cannot apply Exited in state Exited", }) expect(transition(exited, { _tag: "Started", pid: 1, at: 9 })).toEqual({ ok: false, error: "cannot apply Started in state Exited", }) expect(transition(running, { _tag: "SpawnFailed", at: 9 })).toEqual({ ok: false, error: "cannot apply SpawnFailed in state Running", })})
test("frameLines keeps a partial line until its newline arrives", () => { const first = frameLines("", "hello\nwor") expect(first).toEqual({ lines: ["hello"], carry: "wor" }) const second = frameLines(first.carry, "ld\nthree\n") expect(second).toEqual({ lines: ["world", "three"], carry: "" }) expect(frameLines("", "no newline yet")).toEqual({ lines: [], carry: "no newline yet" })})
test("frameLines handles empty lines, CRLF and chunks split anywhere", () => { expect(frameLines("", "a\n\nb\r\n")).toEqual({ lines: ["a", "", "b"], carry: "" }) let carry = "" const lines: string[] = [] for (const chunk of "one\ntwo\nthree".split("")) { const framed = frameLines(carry, chunk) carry = framed.carry lines.push(...framed.lines) } expect(lines).toEqual(["one", "two"]) expect(flushLine(carry)).toEqual(["three"]) expect(flushLine("")).toEqual([])})
test("log lines round-trip through format and parse", () => { const text = formatLogLine(Date.UTC(2025, 0, 2, 3, 4, 5, 6), "stderr", "disk full: retrying") expect(text).toBe("2025-01-02T03:04:05.006Z stderr disk full: retrying") expect(parseLogLine(text)).toEqual({ ok: true, value: { at: Date.UTC(2025, 0, 2, 3, 4, 5, 6), stream: "stderr", line: "disk full: retrying" }, }) expect(parseLogLine("2025-01-02T03:04:05.006Z stdout ")).toEqual({ ok: true, value: { at: Date.UTC(2025, 0, 2, 3, 4, 5, 6), stream: "stdout", line: "" }, })})
test("parseLogLine rejects lines that are not ours", () => { for (const bad of ["", "stdout hello", "2025-01-02T03:04:05.006Z stdin hello", "yesterday stdout hello"]) { expect(parseLogLine(bad)).toEqual({ ok: false, error: `bad log line: ${bad}` }) }})
test("socket paths must be absolute and short enough for sockaddr_un", () => { expect(checkSocketPath("/tmp/m.sock")).toEqual({ ok: true, value: "/tmp/m.sock" }) expect(checkSocketPath("m.sock")).toEqual({ ok: false, error: "socket path must be absolute" }) const long = `/${"a".repeat(103)}` expect(checkSocketPath(long)).toEqual({ ok: false, error: `socket path too long (104 bytes, max 103): ${long}` }) expect(checkSocketPath(`/${"a".repeat(102)}`).ok).toBe(true) const accents = `/${"é".repeat(52)}` expect(checkSocketPath(accents)).toEqual({ ok: false, error: `socket path too long (105 bytes, max 103): ${accents}` })})
test("state messages round-trip and decode from unknown", () => { for (const state of [created, running, exited]) { expect(parseState(encodeState(state).trim())).toEqual({ ok: true, value: state }) } expect(encodeState(created)).toBe('{"_tag":"Created"}\n') expect(parseState("{nope")).toEqual({ ok: false, error: "state: invalid json" }) expect(decodeState(null)).toEqual({ ok: false, error: "state: expected object" }) expect(decodeState([])).toEqual({ ok: false, error: "state: expected object" }) expect(decodeState({ _tag: "Paused" })).toEqual({ ok: false, error: "state._tag: expected Created, Running or Exited" }) expect(decodeState({ _tag: "Running", pid: "42", startedAt: 1 })).toEqual({ ok: false, error: "state.pid: expected number" }) expect(decodeState({ _tag: "Running", pid: 42 })).toEqual({ ok: false, error: "state.startedAt: expected number" }) expect(decodeState({ _tag: "Exited", finishedAt: 1 })).toEqual({ ok: false, error: "state.code: expected number" }) expect(decodeState({ _tag: "Exited", code: 1 })).toEqual({ ok: false, error: "state.finishedAt: expected number" })})
const dirs: string[] = []const monitors: Monitor[] = []
afterEach(async () => { for (const monitor of monitors.splice(0)) { monitor.kill("SIGKILL") await monitor.done monitor.close() } for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })})
async function start(cmd: readonly string[]) { const dir = mkdtempSync(join(tmpdir(), "tsbox-")) dirs.push(dir) const socketPath = join(dir, "m.sock") const logPath = join(dir, "log") let clock = Date.UTC(2025, 0, 1) const started = await startMonitor({ cmd, logPath, socketPath, now: () => clock++ }) if (!started.ok) throw new Error(started.error) monitors.push(started.value) return { monitor: started.value, socketPath, logPath }}
test("the monitor logs both streams, frames partial lines and records the exit", async () => { const { monitor, logPath } = await start(["sh", "-c", "echo out; echo err >&2; printf partial; exit 3"]) const final = await monitor.done expect(final._tag).toBe("Exited") expect(final._tag === "Exited" && final.code).toBe(3) const records = readFileSync(logPath, "utf8") .trimEnd() .split("\n") .map((line) => { const parsed = parseLogLine(line) if (!parsed.ok) throw new Error(parsed.error) return `${parsed.value.stream}:${parsed.value.line}` }) .sort() expect(records).toEqual(["stderr:err", "stdout:out", "stdout:partial"])})
test("another process can ask a running monitor for the state over the Unix socket", async () => { const { monitor, socketPath } = await start(["sh", "-c", "exec sleep 30"]) const whileRunning = await askState(socketPath) expect(whileRunning).toEqual({ ok: true, value: monitor.state() }) expect(whileRunning.ok && whileRunning.value._tag).toBe("Running")
monitor.kill("SIGTERM") const final = await monitor.done expect(final._tag === "Exited" && final.code).toBe(143) expect(await askState(socketPath)).toEqual({ ok: true, value: final })})
test("a program that does not exist is an Exited 127 container, not a crash", async () => { const { monitor, socketPath } = await start(["tsbox-no-such-program"]) expect(await monitor.done).toEqual(monitor.state()) const reply = await askState(socketPath) expect(reply.ok && reply.value._tag === "Exited" && reply.value.code).toBe(127)})
test("asking a monitor that is not there is an error value", async () => { const dir = mkdtempSync(join(tmpdir(), "tsbox-")) dirs.push(dir) const reply = await askState(join(dir, "missing.sock")) expect(reply.ok).toBe(false)})
test("a socket path that is too long is refused before anything starts", async () => { const long = join(tmpdir(), "x".repeat(120), "m.sock") const started = await startMonitor({ cmd: ["echo"], logPath: "/dev/null", socketPath: long, now: () => 0 }) expect(started.ok).toBe(false)})Run it for real
Section titled “Run it for real”Unix sockets and setsid work on macOS and Linux alike, so you can try the monitor on your own machine. Run it from
the folder with main.ts and monitor.ts:
bun -e 'const { startMonitor } = await import("./monitor.ts"); const m = await startMonitor({ cmd: ["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done"], logPath: "/tmp/web.log", socketPath: "/tmp/web.sock", now: Date.now }); if (m.ok) { await m.value.done; m.value.close() }'In a second terminal, while it runs, cat /tmp/web.log shows the ticks arriving, and
bun -e 'const { askState } = await import("./monitor.ts"); console.log(await askState("/tmp/web.sock"))' prints the
Running state. Cleaning up is on you: rm /tmp/web.sock /tmp/web.log.
- tsbox has no daemon. A monitor process per container owns the child, the log and a Unix socket, and outlives the CLI (
detached: true,unref(), stdio"ignore"). - State changes go through one pure
transition. Illegal moves are errors,Exitedis final, and time is passed in. - Pipe chunks are not lines: keep a carry, flush it at the end, and log each line with its time and stream.
- A Unix socket path is limited to about 104 bytes. Check it up front, and decode what comes over the socket as
unknown. Bun.listen({ unix })andBun.connect({ unix })give youSockethandlers. Stale socket files and a missing program are normal cases to handle, not crashes.
Further reading
Section titled “Further reading”- unix(7): Unix domain sockets and their path length limit.
- Spawn (Bun): watching a child process from Bun.