Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import type { Pool, PoolClient, QueryResultRow } from 'pg'
3import { StorageCompatibilityError, StreamError } from './errors.js'
4import { advanceOffset, parseOffset, ZERO_OFFSET } from './offset.js'
5import { formatPayloads, mediaType, preparePayload } from './payload.js'
6import { validateSchema } from './path.js'
7import { InstallationGuard } from './installation.js'
8import type { TransactionOptions } from './transaction.js'
9import { MIGRATION_IDS } from './migrations.js'
10import { ChunkManager } from './storage.js'
11import type { StorageOptions, StoredFrame } from './storage.js'
12import type { ChunkFrame } from './chunk-codec.js'
13import { assertReplayDeadline, ReplayPins } from './replay.js'
14import type { ReplayLease } from './replay.js'
15import { ReclamationManager, emptyReclamation } from './reclamation.js'
16import type { ReclamationResult } from './reclamation.js'
17
18export interface Producer {
19 readonly id: string
20 readonly epoch: number
21 readonly seq: number
22}
23
24export interface StreamMetadata extends QueryResultRow {
25 id: string
26 tenant_id: string
27 path: string
28 content_type: string
29 tail_offset: string
30 change_version: string
31 closed: boolean
32 closed_by: Producer | null
33 last_seq: string | null
34 ttl_seconds: number | null
35 expires_at: Date | null
36 accessed_at: Date
37 valid_for_ms?: string | null
38 deleted_at: Date | null
39 source_id: string | null
40 fork_offset: string | null
41 fork_sub_offset: string
42 fork_depth: number
43 edge_active: boolean
44 ref_count: number
45}
46
47interface LockedStream extends StreamMetadata { expired: boolean }
48export interface CreateOptions {
49 readonly contentType: string
50 readonly body: Uint8Array
51 readonly closed: boolean
52 readonly ttlSeconds?: number
53 readonly expiresAt?: Date
54}
55
56export interface AppendOptions {
57 readonly body: Uint8Array
58 readonly contentType: string | null
59 readonly close: boolean
60 readonly producer?: Producer
61 readonly sequence?: string
62}
63export interface ForkOptions extends Omit<CreateOptions, 'contentType'> {
64 readonly contentType?: string
65 readonly sourcePath: string
66 readonly offset?: string
67 readonly subOffset: number
68}
69
70export interface AppendResult {
71 readonly stream: StreamMetadata
72 readonly status: 200 | 204
73 readonly producer?: { epoch: number; seq: number }
74}
75export interface ReadResult {
76 readonly stream: StreamMetadata
77 readonly body: Buffer
78 readonly next: string
79 readonly upToDate: boolean
80 readonly hasData: boolean
81 readonly validatedAt: number
82 readonly validUntil: number
83}
84interface StoreOptions {
85 readonly maxStoredBytes?: number | undefined
86 readonly maxPageBytes?: number | undefined
87 readonly maxPageFrames?: number | undefined
88 readonly replayTimeoutMs?: number | undefined
89 readonly storage?: StorageOptions | undefined
90 readonly environmentId?: string | undefined
91 readonly timeouts?: Pick<TransactionOptions, 'timeoutMs' | 'lockTimeoutMs'> | undefined
92}
93interface PinnedFrames { readonly frames: readonly StoredFrame[]; readonly lease: ReplayLease | undefined; readonly deadline: number }
94interface ReplayPlan extends Omit<ReadResult, 'body'>, PinnedFrames {}
95
96/** Transactional stream state and bounded replay planning. */
97export class PostgresStreamStore {
98 readonly schema: string
99 readonly guard: InstallationGuard
100 private ready: Promise<void> | undefined
101 private readonly chunks: ChunkManager | undefined
102 private readonly maxStoredBytes: number
103 private readonly maxPageBytes: number
104 private readonly maxPageFrames: number
105 private readonly replayTimeout: number
106 private readonly pins: ReplayPins
107 private readonly reclamation: ReclamationManager
108 private layout: 5 | 6 | undefined
109 get schemaVersion(): 5 | 6 {
110 if (this.layout === undefined) throw new StorageCompatibilityError('Initialize the runtime before reading schema capabilities')
111 return this.layout
112 }
113
114 constructor(
115 private readonly pool: Pool,
116 schema: string,
117 options: StoreOptions = {},
118 ) {
119 const { maxStoredBytes = 1024 * 1024, maxPageBytes = 2 * 1024 * 1024, maxPageFrames = 128, replayTimeoutMs = 60_000, storage, environmentId, timeouts } = options
120 this.maxStoredBytes = maxStoredBytes
121 this.maxPageBytes = maxPageBytes
122 this.maxPageFrames = maxPageFrames
123 this.schema = validateSchema(schema)
124 this.guard = new InstallationGuard(pool, schema, environmentId, timeouts)
125 this.pins = new ReplayPins(this.schema, this.guard)
126 this.reclamation = new ReclamationManager(this.schema, this.guard, storage?.objects)
127 this.replayTimeout = replayTimeoutMs
128 this.chunks = storage ? new ChunkManager(pool, schema, storage, this.guard) : undefined
129 if (!Number.isSafeInteger(maxStoredBytes) || maxStoredBytes < 1 || maxStoredBytes > 16 * 1024 * 1024
130 || !Number.isSafeInteger(maxPageBytes) || maxPageBytes < maxStoredBytes + 2 || maxPageBytes > 64 * 1024 * 1024
131 || !Number.isSafeInteger(maxPageFrames) || maxPageFrames < 1 || maxPageFrames > 1024
132 || !Number.isSafeInteger(replayTimeoutMs) || replayTimeoutMs < 1 || replayTimeoutMs > 300_000) {
133 throw new RangeError('Invalid payload/page limits')
134 }
135 }
136
137 async assertReady(): Promise<void> {
138 this.ready ??= this.pool.query<{ storage_version: number; storage_identity: string | null }>(`SELECT storage_version, storage_identity FROM ${this.schema}.installation`)
139 .then(async (result) => {
140 if (result.rows.length !== 1 || result.rows[0]!.storage_version !== 1) throw new StorageCompatibilityError('Unsupported storage version')
141 const migrations = await this.pool.query<{ id: string }>(`SELECT id FROM ${this.schema}.migrations ORDER BY id`)
142 const history = JSON.stringify(migrations.rows.map((row) => row.id))
143 const legacy = history === JSON.stringify(MIGRATION_IDS.slice(0, 5))
144 if (!legacy && history !== JSON.stringify(MIGRATION_IDS)) throw new StorageCompatibilityError('Unsupported database migrations')
145 this.pins.enabled = !legacy
146 this.layout = legacy ? 5 : 6
147 if (this.chunks) this.chunks.reclamation = !legacy
148 if (result.rows[0]!.storage_identity !== null && !this.chunks) throw new StorageCompatibilityError('This installation requires its configured object storage')
149 await this.chunks?.assertBinding()
150 if (!legacy) await this.reclamation.assertReady()
151 })
152 .catch((error: unknown) => { this.ready = undefined; this.layout = undefined; throw error })
153 await this.ready
154 }
155
156 transaction<T>(options: TransactionOptions, work: (client: PoolClient) => Promise<T>): Promise<T> {
157 return this.guard.run(options, work)
158 }
159
160 private async lock(client: PoolClient, tenant: string, path: string): Promise<LockedStream | undefined> {
161 const claimed = await client.query<{ active_stream_id: string | null }>(`SELECT active_stream_id FROM ${this.schema}.paths
162 WHERE tenant_id = $1 AND path = $2 FOR UPDATE`, [tenant, path])
163 const id = claimed.rows[0]?.active_stream_id
164 if (!id) return undefined
165 const result = await client.query<LockedStream>(`SELECT s.*,
166 CASE WHEN s.expires_at IS NOT NULL OR s.ttl_seconds IS NOT NULL THEN
167 EXTRACT(epoch FROM (COALESCE(s.expires_at, s.accessed_at + s.ttl_seconds * interval '1 second') - clock_timestamp())) * 1000 END AS valid_for_ms,
168 COALESCE(s.expires_at <= clock_timestamp() OR
169 s.accessed_at + s.ttl_seconds * interval '1 second' <= clock_timestamp(), false) AS expired
170 FROM ${this.schema}.streams s
171 WHERE s.id = $1 FOR NO KEY UPDATE`, [id])
172 return result.rows[0]
173 }
174
175 private async change(client: PoolClient, stream: StreamMetadata, before: string, kind: string): Promise<void> {
176 await client.query(`INSERT INTO ${this.schema}.stream_changes
177 (stream_id, version, before_offset, after_offset, kind) VALUES ($1, $2, $3, $4, $5)`,
178 [stream.id, stream.change_version, before, stream.tail_offset, kind])
179 }
180
181 private async retire(client: PoolClient, stream: StreamMetadata, kind: 'deleted' | 'expired'): Promise<void> {
182 const result = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams
183 SET deleted_at = clock_timestamp(), change_version = change_version + 1, cleanup_pending = ref_count > 0 WHERE id = $1 RETURNING *`, [stream.id])
184 if (stream.ttl_seconds !== null || stream.expires_at !== null) await client.query(`DELETE FROM ${this.schema}.stream_expirations WHERE stream_id = $1`, [stream.id])
185 if (!stream.ref_count) await this.detach(client, result.rows[0]!)
186 await this.change(client, result.rows[0]!, stream.tail_offset, kind)
187 }
188
189 /** Own path/stream are locked. Ancestor updates only follow the acyclic edge;
190 * ancestor path cleanup is a separate transaction, never a reverse path lock. */
191 private async detach(client: PoolClient, stream: StreamMetadata): Promise<void> {
192 await client.query(`UPDATE ${this.schema}.paths SET active_stream_id = NULL WHERE tenant_id = $1 AND path = $2 AND active_stream_id = $3`, [stream.tenant_id, stream.path, stream.id])
193 await client.query(`UPDATE ${this.schema}.streams SET cleanup_pending = false, edge_active = false WHERE id = $1`, [stream.id])
194 if (stream.source_id && stream.edge_active) {
195 const parent = await client.query(`UPDATE ${this.schema}.streams SET ref_count = ref_count - 1 WHERE id = $1 AND ref_count > 0 RETURNING id`, [stream.source_id])
196 if (!parent.rowCount) throw new Error('Fork reference invariant failed')
197 }
198 }
199
200 private async scheduleExpiry(client: PoolClient, stream: StreamMetadata): Promise<void> {
201 if (stream.ttl_seconds === null && stream.expires_at === null) return
202 await client.query(`INSERT INTO ${this.schema}.stream_expirations (stream_id, due_at)
203 SELECT id, COALESCE(expires_at, accessed_at + ttl_seconds * interval '1 second') FROM ${this.schema}.streams WHERE id = $1
204 ON CONFLICT (stream_id) DO UPDATE SET due_at = EXCLUDED.due_at`, [stream.id])
205 }
206
207 private async withStream<T>(tenant: string, path: string, work: (client: PoolClient, stream: LockedStream) => Promise<T>): Promise<T> {
208 await this.assertReady()
209 const outcome = await this.transaction({}, async (client) => {
210 const stream = await this.lock(client, tenant, path)
211 if (!stream) return { found: false, status: 404 } as const
212 if (stream.deleted_at) return { found: false, status: 410 } as const
213 if (stream.expired) {
214 await this.retire(client, stream, 'expired')
215 return { found: false, status: stream.ref_count ? 410 : 404 } as const
216 }
217 return { found: true, value: await work(client, stream) } as const
218 })
219 // Missing/expired is reported after committing an expiry transition.
220 if (!outcome.found) throw new StreamError(outcome.status, outcome.status === 410 ? 'STREAM_GONE' : 'STREAM_NOT_FOUND', 'Stream is unavailable')
221 return outcome.value
222 }
223
224 async create(tenant: string, path: string, options: CreateOptions): Promise<{ stream: StreamMetadata; created: boolean }> {
225 await this.assertReady()
226 const payload = preparePayload(options.body, options.contentType, true)
227 this.checkPayload(payload.bytes)
228 const outcome = await this.transaction({}, async (client) => {
229 await client.query(`INSERT INTO ${this.schema}.paths (tenant_id, path) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [tenant, path])
230 const namespace = await client.query(`SELECT path FROM ${this.schema}.paths WHERE tenant_id = $1 AND path = $2 FOR UPDATE`, [tenant, path])
231 if (namespace.rowCount !== 1) throw new StreamError(503, 'NAMESPACE_RETRY', 'Namespace changed; retry creation', { 'Retry-After': '1' })
232 let existing = await this.lock(client, tenant, path)
233 if (existing?.deleted_at) throw new StreamError(409, 'STREAM_RETAINED', 'Stream has active forks')
234 if (existing?.expired) {
235 await this.retire(client, existing, 'expired')
236 if (existing.ref_count) return { error: new StreamError(409, 'STREAM_RETAINED', 'Stream has active forks') } as const
237 existing = undefined
238 }
239 if (existing) {
240 if (existing.source_id !== null || mediaType(existing.content_type) !== mediaType(options.contentType) || existing.closed !== options.closed
241 || existing.ttl_seconds !== (options.ttlSeconds ?? null)
242 || (existing.expires_at?.toISOString() ?? null) !== (options.expiresAt?.toISOString() ?? null)) {
243 throw new StreamError(409, 'CONFIGURATION_MISMATCH', 'Stream configuration differs')
244 }
245 return { stream: existing, created: false }
246 }
247 const id = randomUUID()
248 const tail = payload.bytes.length ? advanceOffset(ZERO_OFFSET, payload.bytes.length) : ZERO_OFFSET
249 const result = await client.query<StreamMetadata>(`INSERT INTO ${this.schema}.streams
250 (id, tenant_id, path, content_type, tail_offset, change_version, closed, ttl_seconds, expires_at)
251 VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8) RETURNING *`,
252 [id, tenant, path, options.contentType, tail, options.closed, options.ttlSeconds ?? null, options.expiresAt ?? null])
253 const stream = result.rows[0]!
254 await client.query(`UPDATE ${this.schema}.paths SET active_stream_id = $3 WHERE tenant_id = $1 AND path = $2`, [tenant, path, id])
255 if (payload.bytes.length) await this.insertAppend(client, id, ZERO_OFFSET, tail, payload.bytes, payload.messageEnds)
256 await this.change(client, stream, ZERO_OFFSET, 'created')
257 await this.scheduleExpiry(client, stream)
258 await this.chunks?.freeze(client, id)
259 return { stream, created: true }
260 })
261 if ('error' in outcome) throw outcome.error
262 return outcome
263 }
264
265 private checkPayload(bytes: Uint8Array): void {
266 if (bytes.byteLength > this.maxStoredBytes) throw new StreamError(413, 'PAYLOAD_TOO_LARGE', 'Stored append exceeds configured limit')
267 }
268
269 /** Each ancestor contributes only its fixed inherited range. No path lookup
270 * or current source lifecycle state can change an existing fork's view. */
271 private lineage(): string {
272 return `WITH RECURSIVE lineage AS (
273 SELECT id, tail_offset AS cap, source_id, fork_offset, 0 AS depth FROM ${this.schema}.streams WHERE id = $1
274 UNION ALL
275 SELECT p.id, LEAST(l.cap, l.fork_offset), p.source_id, p.fork_offset, l.depth + 1
276 FROM lineage l JOIN ${this.schema}.streams p ON p.id = l.source_id WHERE l.depth < 128
277 )`
278 }
279
280 private async boundary(client: PoolClient, stream: StreamMetadata, offset: string): Promise<void> {
281 if (offset > stream.tail_offset) throw new StreamError(400, 'OFFSET_BEYOND_TAIL', 'Offset exceeds stream tail')
282 if (offset === ZERO_OFFSET || offset === stream.tail_offset) return
283 const result = await client.query(`${this.lineage()}
284 SELECT 1 FROM lineage l JOIN ${this.schema}.appends a ON a.stream_id = l.id
285 WHERE a.end_offset = $2 AND a.end_offset <= l.cap LIMIT 1`, [stream.id, offset])
286 if (!result.rowCount) throw new StreamError(400, 'OFFSET_NOT_BOUNDARY', 'Offset is not a returned boundary')
287 }
288
289 private async framePlan(client: PoolClient, id: string, start: string, limit = this.maxPageFrames, bytes = this.maxPageBytes - 2): Promise<readonly StoredFrame[]> {
290 const result = await client.query<StoredFrame>(`${this.lineage()}, candidates AS (
291 SELECT f.* FROM lineage l CROSS JOIN LATERAL (
292 SELECT stream_id, end_offset, payload_bytes FROM ${this.schema}.appends
293 WHERE stream_id = l.id AND end_offset > $2 AND end_offset <= l.cap ORDER BY end_offset LIMIT $4
294 ) f ORDER BY end_offset LIMIT $4
295 ), bounded AS (SELECT stream_id, end_offset, sum(payload_bytes) OVER (ORDER BY end_offset) AS bytes FROM candidates)
296 SELECT a.stream_id, a.start_offset, a.end_offset, a.payload, a.payload_bytes, a.message_ends, a.chunk_id, c.object_key, c.sha256, c.encoded_bytes
297 FROM bounded b JOIN ${this.schema}.appends a ON a.stream_id = b.stream_id AND a.end_offset = b.end_offset
298 LEFT JOIN ${this.schema}.chunks c ON c.id = a.chunk_id WHERE b.bytes <= $3 ORDER BY a.end_offset`, [id, start, bytes, limit])
299 return result.rows
300 }
301
302 private async materialize(plan: PinnedFrames): Promise<readonly ChunkFrame[]> {
303 const { frames, deadline, lease } = plan
304 try {
305 assertReplayDeadline(deadline)
306 const result = this.chunks ? await this.chunks.materialize(frames, deadline) : frames.map((frame) => {
307 if (!frame.payload) throw new StorageCompatibilityError('Sealed replay requires object storage')
308 return { start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }
309 })
310 await this.pins.validate(lease)
311 assertReplayDeadline(deadline)
312 return result
313 } finally { await this.pins.release(lease) }
314 }
315
316 async createFork(tenant: string, path: string, options: ForkOptions): Promise<{ stream: StreamMetadata; created: boolean }> {
317 const deadline = performance.now() + this.replayTimeout
318 await this.assertReady()
319 if (options.offset !== undefined) parseOffset(options.offset)
320 if (!Number.isSafeInteger(options.subOffset) || options.subOffset < 0) throw new StreamError(400, 'INVALID_SUB_OFFSET', 'Invalid sub-offset')
321 type Prefix = { sourceId: string; anchor: string; frame: ChunkFrame }
322 type Outcome = { stream: StreamMetadata; created: boolean } | { error: StreamError }
323 | { prepare: PinnedFrames & { sourceId: string; anchor: string; contentType: string } }
324 const execute = (prefix?: Prefix): Promise<Outcome> => this.transaction({}, async (client) => {
325 // Lock every namespace claim before locking any stream row. Inserts obey
326 // the same byte ordering, including when both paths are initially absent.
327 const paths = [...new Set([path, options.sourcePath])].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))
328 for (const claim of paths) await client.query(`INSERT INTO ${this.schema}.paths (tenant_id, path) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [tenant, claim])
329 const namespaces = await client.query(`SELECT path FROM ${this.schema}.paths WHERE tenant_id = $1 AND path = ANY($2::text[]) ORDER BY path FOR UPDATE`, [tenant, paths])
330 if (namespaces.rowCount !== paths.length) throw new StreamError(503, 'NAMESPACE_RETRY', 'Namespace changed; retry fork creation', { 'Retry-After': '1' })
331 let existing = await this.lock(client, tenant, path)
332 if (existing?.deleted_at) throw new StreamError(409, 'STREAM_RETAINED', 'Target stream has active forks')
333 if (existing?.expired) {
334 await this.retire(client, existing, 'expired')
335 if (existing.ref_count) return { error: new StreamError(409, 'STREAM_RETAINED', 'Target stream has active forks') }
336 existing = undefined
337 }
338 const source = await this.lock(client, tenant, options.sourcePath)
339 if (existing) {
340 const ttl = options.ttlSeconds ?? (options.expiresAt ? null : existing.ttl_seconds)
341 const expiry = options.expiresAt ?? (options.ttlSeconds !== undefined ? null : existing.expires_at)
342 if (!source || existing.source_id !== source.id || existing.closed !== options.closed
343 || mediaType(existing.content_type) !== mediaType(options.contentType ?? existing.content_type)
344 || existing.ttl_seconds !== ttl || (existing.expires_at?.toISOString() ?? null) !== (expiry?.toISOString() ?? null)
345 || (options.offset !== undefined && existing.fork_offset !== options.offset) || BigInt(existing.fork_sub_offset) !== BigInt(options.subOffset)) {
346 throw new StreamError(409, 'CONFIGURATION_MISMATCH', 'Stream configuration differs')
347 }
348 return { stream: existing, created: false }
349 }
350 if (!source) throw new StreamError(404, 'SOURCE_NOT_FOUND', 'Source stream not found')
351 if (source.deleted_at) throw new StreamError(409, 'SOURCE_RETAINED', 'Source stream is deleted')
352 if (source.expired) {
353 await this.retire(client, source, 'expired')
354 return { error: new StreamError(source.ref_count ? 409 : 404, 'SOURCE_EXPIRED', 'Source stream expired') }
355 }
356 if (path === options.sourcePath) throw new StreamError(409, 'SELF_FORK', 'A stream cannot fork itself')
357 if (source.fork_depth >= 128) throw new StreamError(413, 'FORK_DEPTH', 'Maximum fork depth reached')
358 if (options.contentType && mediaType(options.contentType) !== mediaType(source.content_type)) throw new StreamError(409, 'CONTENT_TYPE_MISMATCH', 'Fork content type must match its source')
359 const anchor = options.offset ?? source.tail_offset
360 await this.boundary(client, source, anchor)
361 const payload = preparePayload(options.body, source.content_type, true)
362 this.checkPayload(payload.bytes)
363 if (prefix && (prefix.sourceId !== source.id || prefix.anchor !== anchor)) throw new StreamError(409, 'SOURCE_CHANGED', 'Source generation changed; retry fork creation')
364 if (options.subOffset && !prefix) {
365 const frames = await this.framePlan(client, source.id, anchor, 1, this.maxStoredBytes)
366 if (!frames[0] || frames[0].start_offset !== anchor) throw new StreamError(400, 'SUB_OFFSET_BEYOND_TAIL', 'Sub-offset has no following source frame')
367 assertReplayDeadline(deadline)
368 const lease = await this.pins.acquire(client, frames)
369 return { prepare: { sourceId: source.id, anchor, contentType: source.content_type, frames, lease, deadline } }
370 }
371 const ttl = options.ttlSeconds ?? (options.expiresAt ? null : source.ttl_seconds)
372 const expiry = options.expiresAt ?? (options.ttlSeconds !== undefined ? null : source.expires_at)
373 const id = randomUUID()
374 await client.query(`INSERT INTO ${this.schema}.streams (id, tenant_id, path, content_type, tail_offset, change_version, closed, ttl_seconds, expires_at, source_id, fork_offset, fork_sub_offset, fork_depth, edge_active)
375 VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8, $9, $5, $10, $11, true)`,
376 [id, tenant, path, source.content_type, anchor, options.closed, ttl, expiry, source.id, options.subOffset, source.fork_depth + 1])
377 let next = anchor
378 for (const frame of [...(prefix ? [prefix.frame] : []), ...(payload.bytes.length ? [{ payload: payload.bytes, messageEnds: payload.messageEnds }] : [])]) {
379 const end = advanceOffset(next, frame.payload.length)
380 await this.insertAppend(client, id, next, end, frame.payload, frame.messageEnds)
381 next = end
382 }
383 const updated = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2 WHERE id = $1 RETURNING *`, [id, next])
384 await client.query(`UPDATE ${this.schema}.paths SET active_stream_id = $3 WHERE tenant_id = $1 AND path = $2`, [tenant, path, id])
385 await client.query(`UPDATE ${this.schema}.streams SET ref_count = ref_count + 1 WHERE id = $1`, [source.id])
386 const stream = updated.rows[0]!
387 await this.change(client, stream, ZERO_OFFSET, 'created')
388 await this.scheduleExpiry(client, stream)
389 await this.chunks?.freeze(client, id)
390 return { stream, created: true }
391 })
392 let outcome = await execute()
393 if ('prepare' in outcome) {
394 const plan = outcome.prepare
395 const frame = (await this.materialize(plan))[0]!
396 const json = mediaType(plan.contentType) === 'application/json'
397 const units = json ? frame.messageEnds?.length ?? 0 : frame.payload.length
398 if (options.subOffset > units) throw new StreamError(400, 'SUB_OFFSET_OVERSHOOT', 'Sub-offset exceeds the next source frame')
399 const length = json ? frame.messageEnds![options.subOffset - 1]! : options.subOffset
400 const prefix = { ...frame, payload: Buffer.from(frame.payload.subarray(0, length)), messageEnds: json ? frame.messageEnds!.slice(0, options.subOffset) : null }
401 outcome = await execute({ sourceId: plan.sourceId, anchor: plan.anchor, frame: prefix })
402 }
403 if ('error' in outcome) throw outcome.error
404 if ('prepare' in outcome) throw new Error('Fork prefix was not resolved')
405 return outcome
406 }
407
408 private async insertAppend(client: PoolClient, id: string, start: string, end: string, bytes: Uint8Array, ends: readonly number[] | null): Promise<void> {
409 await client.query(`INSERT INTO ${this.schema}.appends (stream_id, start_offset, end_offset, payload, message_ends, payload_bytes)
410 VALUES ($1, $2, $3, $4, $5, $6)`, [id, start, end, bytes, ends, bytes.byteLength])
411 await client.query(`UPDATE ${this.schema}.streams SET hot_bytes = hot_bytes + $2, hot_frames = hot_frames + 1,
412 seal_after = CASE WHEN hot_frames = 0 THEN clock_timestamp() ELSE seal_after END WHERE id = $1`, [id, bytes.byteLength])
413 }
414
415 async append(tenant: string, path: string, options: AppendOptions): Promise<AppendResult> {
416 return this.withStream(tenant, path, async (client, stream) => {
417 const producer = options.producer
418 if (stream.closed) {
419 const duplicate = producer && stream.closed_by?.id === producer.id && stream.closed_by.epoch === producer.epoch && stream.closed_by.seq === producer.seq
420 if (duplicate || (!producer && options.close && options.body.length === 0)) {
421 return { stream, status: 204, ...(producer ? { producer: { epoch: producer.epoch, seq: producer.seq } } : {}) }
422 }
423 throw new StreamError(409, 'STREAM_CLOSED', 'Stream is closed', { 'Stream-Closed': 'true', 'Stream-Next-Offset': stream.tail_offset })
424 }
425 if (options.body.length && (!options.contentType || mediaType(options.contentType) !== mediaType(stream.content_type))) {
426 throw new StreamError(options.contentType ? 409 : 400, 'CONTENT_TYPE_MISMATCH', 'Content-Type must match the stream')
427 }
428 if (producer) {
429 const result = await client.query<{ epoch: string; last_seq: string }>(`SELECT epoch, last_seq FROM ${this.schema}.producers WHERE stream_id = $1 AND producer_id = $2`, [stream.id, producer.id])
430 const prior = result.rows[0]
431 const epoch = prior ? Number(prior.epoch) : -1
432 const last = prior ? Number(prior.last_seq) : -1
433 if (producer.epoch < epoch) throw new StreamError(403, 'STALE_PRODUCER', 'Producer epoch is fenced', { 'Producer-Epoch': String(epoch) })
434 if (producer.epoch === epoch && producer.seq <= last) return { stream, status: 204, producer: { epoch, seq: last } }
435 const expected = producer.epoch === epoch ? last + 1 : 0
436 if (producer.seq !== expected) {
437 if (prior && producer.epoch > epoch) throw new StreamError(400, 'NEW_EPOCH_SEQUENCE', 'A new epoch must start at sequence zero')
438 throw new StreamError(409, 'PRODUCER_SEQUENCE_GAP', 'Producer sequence gap', { 'Producer-Expected-Seq': String(expected), 'Producer-Received-Seq': String(producer.seq) })
439 }
440 }
441 if (options.sequence !== undefined && stream.last_seq !== null && Buffer.compare(Buffer.from(options.sequence), Buffer.from(stream.last_seq)) <= 0) {
442 throw new StreamError(409, 'SEQUENCE_REGRESSION', 'Stream-Seq must increase')
443 }
444 if (!options.body.length && !options.close) throw new StreamError(400, 'EMPTY_APPEND', 'Append body must not be empty')
445 const payload = options.body.length ? preparePayload(options.body, stream.content_type) : { bytes: Buffer.alloc(0), messageEnds: null }
446 this.checkPayload(payload.bytes)
447 const next = payload.bytes.length ? advanceOffset(stream.tail_offset, payload.bytes.length) : stream.tail_offset
448 if (payload.bytes.length) await this.insertAppend(client, stream.id, stream.tail_offset, next, payload.bytes, payload.messageEnds)
449 if (producer) await client.query(`INSERT INTO ${this.schema}.producers (stream_id, producer_id, epoch, last_seq)
450 VALUES ($1, $2, $3, $4) ON CONFLICT (stream_id, producer_id) DO UPDATE SET epoch = EXCLUDED.epoch, last_seq = EXCLUDED.last_seq`,
451 [stream.id, producer.id, producer.epoch, producer.seq])
452 const updated = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2,
453 change_version = change_version + 1, closed = $3, closed_by = $4, last_seq = COALESCE($5, last_seq), accessed_at = clock_timestamp()
454 WHERE id = $1 RETURNING *`, [stream.id, next, options.close, options.close && producer ? producer : null, options.sequence ?? null])
455 const value = updated.rows[0]!
456 await this.change(client, value, stream.tail_offset, options.close ? 'closed' : 'appended')
457 if (value.ttl_seconds !== null) await this.scheduleExpiry(client, value)
458 await this.chunks?.freeze(client, stream.id)
459 return { stream: value, status: producer && payload.bytes.length ? 200 : 204, ...(producer ? { producer: { epoch: producer.epoch, seq: producer.seq } } : {}) }
460 })
461 }
462
463 async head(tenant: string, path: string): Promise<StreamMetadata> {
464 return this.withStream(tenant, path, async (_client, stream) => stream)
465 }
466
467 /** Only the subscription coordinator calls this inside its own transaction.
468 * Wake publication and the subscription's generation commit atomically. */
469 async appendWake(client: PoolClient, tenant: string, path: string, events: readonly Record<string, unknown>[]): Promise<void> {
470 const stream = await this.lock(client, tenant, path)
471 if (!stream || stream.deleted_at || stream.expired || stream.closed || mediaType(stream.content_type) !== 'application/json') throw new StreamError(409, 'WAKE_STREAM_UNAVAILABLE', 'Create an open JSON wake stream before issuing wakes')
472 let next = stream.tail_offset
473 let parts: Buffer[] = [], ends: number[] = [], bytes = 0
474 const flush = async () => {
475 if (!bytes) return
476 const end = advanceOffset(next, bytes)
477 await this.insertAppend(client, stream.id, next, end, Buffer.concat(parts, bytes), ends)
478 next = end
479 parts = []; ends = []; bytes = 0
480 }
481 for (const event of events) {
482 const fragment = Buffer.from(`${JSON.stringify(event)},`)
483 this.checkPayload(fragment)
484 if (bytes + fragment.length > this.maxStoredBytes) await flush()
485 parts.push(fragment); bytes += fragment.length; ends.push(bytes)
486 }
487 await flush()
488 if (next === stream.tail_offset) return
489 const result = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2, change_version = change_version + 1,
490 accessed_at = clock_timestamp() WHERE id = $1 RETURNING *`, [stream.id, next])
491 await this.change(client, result.rows[0]!, stream.tail_offset, 'appended')
492 if (stream.ttl_seconds !== null) await this.scheduleExpiry(client, stream)
493 await this.chunks?.freeze(client, stream.id)
494 }
495
496 async validateAckBoundaries(client: PoolClient, values: readonly { stream_id: string; offset: string }[]): Promise<void> {
497 if (!values.length) return
498 const invalid = await client.query(`${this.lineageForAcks()} SELECT r.stream_id FROM roots r WHERE r.offset <> $2 AND NOT EXISTS (
499 SELECT 1 FROM lineage l JOIN ${this.schema}.appends a ON a.stream_id = l.id WHERE l.root = r.stream_id AND a.end_offset = r.offset AND a.end_offset <= l.cap
500 ) LIMIT 1`, [JSON.stringify(values), ZERO_OFFSET])
501 if (invalid.rowCount) throw new StreamError(409, 'INVALID_OFFSET', 'Ack offset is not a returned boundary')
502 }
503
504 private lineageForAcks(): string {
505 return `WITH RECURSIVE roots AS (SELECT * FROM jsonb_to_recordset($1::jsonb) AS x(stream_id uuid, "offset" text)), lineage AS (
506 SELECT r.stream_id AS root, s.id, s.source_id, s.fork_offset, s.tail_offset AS cap, 0 AS depth FROM roots r JOIN ${this.schema}.streams s ON s.id = r.stream_id
507 UNION ALL SELECT l.root, p.id, p.source_id, p.fork_offset, LEAST(l.cap, l.fork_offset), l.depth + 1
508 FROM lineage l JOIN ${this.schema}.streams p ON p.id = l.source_id WHERE l.depth < 128
509 )`
510 }
511
512 async read(tenant: string, path: string, offset: string): Promise<ReadResult> {
513 const observedAt = performance.now()
514 if (!['-1', 'now'].includes(offset)) parseOffset(offset)
515 const plan = await this.withStream(tenant, path, async (client, stream) => {
516 if (stream.ttl_seconds !== null) {
517 const renewed = await client.query<{ accessed_at: Date; valid_for_ms: string }>(`UPDATE ${this.schema}.streams SET accessed_at = clock_timestamp() WHERE id = $1
518 RETURNING accessed_at, EXTRACT(epoch FROM (accessed_at + ttl_seconds * interval '1 second' - clock_timestamp())) * 1000 AS valid_for_ms`, [stream.id])
519 stream.accessed_at = renewed.rows[0]!.accessed_at
520 stream.valid_for_ms = renewed.rows[0]!.valid_for_ms
521 await this.scheduleExpiry(client, stream)
522 }
523 // The generation/tail are locked and lineage ranges are immutable.
524 // The frame query captures local bytes or a sealed reference atomically,
525 // including concurrent publication, before releasing these locks.
526 return this.planRead(client, stream, offset, observedAt)
527 })
528 return this.materializeRead(plan)
529 }
530
531 private async planRead(client: PoolClient, stream: StreamMetadata, offset: string, observedAt: number): Promise<ReplayPlan> {
532 const deadline = observedAt + this.replayTimeout
533 assertReplayDeadline(deadline)
534 const start = offset === '-1' ? ZERO_OFFSET : offset === 'now' ? stream.tail_offset : offset
535 await this.boundary(client, stream, start)
536 const frames = await this.framePlan(client, stream.id, start)
537 assertReplayDeadline(deadline)
538 const lease = await this.pins.acquire(client, frames)
539 const next = frames.at(-1)?.end_offset ?? start
540 return { stream, frames, lease, deadline, next, upToDate: next === stream.tail_offset, hasData: frames.length > 0,
541 validatedAt: observedAt, validUntil: observedAt + (stream.valid_for_ms == null ? Infinity : Number(stream.valid_for_ms)) }
542 }
543
544 private async materializeRead(plan: ReplayPlan): Promise<ReadResult> {
545 const frames = await this.materialize(plan)
546 if (plan.frames.some((frame) => frame.payload === null)) await this.guard.check()
547 return { stream: plan.stream, body: formatPayloads(frames.map((frame) => frame.payload), plan.stream.content_type), next: plan.next, upToDate: plan.upToDate, hasData: plan.hasData,
548 validatedAt: plan.validatedAt, validUntil: plan.validUntil }
549 }
550
551 private async generation(client: PoolClient, tenant: string, id: string): Promise<LockedStream> {
552 const metadata = await client.query<LockedStream>(`SELECT s.*, COALESCE(expires_at <= clock_timestamp()
553 OR accessed_at + ttl_seconds * interval '1 second' <= clock_timestamp(), false) AS expired,
554 CASE WHEN expires_at IS NOT NULL OR ttl_seconds IS NOT NULL THEN EXTRACT(epoch FROM
555 (COALESCE(expires_at, accessed_at + ttl_seconds * interval '1 second') - clock_timestamp())) * 1000 END AS valid_for_ms
556 FROM ${this.schema}.streams s WHERE tenant_id = $1 AND id = $2`, [tenant, id])
557 const stream = metadata.rows[0]
558 if (!stream) throw new StreamError(404, 'STREAM_NOT_FOUND', 'Stream no longer exists')
559 if (stream.deleted_at || stream.expired) throw new StreamError(stream.ref_count ? 410 : 404, 'STREAM_UNAVAILABLE', 'Stream is unavailable')
560 return stream
561 }
562
563 async validateGeneration(tenant: string, id: string): Promise<Pick<ReadResult, 'stream' | 'validatedAt' | 'validUntil'>> {
564 const validatedAt = performance.now()
565 const stream = await this.transaction({ readOnly: true }, (client) => this.generation(client, tenant, id))
566 return { stream, validatedAt, validUntil: validatedAt + (stream.valid_for_ms == null ? Infinity : Number(stream.valid_for_ms)) }
567 }
568
569 get replayLimits(): { maxBytes: number; maxFrames: number } { return { maxBytes: this.maxPageBytes - 2, maxFrames: this.maxPageFrames } }
570
571 /** An active live read must never switch to a recreated path generation. */
572 async readGeneration(tenant: string, id: string, offset: string): Promise<ReadResult> {
573 const observedAt = performance.now()
574 if (!['-1', 'now'].includes(offset)) parseOffset(offset)
575 const plan = await this.transaction(this.pins.enabled ? { repeatableRead: true } : { readOnly: true }, async (client) => {
576 return this.planRead(client, await this.generation(client, tenant, id), offset, observedAt)
577 })
578 return this.materializeRead(plan)
579 }
580
581 async maintain(options: { readonly maxChunks?: number; readonly freezeHot?: boolean } = {}): Promise<{ frozen: number; sealed: number; retired: number; reclamationWorked: boolean } & ReclamationResult> {
582 await this.assertReady()
583 const maximum = options.maxChunks ?? 8
584 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid maintenance batch')
585 let retired = 0
586 for (let i = 0; i < maximum; i++) {
587 const cleaned = await this.transaction({}, async (client) => {
588 const candidate = await client.query<{ tenant_id: string; path: string }>(`WITH candidates AS (
589 (SELECT s.id, s.tenant_id, s.path, e.due_at FROM ${this.schema}.stream_expirations e
590 JOIN ${this.schema}.streams s ON s.id = e.stream_id WHERE e.due_at <= clock_timestamp() ORDER BY e.due_at, e.stream_id LIMIT 128)
591 UNION ALL
592 (SELECT id, tenant_id, path, deleted_at AS due_at FROM ${this.schema}.streams WHERE cleanup_pending AND ref_count = 0 ORDER BY deleted_at, id LIMIT 128)
593 ) SELECT p.tenant_id, p.path FROM candidates c JOIN ${this.schema}.paths p
594 ON p.tenant_id = c.tenant_id AND p.path = c.path AND p.active_stream_id = c.id
595 ORDER BY c.due_at, c.id LIMIT 1 FOR UPDATE OF p SKIP LOCKED`)
596 if (!candidate.rows[0]) return false
597 const row = candidate.rows[0]
598 const stream = await this.lock(client, row.tenant_id, row.path)
599 if (stream?.deleted_at && !stream.ref_count) { await this.detach(client, stream); return true }
600 if (stream?.expired && !stream.deleted_at) { await this.retire(client, stream, 'expired'); return true }
601 return false
602 })
603 if (!cleaned) break
604 retired++
605 }
606 const chunks = this.chunks ? await this.chunks.maintain(options) : { frozen: 0, sealed: 0 }
607 const collected = this.schemaVersion === 6 ? await this.reclamation.maintain() : { ...emptyReclamation(), worked: false }
608 const { worked: reclamationWorked, ...counts } = collected
609 return { ...chunks, retired, ...counts, reclamationWorked }
610 }
611
612 /** One bounded query per watched generation, shared by all local readers. */
613 async headVersion(tenant: string, id: string): Promise<string | null> {
614 await this.guard.check()
615 const result = await this.pool.query<{ change_version: string }>(`SELECT change_version FROM ${this.schema}.streams WHERE tenant_id = $1 AND id = $2 AND deleted_at IS NULL
616 AND (expires_at IS NULL OR expires_at > clock_timestamp())
617 AND (ttl_seconds IS NULL OR accessed_at + ttl_seconds * interval '1 second' > clock_timestamp())`, [tenant, id])
618 return result.rows[0]?.change_version ?? null
619 }
620
621 async delete(tenant: string, path: string): Promise<void> {
622 await this.withStream(tenant, path, (client, stream) => this.retire(client, stream, 'deleted'))
623 }
624}