Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

durability.ts

164 lines6.4 KB

1/**
2 * The portable seams over a {@link RunEventLog} — what makes the coordinator a
3 * platform *binding* of core's run driver rather than a parallel architecture.
4 *
5 * Core's `pipeToRunLog` / `RunController` (`@tanstack/ai-sandbox`) drive a run
6 * through two seams: a `RunStore` for the lifecycle record and a per-run
7 * `StreamDurability` for the event log. On Cloudflare both are backed by the
8 * SAME Durable Object storage — the run log's `rec:` record is core's
9 * {@link RunLogRecord} and its `evt:` rows are the chunks — so this module is
10 * two thin views over one log:
11 *
12 * - {@link runLogStore} — the log as a `RunStore`;
13 * - {@link runLogStream} — one run of the log as a `StreamDurability`.
14 *
15 * The fusion has one consequence worth naming: the record's `status` and the
16 * log's terminal state are the same field. Core's driver terminalizes through
17 * `runs.update(...)` and then calls `durability.close()`; on this backend the
18 * `update` already ended the log (and woke its readers — see
19 * {@link RunEventLog.update}), so `close()` is normally a no-op. It still maps
20 * to `finish('completed')` for the one path where it isn't: an `update` that
21 * failed would otherwise leave readers parked on a log nothing will ever end.
22 */
23import type { RunStore, StreamChunk, StreamDurability } from '@tanstack/ai'
24import type { RunEventLog } from './run-log'
25​
26/**
27 * Expose a {@link RunEventLog} as core's `RunStore`, for the `runs` half of
28 * `RunDeps`. A pure rename layer — the invariants (idempotent `createOrResume`,
29 * no-op `update` on an unknown run) are the log's own.
30 */
31export function runLogStore(log: RunEventLog): RunStore {
32 return {
33 // `status` is accepted but ignored: a log run always opens `'running'`,
34 // which is also `createOrResume`'s documented default, and core's driver
35 // never passes anything else.
36 createOrResume: ({ runId, threadId, startedAt }) =>
37 log.open({ runId, threadId, startedAt }),
38 update: (runId, patch) => log.update(runId, patch),
39 get: (runId) => log.get(runId),
40 findActiveRun: async (threadId) => {
41 let active = null
42 for (const record of await log.list()) {
43 if (record.threadId !== threadId || record.status !== 'running') {
44 continue
45 }
46 if (active === null || record.startedAt > active.startedAt) {
47 active = record
48 }
49 }
50 return active
51 },
52 }
54​
55const RUN_LOG_OFFSET_PREFIX = 'cfrunlog:v1:'
56​
57function encodeOffset(runId: string, seq: number): string {
58 return `${RUN_LOG_OFFSET_PREFIX}${encodeURIComponent(runId)}:${seq}`
60​
61function decodeOffset(offset: string): { runId: string; seq: number } {
62 if (!offset.startsWith(RUN_LOG_OFFSET_PREFIX)) {
63 throw new Error(`Invalid run-log stream offset: ${offset}`)
64 }
65 const encoded = offset.slice(RUN_LOG_OFFSET_PREFIX.length)
66 const separator = encoded.lastIndexOf(':')
67 if (separator === -1) {
68 throw new Error(`Invalid run-log stream offset: ${offset}`)
69 }
70 const runId = decodeURIComponent(encoded.slice(0, separator))
71 const seq = Number(encoded.slice(separator + 1))
72 if (!Number.isSafeInteger(seq) || seq < 0) {
73 throw new Error(`Invalid run-log stream offset: ${offset}`)
74 }
75 return { runId, seq }
77​
78/** Construction input for {@link runLogStream}. */
79export interface RunLogStreamInit {
80 /** The run this durability adapter attaches to. */
81 runId: string
82 /**
83 * Resume offset captured by the consumer (`resumeFrom()` returns it).
84 * Defaults to `null` (a producer / from-start reader).
85 */
86 offset?: string | null
88​
89/**
90 * Expose one run of a {@link RunEventLog} as core's `StreamDurability`, for the
91 * `durability` half of `RunDeps`: `(runId) => runLogStream(log, { runId })`.
92 *
93 * The run must already exist — core's driver guarantees it (`createOrResume`
94 * runs before the first `append`), and a standalone consumer opens it first.
95 * `append` and `read` on an unknown run reject, per the log's own contract;
96 * `snapshot` resolves `[]`, per `StreamDurability`'s.
97 *
98 * Offsets encode the log's monotonic `seq` (versioned, run-scoped, opaque to
99 * callers). The `'-1'` (from-start) and `'now'` (tail-only) read sentinels
100 * every shipped backend honors are supported.
101 */
102export function runLogStream(
103 log: RunEventLog,
104 init: RunLogStreamInit,
105): StreamDurability {
106 const { runId } = init
107 const resumeOffset = init.offset ?? null
108​
109 const seqAfter = async (offset: string): Promise<number> => {
110 if (offset === '-1') return -1
111 if (offset === 'now') return (await log.get(runId))?.lastSeq ?? -1
112 const decoded = decodeOffset(offset)
113 if (decoded.runId !== runId) {
114 throw new Error(
115 `Run-log stream offset belongs to run ${JSON.stringify(decoded.runId)}, not ${JSON.stringify(runId)}`,
116 )
117 }
118 return decoded.seq
119 }
120​
121 return {
122 resumeFrom: () => resumeOffset,
123 append: async (chunks) => {
124 const offsets: Array<string> = []
125 for (const chunk of chunks) {
126 offsets.push(encodeOffset(runId, await log.append(runId, chunk)))
127 }
128 return offsets
129 },
130 read: async function* (offset, signal) {
131 const fromSeq = await seqAfter(offset)
132 const events = log.read(runId, {
133 fromSeq,
134 ...(signal !== undefined ? { signal } : {}),
135 })
136 for await (const event of events) {
137 yield { offset: encodeOffset(runId, event.seq), chunk: event.chunk }
138 }
139 },
140 // See the module header: normally a no-op (the driver's terminal
141 // `runs.update` already ended the shared record); `'completed'` lands only
142 // when that update failed, where unwedging parked readers beats leaving
143 // them on a log nothing will ever end.
144 close: () => log.finish(runId, 'completed'),
145 snapshot: async () => {
146 const record = await log.get(runId)
147 // Unknown run resolves to [] — the contract forbids reusing the
148 // unknown-run failure path a from-start `read` join takes.
149 if (record === null || record.lastSeq < 0) return []
150 const lastSeq = record.lastSeq
151 const entries: Array<{ offset: string; chunk: StreamChunk }> = []
152 for await (const event of log.read(runId, { fromSeq: -1 })) {
153 entries.push({
154 offset: encodeOffset(runId, event.seq),
155 chunk: event.chunk,
156 })
157 // Stop at the lastSeq captured BEFORE the read: `read` live-tails an
158 // open log, and a snapshot must return a point-in-time view instead.
159 if (event.seq >= lastSeq) break
160 }
161 return entries
162 },
163 }