Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

store.ts

806 lines50.3 KB

1import { randomUUID } from 'node:crypto'
2import type { Pool, PoolClient, QueryResultRow } from 'pg'
3import { StorageCompatibilityError, StreamError } from './errors.js'
4import { advanceOffset, MAX_OFFSET_COMPONENT, ordinalOffset, 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, STORAGE_VERSION } from './migrations.js'
10import { streamPresence, unavailableGenerationStatus } from './stream-lifecycle.js'
11import { replayEtag, matchesEtag } from './etag.js'
12import { ReplayBudget } from './replay-budget.js'
13import { ChunkManager } from './storage.js'
14import type { StorageOptions } from './storage.js'
15import { unpackBlockDirectory } from './block-codec.js'
16import { decodeReplayRow } from './replay-plan.js'
17import type { StoredFrame, ReplayRow } from './replay-plan.js'
18import type { ChunkFrame } from './chunk-codec.js'
19import { assertReplayDeadline, ReplayPins } from './replay.js'
20import type { ReplayLease } from './replay.js'
21import { ReclamationManager } from './reclamation.js'
22import type { ReclamationResult } from './reclamation.js'
23​
24export interface Producer {
25 readonly id: string
26 readonly epoch: number
27 readonly seq: number
29​
30export interface StreamMetadata extends QueryResultRow {
31 id: string
32 tenant_id: string
33 path: string
34 content_type: string
35 tail_offset: string
36 change_version: string
37 closed: boolean
38 closed_by: Producer | null
39 last_seq: string | null
40 ttl_seconds: number | null
41 expires_at: Date | null
42 accessed_at: Date
43 valid_for_ms?: string | null
44 deleted_at: Date | null
45 source_id: string | null
46 fork_offset: string | null
47 fork_sub_offset: string
48 fork_depth: number
49 edge_active: boolean
50 ref_count: number
51 write_epoch: string
52 write_history: string
53 hot_frames: number
54 hot_bytes: string
56​
57interface LockedStream extends StreamMetadata { expired: boolean }
58export interface CreateOptions {
59 readonly contentType: string
60 readonly body: Uint8Array
61 readonly closed: boolean
62 readonly ttlSeconds?: number
63 readonly expiresAt?: Date
65​
66export interface AppendOptions {
67 readonly body: Uint8Array
68 readonly contentType: string | null
69 readonly close: boolean
70 readonly producer?: Producer
71 readonly sequence?: string
73export interface ForkOptions extends Omit<CreateOptions, 'contentType'> {
74 readonly contentType?: string
75 readonly sourcePath: string
76 readonly offset?: string
77 readonly subOffset: number
79​
80export interface AppendResult {
81 readonly stream: StreamMetadata
82 readonly status: 200 | 204
83 readonly producer?: { epoch: number; seq: number }
85export interface ReadResult {
86 readonly stream: StreamMetadata
87 readonly body: Buffer<ArrayBuffer>
88 readonly next: string
89 readonly upToDate: boolean
90 readonly hasData: boolean
91 readonly validatedAt: number
92 readonly validUntil: number
93 readonly etag?: string
94 readonly notModified?: boolean
95 readonly release?: () => void
97interface StoreOptions {
98 readonly maxStoredBytes?: number | undefined
99 readonly maxPageBytes?: number | undefined
100 readonly maxPageFrames?: number | undefined
101 readonly replayTimeoutMs?: number | undefined
102 readonly maxReplayMemoryBytes?: number | undefined
103 readonly consumesChanges?: boolean | undefined
104 readonly storage?: StorageOptions | undefined
105 readonly environmentId?: string | undefined
106 readonly timeouts?: Pick<TransactionOptions, 'timeoutMs' | 'lockTimeoutMs'> | undefined
108interface PinnedFrames { readonly frames: readonly StoredFrame[]; readonly lease: ReplayLease | undefined; readonly deadline: number }
109interface ReplayPlan extends Omit<ReadResult, 'body'>, PinnedFrames {
110 readonly etag: string
111 readonly notModified: boolean
112 readonly start: string
113 readonly condition: string | null | undefined
115​
116const MAX_PAGE_OBJECTS = 64
117​
118/** Transactional stream state and bounded replay planning. */
119export class PostgresStreamStore {
120 readonly schema: string
121 readonly guard: InstallationGuard
122 private ready: Promise<void> | undefined
123 private readonly chunks: ChunkManager | undefined
124 private readonly maxStoredBytes: number
125 private readonly maxPageBytes: number
126 private readonly maxPageFrames: number
127 private readonly replayTimeout: number
128 private readonly pins: ReplayPins
129 private readonly reclamation: ReclamationManager
130 private readonly replayBudget: ReplayBudget
131 private readonly reservationBytes: number
132 private readonly consumesChanges: boolean
133 close(): void { this.replayBudget.close(); this.chunks?.close() }
134 reserveRead(): () => void { return this.replayBudget.acquire(this.reservationBytes) }
135 reserveBody(bytes: number): () => void { return this.replayBudget.acquire(Math.max(1, bytes)) }
136​
137 constructor(
138 private readonly pool: Pool,
139 schema: string,
140 options: StoreOptions = {},
141 ) {
142 const { maxStoredBytes = 1024 * 1024, maxPageBytes = 2 * 1024 * 1024, maxPageFrames = 8192, replayTimeoutMs = 60_000,
143 maxReplayMemoryBytes = 256 * 1024 * 1024, storage, environmentId, timeouts } = options
144 this.consumesChanges = options.consumesChanges ?? false
145 this.maxStoredBytes = maxStoredBytes
146 this.maxPageBytes = maxPageBytes
147 this.maxPageFrames = maxPageFrames
148 this.schema = validateSchema(schema)
149 this.guard = new InstallationGuard(pool, schema, environmentId, timeouts)
150 this.pins = new ReplayPins(this.schema, this.guard)
151 this.reclamation = new ReclamationManager(this.schema, this.guard, storage?.objects)
152 this.replayTimeout = replayTimeoutMs
153 this.reservationBytes = Math.max(1024 * 1024, maxPageBytes * 3 + maxPageFrames * 512)
154 this.replayBudget = new ReplayBudget(maxReplayMemoryBytes)
155 this.chunks = storage ? new ChunkManager(pool, schema, storage, this.guard) : undefined
156 if (!Number.isSafeInteger(maxStoredBytes) || maxStoredBytes < 1 || maxStoredBytes > 16 * 1024 * 1024
157 || !Number.isSafeInteger(maxPageBytes) || maxPageBytes < maxStoredBytes + 2 || maxPageBytes > 64 * 1024 * 1024
158 || !Number.isSafeInteger(maxPageFrames) || maxPageFrames < 1 || maxPageFrames > 131072
159 || !Number.isSafeInteger(maxReplayMemoryBytes) || maxReplayMemoryBytes < this.reservationBytes || maxReplayMemoryBytes > 1024 * 1024 * 1024
160 || !Number.isSafeInteger(replayTimeoutMs) || replayTimeoutMs < 1 || replayTimeoutMs > 300_000) {
161 throw new RangeError('Invalid payload/page limits')
162 }
163 }
164​
165 async assertReady(): Promise<void> {
166 this.ready ??= this.pool.query<{ storage_version: number; storage_identity: string | null }>(`SELECT storage_version, storage_identity FROM ${this.schema}.installation`)
167 .then(async (result) => {
168 if (result.rows.length !== 1 || result.rows[0]!.storage_version !== STORAGE_VERSION) throw new StorageCompatibilityError('Unsupported storage version')
169 const migrations = await this.pool.query<{ id: string }>(`SELECT id FROM ${this.schema}.migrations ORDER BY id`)
170 const history = JSON.stringify(migrations.rows.map((row) => row.id))
171 if (history !== JSON.stringify(MIGRATION_IDS)) throw new StorageCompatibilityError('Unsupported database migrations; install the current baseline in a fresh schema')
172 if (result.rows[0]!.storage_identity !== null && !this.chunks) throw new StorageCompatibilityError('This installation requires its configured object storage')
173 await this.chunks?.assertBinding()
174 await this.reclamation.assertReady()
175 })
176 .catch((error: unknown) => { this.ready = undefined; throw error })
177 await this.ready
178 }
179​
180 transaction<T>(options: TransactionOptions, work: (client: PoolClient) => Promise<T>): Promise<T> {
181 return this.guard.run(options, work)
182 }
183​
184 private async lock(client: PoolClient, tenant: string, path: string): Promise<LockedStream | undefined> {
185 const claimed = await client.query<{ active_stream_id: string | null }>(`SELECT active_stream_id FROM ${this.schema}.paths
186 WHERE tenant_id = $1 AND path = $2 FOR UPDATE`, [tenant, path])
187 const id = claimed.rows[0]?.active_stream_id
188 if (!id) return undefined
189 const result = await client.query<LockedStream>(`SELECT s.*,
190 CASE WHEN s.expires_at IS NOT NULL OR s.ttl_seconds IS NOT NULL THEN
191 EXTRACT(epoch FROM (COALESCE(s.expires_at, s.accessed_at + s.ttl_seconds * interval '1 second') - clock_timestamp())) * 1000 END AS valid_for_ms,
192 COALESCE(s.expires_at <= clock_timestamp() OR
193 s.accessed_at + s.ttl_seconds * interval '1 second' <= clock_timestamp(), false) AS expired
194 FROM ${this.schema}.streams s
195 WHERE s.id = $1 FOR NO KEY UPDATE`, [id])
196 return result.rows[0]
197 }
198​
199 private async change(client: PoolClient, stream: StreamMetadata, before: string, kind: string): Promise<void> {
200 await client.query(`INSERT INTO ${this.schema}.stream_changes
201 (stream_id, version, before_offset, after_offset, kind) VALUES ($1, $2, $3, $4, $5)`,
202 [stream.id, stream.change_version, before, stream.tail_offset, kind])
203 }
204​
205 private async retire(client: PoolClient, stream: StreamMetadata, kind: 'deleted' | 'expired'): Promise<void> {
206 const result = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams
207 SET deleted_at = clock_timestamp(), change_version = change_version + 1, cleanup_pending = ref_count > 0 WHERE id = $1 RETURNING *`, [stream.id])
208 if (stream.ttl_seconds !== null || stream.expires_at !== null) await client.query(`DELETE FROM ${this.schema}.stream_expirations WHERE stream_id = $1`, [stream.id])
209 if (!stream.ref_count) await this.detach(client, result.rows[0]!)
210 await this.change(client, result.rows[0]!, stream.tail_offset, kind)
211 }
212​
213 /** Own path/stream are locked. Ancestor updates only follow the acyclic edge;
214 * ancestor path cleanup is a separate transaction, never a reverse path lock. */
215 private async detach(client: PoolClient, stream: StreamMetadata): Promise<void> {
216 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])
217 await client.query(`UPDATE ${this.schema}.streams SET cleanup_pending = false, edge_active = false WHERE id = $1`, [stream.id])
218 if (stream.source_id && stream.edge_active) {
219 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])
220 if (!parent.rowCount) throw new Error('Fork reference invariant failed')
221 }
222 }
223​
224 private async scheduleExpiry(client: PoolClient, stream: StreamMetadata): Promise<void> {
225 if (stream.ttl_seconds === null && stream.expires_at === null) return
226 await client.query(`INSERT INTO ${this.schema}.stream_expirations (stream_id, due_at)
227 SELECT id, COALESCE(expires_at, accessed_at + ttl_seconds * interval '1 second') FROM ${this.schema}.streams WHERE id = $1
228 ON CONFLICT (stream_id) DO UPDATE SET due_at = EXCLUDED.due_at`, [stream.id])
229 }
230​
231 private async withStream<T>(tenant: string, path: string, work: (client: PoolClient, stream: LockedStream) => Promise<T>): Promise<T> {
232 await this.assertReady()
233 const outcome = await this.transaction({}, async (client) => {
234 const stream = await this.lock(client, tenant, path)
235 if (!stream) return { found: false, status: 404 } as const
236 const presence = streamPresence(stream)
237 if (presence === 'deleted') return { found: false, status: 410 } as const
238 if (presence === 'expired') {
239 await this.retire(client, stream, 'expired')
240 return { found: false, status: unavailableGenerationStatus(stream.ref_count) } as const
241 }
242 return { found: true, value: await work(client, stream) } as const
243 })
244 // Missing/expired is reported after committing an expiry transition.
245 if (!outcome.found) throw new StreamError(outcome.status, outcome.status === 410 ? 'STREAM_GONE' : 'STREAM_NOT_FOUND', 'Stream is unavailable')
246 return outcome.value
247 }
248​
249 async create(tenant: string, path: string, options: CreateOptions): Promise<{ stream: StreamMetadata; created: boolean }> {
250 await this.assertReady()
251 const payload = preparePayload(options.body, options.contentType, true)
252 this.checkPayload(payload.bytes)
253 const outcome = await this.transaction({}, async (client) => {
254 await client.query(`INSERT INTO ${this.schema}.paths (tenant_id, path) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [tenant, path])
255 const namespace = await client.query(`SELECT path FROM ${this.schema}.paths WHERE tenant_id = $1 AND path = $2 FOR UPDATE`, [tenant, path])
256 if (namespace.rowCount !== 1) throw new StreamError(503, 'NAMESPACE_RETRY', 'Namespace changed; retry creation', { 'Retry-After': '1' })
257 let existing = await this.lock(client, tenant, path)
258 if (existing?.deleted_at) throw new StreamError(409, 'STREAM_RETAINED', 'Stream has active forks')
259 if (existing?.expired) {
260 await this.retire(client, existing, 'expired')
261 if (existing.ref_count) return { error: new StreamError(409, 'STREAM_RETAINED', 'Stream has active forks') } as const
262 existing = undefined
263 }
264 if (existing) {
265 if (existing.source_id !== null || mediaType(existing.content_type) !== mediaType(options.contentType) || existing.closed !== options.closed
266 || existing.ttl_seconds !== (options.ttlSeconds ?? null)
267 || (existing.expires_at?.toISOString() ?? null) !== (options.expiresAt?.toISOString() ?? null)) {
268 throw new StreamError(409, 'CONFIGURATION_MISMATCH', 'Stream configuration differs')
269 }
270 return { stream: existing, created: false }
271 }
272 const id = randomUUID()
273 const epoch = (await this.guard.snapshot()).serving_epoch
274 const history = id.replaceAll('-', '')
275 const tail = payload.bytes.length ? advanceOffset(ZERO_OFFSET, history) : ZERO_OFFSET
276 const result = await client.query<StreamMetadata>(`INSERT INTO ${this.schema}.streams
277 (id, tenant_id, path, content_type, tail_offset, change_version, closed, ttl_seconds, expires_at,hot_bytes,hot_frames,write_epoch,write_history)
278 VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8,$9,$10,$11,$1) RETURNING *`,
279 [id, tenant, path, options.contentType, tail, options.closed, options.ttlSeconds ?? null, options.expiresAt ?? null,payload.bytes.length,payload.bytes.length ? 1 : 0,epoch])
280 const stream = result.rows[0]!
281 await client.query(`UPDATE ${this.schema}.paths SET active_stream_id = $3 WHERE tenant_id = $1 AND path = $2`, [tenant, path, id])
282 if (payload.bytes.length) await this.insertAppend(client, id, ZERO_OFFSET, tail, payload.bytes, payload.messageEnds, true)
283 await this.change(client, stream, ZERO_OFFSET, 'created')
284 await this.scheduleExpiry(client, stream)
285 await this.chunks?.freeze(client, id)
286 return { stream, created: true }
287 })
288 if ('error' in outcome) throw outcome.error
289 return outcome
290 }
291​
292 private checkPayload(bytes: Uint8Array): void {
293 if (bytes.byteLength > this.maxStoredBytes) throw new StreamError(413, 'PAYLOAD_TOO_LARGE', 'Stored append exceeds configured limit')
294 }
295​
296 /** Each ancestor contributes only its fixed inherited range. No path lookup
297 * or current source lifecycle state can change an existing fork's view. */
298 private lineage(): string {
299 return `WITH RECURSIVE lineage AS (
300 SELECT id, tail_offset AS cap, source_id, fork_offset, 0 AS depth FROM ${this.schema}.streams WHERE id = $1
301 UNION ALL
302 SELECT p.id, LEAST(l.cap, l.fork_offset), p.source_id, p.fork_offset, l.depth + 1
303 FROM lineage l JOIN ${this.schema}.streams p ON p.id = l.source_id WHERE l.depth < 128
304 )`
305 }
306​
307 private async boundary(client: PoolClient, stream: StreamMetadata, offset: string): Promise<void> {
308 if (offset > stream.tail_offset) throw new StreamError(400, 'OFFSET_BEYOND_TAIL', 'Offset exceeds stream tail')
309 if (offset === ZERO_OFFSET || offset === stream.tail_offset) return
310 const result = await client.query(`${this.lineage()}
311 SELECT 1 FROM lineage l WHERE ${this.boundaryInLineage('$2')} LIMIT 1`, [stream.id, offset])
312 if (!result.rowCount) throw new StreamError(400, 'OFFSET_NOT_BOUNDARY', 'Offset is not a returned boundary')
313 }
314​
315 /** A dense ordinal interval authenticates every interior checkpoint using one
316 * history suffix. No per-append SQL directory survives sealing. */
317 private boundaryInLineage(offset: string): string {
318 return `${offset}<=l.cap AND (EXISTS (SELECT 1 FROM ${this.schema}.appends a WHERE a.stream_id=l.id AND a.end_offset=${offset})
319 OR EXISTS (SELECT 1 FROM LATERAL (SELECT start_offset,end_offset FROM ${this.schema}.chunks
320 WHERE stream_id=l.id AND state='sealed' AND end_offset>=${offset} ORDER BY end_offset LIMIT 1) c
321 WHERE c.start_offset=${offset} OR (substring(${offset},1,16)::bigint>substring(c.start_offset,1,16)::bigint
322 AND substring(${offset},1,16)::bigint<=substring(c.end_offset,1,16)::bigint
323 AND substring(${offset},18)=substring(c.end_offset,18))))`
324 }
325​
326 private async framePlan(client: PoolClient, id: string, start: string, limit = this.maxPageFrames, bytes = this.maxPageBytes - 2): Promise<readonly StoredFrame[]> {
327 const ordinal = parseOffset(start).ordinal
328 const ceiling = (value: bigint) => ordinalOffset(value > MAX_OFFSET_COMPONENT ? MAX_OFFSET_COMPONENT : value, 'f'.repeat(32))
329 const frameHorizon = ceiling(ordinal + BigInt(limit))
330 // A containing chunk can end at most the schema's frame cap beyond this
331 // horizon. Bound index scans even when later chunks remain frozen.
332 const chunkHorizon = ceiling(ordinal + BigInt(limit) + 131072n)
333 const result = await client.query<ReplayRow>(`${this.lineage()}, local_sources AS (
334 SELECT f.*,l.cap FROM lineage l CROSS JOIN LATERAL (
335 SELECT stream_id,start_offset,end_offset,payload_bytes FROM ${this.schema}.appends
336 WHERE stream_id=l.id AND end_offset>$2 AND end_offset<=$5 AND end_offset<=l.cap ORDER BY end_offset LIMIT $4
337 ) f WHERE l.cap>$2 AND (l.fork_offset IS NULL OR l.fork_offset<$5)
338 ), local_budget AS (
339 SELECT *,sum(payload_bytes) OVER (ORDER BY end_offset)-payload_bytes AS preceding_bytes FROM local_sources
340 ), sealed_sources AS (
341 SELECT c.*,l.cap FROM lineage l CROSS JOIN LATERAL (
342 SELECT id,stream_id,start_offset,end_offset,payload_bytes FROM ${this.schema}.chunks WHERE stream_id=l.id AND state='sealed'
343 AND end_offset>$2 AND end_offset<=$6 ORDER BY end_offset LIMIT LEAST($4,${MAX_PAGE_OBJECTS})
344 ) c WHERE l.cap>$2 AND c.start_offset<l.cap AND c.start_offset<$5 AND (l.fork_offset IS NULL OR l.fork_offset<$5)
345 ), sealed_ranges AS (
346 SELECT *,LEAST(left(end_offset,16)::bigint,left(cap,16)::bigint)
347 - GREATEST(left(start_offset,16)::bigint,left($2,16)::bigint) AS contributing_frames FROM sealed_sources
348 ), sealed_budget AS (
349 SELECT *,sum(contributing_frames) OVER (ORDER BY start_offset)-contributing_frames AS preceding_frames,
350 row_number() OVER (ORDER BY start_offset) AS object_number FROM sealed_ranges
351 ), candidates AS (
352 SELECT stream_id,start_offset,end_offset,payload_bytes,cap,NULL::uuid AS chunk_id FROM local_budget WHERE preceding_bytes<$3
353 UNION ALL
354 SELECT stream_id,start_offset,end_offset,payload_bytes::integer,cap,id AS chunk_id FROM sealed_budget WHERE preceding_frames<$4 AND object_number<=${MAX_PAGE_OBJECTS}
355 ORDER BY start_offset LIMIT $4
356 ) SELECT s.*,a.payload,a.message_ends,c.object_key,c.sha256,c.encoded_bytes,c.frame_count,c.block_directory,
357 c.start_offset AS chunk_start,c.end_offset AS chunk_end,CASE WHEN c.id IS NOT NULL THEN 1 END AS first_frame,c.frame_count AS last_frame
358 FROM candidates s LEFT JOIN ${this.schema}.appends a ON s.chunk_id IS NULL AND a.stream_id=s.stream_id AND a.end_offset=s.end_offset
359 LEFT JOIN ${this.schema}.chunks c ON c.id=s.chunk_id ORDER BY s.start_offset`, [id, start, bytes, limit, frameHorizon, chunkHorizon])
360 const planned: StoredFrame[] = []
361 let expected = start, count = 0, projected = 0, objects = 0
362 const add = (range: StoredFrame, frames: number) => {
363 if (range.start_offset !== expected || range.end_offset <= expected) throw new Error('Durable replay plan has a gap or overlap')
364 const previous = planned.at(-1)
365 if (previous?.storage === 'object' && range.storage === 'object' && previous.manifest.id === range.manifest.id) {
366 planned[planned.length - 1] = { ...previous, end_offset: range.end_offset, lastFrame: range.lastFrame,
367 payload_bytes: previous.payload_bytes + range.payload_bytes, exactBytes: previous.exactBytes && range.exactBytes }
368 } else planned.push(range)
369 expected = range.end_offset; count += frames; projected += range.payload_bytes
370 }
371 outer: for (const row of result.rows) {
372 if (count >= limit || projected >= bytes || objects >= MAX_PAGE_OBJECTS) break
373 const source = decodeReplayRow(row)
374 if (source.storage === 'postgres') {
375 if (count >= limit || projected >= bytes) break
376 add(source, 1)
377 continue
378 }
379 objects++
380 const { manifest } = source
381 const directory = unpackBlockDirectory(manifest.blockDirectory, manifest.encodedBytes, manifest.frameCount)
382 if (directory[0]!.start !== manifest.start || directory.at(-1)!.end !== manifest.end
383 || directory.reduce((sum, block) => sum + block.payloadBytes, 0) !== source.payload_bytes) throw new Error('Block directory differs from manifest')
384 const base = parseOffset(manifest.start).ordinal, history = parseOffset(manifest.end).history
385 const first = Math.max(0, Number(parseOffset(start).ordinal - base))
386 const last = Math.min(manifest.frameCount, Number(parseOffset(row.cap!).ordinal - base))
387 for (const block of directory) {
388 if (parseOffset(block.end).history !== history) throw new Error('Chunk crosses history spans')
389 const from = Math.max(first, block.firstFrame), through = Math.min(last, block.firstFrame + block.frameCount, from + limit - count)
390 if (through <= from) continue
391 if (count >= limit || projected >= bytes) break outer
392 const before = from === 0 ? manifest.start : ordinalOffset(base + BigInt(from), history)
393 const end = ordinalOffset(base + BigInt(through), history)
394 add({ ...source, start_offset: before, end_offset: end, payload_bytes: block.payloadBytes,
395 firstFrame: from + 1, lastFrame: through, exactBytes: from === block.firstFrame && through === block.firstFrame + block.frameCount }, through - from)
396 }
397 }
398 return planned
399 }
400​
401 private async materialize(plan: PinnedFrames, signal?: AbortSignal): Promise<readonly ChunkFrame[]> {
402 const { frames, deadline, lease } = plan
403 let result: readonly ChunkFrame[]
404 let completed = false
405 try {
406 signal?.throwIfAborted()
407 assertReplayDeadline(deadline)
408 const timeout = AbortSignal.timeout(Math.max(1, Math.ceil(deadline - performance.now())))
409 const combined = signal ? AbortSignal.any([signal, timeout]) : timeout
410 result = this.chunks ? await this.chunks.materialize(frames, deadline, combined) : frames.map((frame) => {
411 if (frame.storage !== 'postgres') throw new StorageCompatibilityError('Sealed replay requires object storage')
412 return { start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }
413 })
414 await this.pins.complete(lease)
415 completed = true
416 assertReplayDeadline(deadline)
417 signal?.throwIfAborted()
418 } catch (error) {
419 assertReplayDeadline(deadline)
420 throw error
421 } finally { if (!completed) await this.pins.release(lease) }
422 assertReplayDeadline(deadline)
423 return result
424 }
425​
426 async createFork(tenant: string, path: string, options: ForkOptions): Promise<{ stream: StreamMetadata; created: boolean }> {
427 const deadline = performance.now() + this.replayTimeout
428 await this.assertReady()
429 if (options.offset !== undefined) parseOffset(options.offset)
430 if (!Number.isSafeInteger(options.subOffset) || options.subOffset < 0) throw new StreamError(400, 'INVALID_SUB_OFFSET', 'Invalid sub-offset')
431 type Prefix = { sourceId: string; anchor: string; frame: ChunkFrame }
432 type Outcome = { stream: StreamMetadata; created: boolean } | { error: StreamError }
433 | { prepare: PinnedFrames & { sourceId: string; anchor: string; contentType: string } }
434 const execute = (prefix?: Prefix): Promise<Outcome> => this.transaction({}, async (client) => {
435 // Lock every namespace claim before locking any stream row. Inserts obey
436 // the same byte ordering, including when both paths are initially absent.
437 const paths = [...new Set([path, options.sourcePath])].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))
438 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])
439 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])
440 if (namespaces.rowCount !== paths.length) throw new StreamError(503, 'NAMESPACE_RETRY', 'Namespace changed; retry fork creation', { 'Retry-After': '1' })
441 let existing = await this.lock(client, tenant, path)
442 if (existing?.deleted_at) throw new StreamError(409, 'STREAM_RETAINED', 'Target stream has active forks')
443 if (existing?.expired) {
444 await this.retire(client, existing, 'expired')
445 if (existing.ref_count) return { error: new StreamError(409, 'STREAM_RETAINED', 'Target stream has active forks') }
446 existing = undefined
447 }
448 const source = await this.lock(client, tenant, options.sourcePath)
449 if (existing) {
450 const ttl = options.ttlSeconds ?? (options.expiresAt ? null : existing.ttl_seconds)
451 const expiry = options.expiresAt ?? (options.ttlSeconds !== undefined ? null : existing.expires_at)
452 if (!source || existing.source_id !== source.id || existing.closed !== options.closed
453 || mediaType(existing.content_type) !== mediaType(options.contentType ?? existing.content_type)
454 || existing.ttl_seconds !== ttl || (existing.expires_at?.toISOString() ?? null) !== (expiry?.toISOString() ?? null)
455 || (options.offset !== undefined && existing.fork_offset !== options.offset) || BigInt(existing.fork_sub_offset) !== BigInt(options.subOffset)) {
456 throw new StreamError(409, 'CONFIGURATION_MISMATCH', 'Stream configuration differs')
457 }
458 return { stream: existing, created: false }
459 }
460 if (!source) throw new StreamError(404, 'SOURCE_NOT_FOUND', 'Source stream not found')
461 if (source.deleted_at) throw new StreamError(409, 'SOURCE_RETAINED', 'Source stream is deleted')
462 if (source.expired) {
463 await this.retire(client, source, 'expired')
464 return { error: new StreamError(source.ref_count ? 409 : 404, 'SOURCE_EXPIRED', 'Source stream expired') }
465 }
466 if (path === options.sourcePath) throw new StreamError(409, 'SELF_FORK', 'A stream cannot fork itself')
467 if (source.fork_depth >= 128) throw new StreamError(413, 'FORK_DEPTH', 'Maximum fork depth reached')
468 if (options.contentType && mediaType(options.contentType) !== mediaType(source.content_type)) throw new StreamError(409, 'CONTENT_TYPE_MISMATCH', 'Fork content type must match its source')
469 const anchor = options.offset ?? source.tail_offset
470 await this.boundary(client, source, anchor)
471 const payload = preparePayload(options.body, source.content_type, true)
472 this.checkPayload(payload.bytes)
473 if (prefix && (prefix.sourceId !== source.id || prefix.anchor !== anchor)) throw new StreamError(409, 'SOURCE_CHANGED', 'Source generation changed; retry fork creation')
474 if (options.subOffset && !prefix) {
475 const frames = await this.framePlan(client, source.id, anchor, 1, this.maxStoredBytes)
476 if (!frames[0] || frames[0].start_offset !== anchor) throw new StreamError(400, 'SUB_OFFSET_BEYOND_TAIL', 'Sub-offset has no following source frame')
477 assertReplayDeadline(deadline)
478 const lease = await this.pins.acquire(client, frames)
479 return { prepare: { sourceId: source.id, anchor, contentType: source.content_type, frames, lease, deadline } }
480 }
481 const ttl = options.ttlSeconds ?? (options.expiresAt ? null : source.ttl_seconds)
482 const expiry = options.expiresAt ?? (options.ttlSeconds !== undefined ? null : source.expires_at)
483 const id = randomUUID()
484 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,hot_start_offset,write_epoch,write_history)
485 VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8, $9, $5, $10, $11, true,$5,$12,$1)`,
486 [id, tenant, path, source.content_type, anchor, options.closed, ttl, expiry, source.id, options.subOffset, source.fork_depth + 1,(await this.guard.snapshot()).serving_epoch])
487 let next = anchor
488 for (const frame of [...(prefix ? [prefix.frame] : []), ...(payload.bytes.length ? [{ payload: payload.bytes, messageEnds: payload.messageEnds }] : [])]) {
489 const end = advanceOffset(next, id.replaceAll('-', ''))
490 await this.insertAppend(client, id, next, end, frame.payload, frame.messageEnds, next === anchor)
491 next = end
492 }
493 const updated = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2,hot_frames=$3,hot_bytes=$4 WHERE id = $1 RETURNING *`,
494 [id,next,(prefix ? 1 : 0)+(payload.bytes.length ? 1 : 0),(prefix?.frame.payload.length ?? 0)+payload.bytes.length])
495 await client.query(`UPDATE ${this.schema}.paths SET active_stream_id = $3 WHERE tenant_id = $1 AND path = $2`, [tenant, path, id])
496 await client.query(`UPDATE ${this.schema}.streams SET ref_count = ref_count + 1 WHERE id = $1`, [source.id])
497 const stream = updated.rows[0]!
498 await this.change(client, stream, ZERO_OFFSET, 'created')
499 await this.scheduleExpiry(client, stream)
500 await this.chunks?.freeze(client, id)
501 return { stream, created: true }
502 })
503 let outcome = await execute()
504 if ('prepare' in outcome) {
505 const plan = outcome.prepare
506 const frame = (await this.materialize(plan))[0]!
507 const json = mediaType(plan.contentType) === 'application/json'
508 const units = json ? frame.messageEnds?.length ?? 0 : frame.payload.length
509 if (options.subOffset > units) throw new StreamError(400, 'SUB_OFFSET_OVERSHOOT', 'Sub-offset exceeds the next source frame')
510 const length = json ? frame.messageEnds![options.subOffset - 1]! : options.subOffset
511 const prefix = { ...frame, payload: Buffer.from(frame.payload.subarray(0, length)), messageEnds: json ? frame.messageEnds!.slice(0, options.subOffset) : null }
512 outcome = await execute({ sourceId: plan.sourceId, anchor: plan.anchor, frame: prefix })
513 }
514 if ('error' in outcome) throw outcome.error
515 if ('prepare' in outcome) throw new Error('Fork prefix was not resolved')
516 return outcome
517 }
518​
519 /** A surviving prefix keeps its tokens; the first write after recovery starts a
520 * fresh dense span. Freeze the previous hot span before entering the new one. */
521 private async writeHistory(client: PoolClient, stream: StreamMetadata): Promise<string> {
522 const epoch = (await this.guard.snapshot()).serving_epoch
523 if (stream.write_epoch !== epoch) {
524 await this.chunks?.freeze(client, stream.id, true)
525 const history = randomUUID()
526 await client.query(`UPDATE ${this.schema}.streams SET write_epoch=$2,write_history=$3 WHERE id=$1`, [stream.id, epoch, history])
527 stream.write_epoch = epoch
528 stream.write_history = history
529 // A lower work limit may leave an older span queued. Its next freeze
530 // stops at the history boundary; inserting the due record is idempotent.
531 if (this.chunks) stream.hot_frames = 0
532 }
533 return stream.write_history.replaceAll('-', '')
534 }
535​
536 private async insertAppend(client: PoolClient, id: string, start: string, end: string, bytes: Uint8Array, ends: readonly number[] | null, firstHot: boolean): Promise<void> {
537 const insert = `INSERT INTO ${this.schema}.appends (stream_id,start_offset,end_offset,payload,message_ends,payload_bytes) VALUES ($1,$2,$3,$4,$5,$6)`
538 if (firstHot && this.chunks) await client.query(`WITH inserted AS (${insert} RETURNING stream_id)
539 INSERT INTO ${this.schema}.hot_chunks SELECT stream_id,clock_timestamp()+$7*interval '1 millisecond' FROM inserted ON CONFLICT DO NOTHING`,
540 [id,start,end,bytes,ends,bytes.byteLength,this.chunks.maxAgeMs])
541 else await client.query(insert, [id,start,end,bytes,ends,bytes.byteLength])
542 }
543​
544 async append(tenant: string, path: string, options: AppendOptions): Promise<AppendResult> {
545 return this.withStream(tenant, path, async (client, stream) => {
546 const producer = options.producer
547 if (stream.closed) {
548 const duplicate = producer && stream.closed_by?.id === producer.id && stream.closed_by.epoch === producer.epoch && stream.closed_by.seq === producer.seq
549 if (duplicate || (!producer && options.close && options.body.length === 0)) {
550 return { stream, status: 204, ...(producer ? { producer: { epoch: producer.epoch, seq: producer.seq } } : {}) }
551 }
552 throw new StreamError(409, 'STREAM_CLOSED', 'Stream is closed', { 'Stream-Closed': 'true', 'Stream-Next-Offset': stream.tail_offset })
553 }
554 if (options.body.length && (!options.contentType || mediaType(options.contentType) !== mediaType(stream.content_type))) {
555 throw new StreamError(options.contentType ? 409 : 400, 'CONTENT_TYPE_MISMATCH', 'Content-Type must match the stream')
556 }
557 if (producer) {
558 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])
559 const prior = result.rows[0]
560 const epoch = prior ? Number(prior.epoch) : -1
561 const last = prior ? Number(prior.last_seq) : -1
562 if (producer.epoch < epoch) throw new StreamError(403, 'STALE_PRODUCER', 'Producer epoch is fenced', { 'Producer-Epoch': String(epoch) })
563 if (producer.epoch === epoch && producer.seq <= last) return { stream, status: 204, producer: { epoch, seq: last } }
564 const expected = producer.epoch === epoch ? last + 1 : 0
565 if (producer.seq !== expected) {
566 if (prior && producer.epoch > epoch) throw new StreamError(400, 'NEW_EPOCH_SEQUENCE', 'A new epoch must start at sequence zero')
567 throw new StreamError(409, 'PRODUCER_SEQUENCE_GAP', 'Producer sequence gap', { 'Producer-Expected-Seq': String(expected), 'Producer-Received-Seq': String(producer.seq) })
568 }
569 }
570 if (options.sequence !== undefined && stream.last_seq !== null && Buffer.compare(Buffer.from(options.sequence), Buffer.from(stream.last_seq)) <= 0) {
571 throw new StreamError(409, 'SEQUENCE_REGRESSION', 'Stream-Seq must increase')
572 }
573 if (!options.body.length && !options.close) throw new StreamError(400, 'EMPTY_APPEND', 'Append body must not be empty')
574 const payload = options.body.length ? preparePayload(options.body, stream.content_type) : { bytes: Buffer.alloc(0), messageEnds: null }
575 this.checkPayload(payload.bytes)
576 const history = payload.bytes.length ? await this.writeHistory(client, stream) : undefined
577 const next = payload.bytes.length ? advanceOffset(stream.tail_offset, history) : stream.tail_offset
578 if (payload.bytes.length) await this.insertAppend(client, stream.id, stream.tail_offset, next, payload.bytes, payload.messageEnds, stream.hot_frames===0)
579 if (producer) await client.query(`INSERT INTO ${this.schema}.producers (stream_id, producer_id, epoch, last_seq)
580 VALUES ($1, $2, $3, $4) ON CONFLICT (stream_id, producer_id) DO UPDATE SET epoch = EXCLUDED.epoch, last_seq = EXCLUDED.last_seq`,
581 [stream.id, producer.id, producer.epoch, producer.seq])
582 const updated = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2,
583 change_version = change_version + 1, closed = $3, closed_by = $4, last_seq = COALESCE($5, last_seq), accessed_at = clock_timestamp(),
584 hot_bytes=hot_bytes+$6,hot_frames=hot_frames+$7
585 WHERE id = $1 RETURNING *`, [stream.id, next, options.close, options.close && producer ? producer : null, options.sequence ?? null,payload.bytes.length,payload.bytes.length ? 1 : 0])
586 const value = updated.rows[0]!
587 await this.change(client, value, stream.tail_offset, options.close ? 'closed' : 'appended')
588 if (value.ttl_seconds !== null) await this.scheduleExpiry(client, value)
589 await this.chunks?.freeze(client, stream.id)
590 return { stream: value, status: producer && payload.bytes.length ? 200 : 204, ...(producer ? { producer: { epoch: producer.epoch, seq: producer.seq } } : {}) }
591 })
592 }
593​
594 async head(tenant: string, path: string): Promise<StreamMetadata> {
595 return this.withStream(tenant, path, async (_client, stream) => stream)
596 }
597​
598 /** Only the subscription coordinator calls this inside its own transaction.
599 * Wake publication and the subscription's generation commit atomically. */
600 async appendWake(client: PoolClient, tenant: string, path: string, events: readonly Record<string, unknown>[]): Promise<void> {
601 const stream = await this.lock(client, tenant, path)
602 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')
603 const history = events.length ? await this.writeHistory(client, stream) : undefined
604 let next = stream.tail_offset
605 let addedBytes=0,addedFrames=0
606 let parts: Buffer[] = [], ends: number[] = [], bytes = 0
607 const flush = async () => {
608 if (!bytes) return
609 const end = advanceOffset(next, history)
610 await this.insertAppend(client, stream.id, next, end, Buffer.concat(parts, bytes), ends,stream.hot_frames===0 && addedFrames===0)
611 addedBytes+=bytes; addedFrames++
612 next = end
613 parts = []; ends = []; bytes = 0
614 }
615 for (const event of events) {
616 const fragment = Buffer.from(`${JSON.stringify(event)},`)
617 this.checkPayload(fragment)
618 if (bytes + fragment.length > this.maxStoredBytes) await flush()
619 parts.push(fragment); bytes += fragment.length; ends.push(bytes)
620 }
621 await flush()
622 if (next === stream.tail_offset) return
623 const result = await client.query<StreamMetadata>(`UPDATE ${this.schema}.streams SET tail_offset = $2, change_version = change_version + 1,
624 accessed_at = clock_timestamp(),hot_bytes=hot_bytes+$3,hot_frames=hot_frames+$4 WHERE id = $1 RETURNING *`, [stream.id, next,addedBytes,addedFrames])
625 await this.change(client, result.rows[0]!, stream.tail_offset, 'appended')
626 if (stream.ttl_seconds !== null) await this.scheduleExpiry(client, stream)
627 await this.chunks?.freeze(client, stream.id)
628 }
629​
630 async validateAckBoundaries(client: PoolClient, values: readonly { stream_id: string; offset: string }[]): Promise<void> {
631 if (!values.length) return
632 const invalid = await client.query(`${this.lineageForAcks()} SELECT r.stream_id FROM roots r WHERE r.offset <> $2 AND NOT EXISTS (
633 SELECT 1 FROM lineage l WHERE l.root=r.stream_id AND ${this.boundaryInLineage('r.offset')}
634 ) LIMIT 1`, [JSON.stringify(values), ZERO_OFFSET])
635 if (invalid.rowCount) throw new StreamError(409, 'INVALID_OFFSET', 'Ack offset is not a returned boundary')
636 }
637​
638 private lineageForAcks(): string {
639 return `WITH RECURSIVE roots AS (SELECT * FROM jsonb_to_recordset($1::jsonb) AS x(stream_id uuid, "offset" text)), lineage AS (
640 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
641 UNION ALL SELECT l.root, p.id, p.source_id, p.fork_offset, LEAST(l.cap, l.fork_offset), l.depth + 1
642 FROM lineage l JOIN ${this.schema}.streams p ON p.id = l.source_id WHERE l.depth < 128
643 )`
644 }
645​
646 async read(tenant: string, path: string, offset: string, condition?: string | null, signal?: AbortSignal): Promise<ReadResult> {
647 signal?.throwIfAborted()
648 const observedAt = performance.now()
649 if (!['-1', 'now'].includes(offset)) parseOffset(offset)
650 await this.assertReady()
651 const snapshot = await this.transaction({ repeatableRead: true }, async (client) => {
652 const result = await client.query<LockedStream>(`SELECT s.*, COALESCE(expires_at <= clock_timestamp()
653 OR accessed_at + ttl_seconds * interval '1 second' <= clock_timestamp(), false) AS expired,
654 CASE WHEN expires_at IS NOT NULL THEN EXTRACT(epoch FROM (expires_at-clock_timestamp())) * 1000 END AS valid_for_ms
655 FROM ${this.schema}.paths p JOIN ${this.schema}.streams s ON s.id=p.active_stream_id
656 WHERE p.tenant_id=$1 AND p.path=$2`, [tenant, path])
657 const stream = result.rows[0]
658 if (!stream) throw new StreamError(404, 'STREAM_NOT_FOUND', 'Stream is unavailable')
659 // Lifecycle transitions and sliding TTL renewal require the writer path.
660 // Ordinary readers use one MVCC snapshot without locking the stream head.
661 if (stream.ttl_seconds !== null || streamPresence(stream) !== 'available') return undefined
662 return this.planRead(client, stream, offset, observedAt, condition)
663 }).catch((error: unknown) => {
664 if (typeof error === 'object' && error !== null && 'code' in error && error.code === '40001') {
665 throw new StreamError(503, 'REPLAY_RETRY', 'Replay snapshot changed; retry from the durable checkpoint', { 'Retry-After': '1' })
666 }
667 throw error
668 })
669 if (snapshot) return this.materializeRead(snapshot, signal)
670 const plan = await this.withStream(tenant, path, async (client, stream) => {
671 if (stream.ttl_seconds !== null) {
672 const renewed = await client.query<{ accessed_at: Date; valid_for_ms: string }>(`UPDATE ${this.schema}.streams SET accessed_at = clock_timestamp() WHERE id = $1
673 RETURNING accessed_at, EXTRACT(epoch FROM (accessed_at + ttl_seconds * interval '1 second' - clock_timestamp())) * 1000 AS valid_for_ms`, [stream.id])
674 stream.accessed_at = renewed.rows[0]!.accessed_at
675 stream.valid_for_ms = renewed.rows[0]!.valid_for_ms
676 await this.scheduleExpiry(client, stream)
677 }
678 // The generation/tail are locked and lineage ranges are immutable.
679 // The frame query captures local bytes or a sealed reference atomically,
680 // including concurrent publication, before releasing these locks.
681 return this.planRead(client, stream, offset, observedAt, condition)
682 })
683 return this.materializeRead(plan, signal)
684 }
685​
686 private async planRead(client: PoolClient, stream: StreamMetadata, offset: string, observedAt: number, condition?: string | null): Promise<ReplayPlan> {
687 const deadline = observedAt + this.replayTimeout
688 assertReplayDeadline(deadline)
689 const start = offset === '-1' ? ZERO_OFFSET : offset === 'now' ? stream.tail_offset : offset
690 await this.boundary(client, stream, start)
691 const overhead = mediaType(stream.content_type) === 'application/json' ? 1 : 0
692 const frames = await this.framePlan(client, stream.id, start, this.maxPageFrames, this.maxPageBytes - overhead)
693 assertReplayDeadline(deadline)
694 const next = frames.at(-1)?.end_offset ?? start
695 const installation = await this.guard.snapshot()
696 const etag = replayEtag({ generationId: stream.id, servingEpoch: installation.serving_epoch,
697 start, end: next, contentType: stream.content_type, closed: stream.closed })
698 const exact = frames.reduce((sum, frame) => sum + frame.payload_bytes, 0) <= this.maxPageBytes - overhead
699 const notModified = exact && offset !== 'now' && matchesEtag(condition, etag)
700 const lease = notModified ? undefined : await this.pins.acquire(client, frames)
701 return { stream, frames, lease, deadline, next, etag, notModified, start, condition: offset === 'now' ? undefined : condition, upToDate: next === stream.tail_offset, hasData: frames.length > 0,
702 validatedAt: observedAt, validUntil: observedAt + (stream.valid_for_ms == null ? Infinity : Number(stream.valid_for_ms)) }
703 }
704​
705 private async materializeRead(plan: ReplayPlan, signal?: AbortSignal): Promise<ReadResult> {
706 if (plan.notModified) {
707 await this.guard.check()
708 assertReplayDeadline(plan.deadline)
709 signal?.throwIfAborted()
710 return { ...plan, body: Buffer.alloc(0) }
711 }
712 const loaded = await this.materialize(plan, signal)
713 const frames: ChunkFrame[] = []
714 let payloadBytes = 0
715 const maximum = this.maxPageBytes - (mediaType(plan.stream.content_type) === 'application/json' ? 1 : 0)
716 for (const frame of loaded) {
717 if (payloadBytes + frame.payload.length > maximum || frames.length >= this.maxPageFrames) break
718 frames.push(frame); payloadBytes += frame.payload.length
719 }
720 if (loaded.length && !frames.length) throw new Error('Replay page cannot fit its first frame')
721 const next = frames.at(-1)?.end ?? plan.start
722 const etag = replayEtag({ generationId: plan.stream.id, servingEpoch: (await this.guard.snapshot()).serving_epoch,
723 start: plan.start, end: next, contentType: plan.stream.content_type, closed: plan.stream.closed })
724 const notModified = matchesEtag(plan.condition, etag)
725 if (plan.frames.some((frame) => frame.storage === 'object')) await this.guard.check()
726 const body = notModified ? Buffer.alloc(0) : formatPayloads(frames.map((frame) => frame.payload), plan.stream.content_type)
727 assertReplayDeadline(plan.deadline)
728 return { stream: plan.stream, body, next, upToDate: next === plan.stream.tail_offset, hasData: frames.length > 0, etag, notModified,
729 validatedAt: plan.validatedAt, validUntil: plan.validUntil }
730 }
731​
732 private async generation(client: PoolClient, tenant: string, id: string): Promise<LockedStream> {
733 const metadata = await client.query<LockedStream>(`SELECT s.*, COALESCE(expires_at <= clock_timestamp()
734 OR accessed_at + ttl_seconds * interval '1 second' <= clock_timestamp(), false) AS expired,
735 CASE WHEN expires_at IS NOT NULL OR ttl_seconds IS NOT NULL THEN EXTRACT(epoch FROM
736 (COALESCE(expires_at, accessed_at + ttl_seconds * interval '1 second') - clock_timestamp())) * 1000 END AS valid_for_ms
737 FROM ${this.schema}.streams s WHERE tenant_id = $1 AND id = $2`, [tenant, id])
738 const stream = metadata.rows[0]
739 if (!stream) throw new StreamError(404, 'STREAM_NOT_FOUND', 'Stream no longer exists')
740 if (streamPresence(stream) !== 'available') throw new StreamError(unavailableGenerationStatus(stream.ref_count), 'STREAM_UNAVAILABLE', 'Stream is unavailable')
741 return stream
742 }
743​
744 async validateGeneration(tenant: string, id: string): Promise<Pick<ReadResult, 'stream' | 'validatedAt' | 'validUntil'>> {
745 const validatedAt = performance.now()
746 const stream = await this.transaction({ readOnly: true }, (client) => this.generation(client, tenant, id))
747 return { stream, validatedAt, validUntil: validatedAt + (stream.valid_for_ms == null ? Infinity : Number(stream.valid_for_ms)) }
748 }
749​
750 get replayLimits(): { maxBytes: number; maxFrames: number } { return { maxBytes: this.maxPageBytes, maxFrames: this.maxPageFrames } }
751​
752 /** An active live read must never switch to a recreated path generation. */
753 async readGeneration(tenant: string, id: string, offset: string, signal?: AbortSignal): Promise<ReadResult> {
754 signal?.throwIfAborted()
755 const observedAt = performance.now()
756 if (!['-1', 'now'].includes(offset)) parseOffset(offset)
757 const plan = await this.transaction({ repeatableRead: true }, async (client) => {
758 return this.planRead(client, await this.generation(client, tenant, id), offset, observedAt)
759 })
760 return this.materializeRead(plan, signal)
761 }
762​
763 async maintain(options: { readonly maxChunks?: number; readonly forceHot?: boolean } = {}): Promise<{ frozen: number; sealed: number; retired: number; reclamationWorked: boolean } & ReclamationResult> {
764 await this.assertReady()
765 const maximum = options.maxChunks ?? 8
766 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid maintenance batch')
767 let retired = 0
768 for (let i = 0; i < maximum; i++) {
769 const cleaned = await this.transaction({}, async (client) => {
770 const candidate = await client.query<{ tenant_id: string; path: string }>(`WITH candidates AS (
771 (SELECT s.id, s.tenant_id, s.path, e.due_at FROM ${this.schema}.stream_expirations e
772 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)
773 UNION ALL
774 (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)
775 ) SELECT p.tenant_id, p.path FROM candidates c JOIN ${this.schema}.paths p
776 ON p.tenant_id = c.tenant_id AND p.path = c.path AND p.active_stream_id = c.id
777 ORDER BY c.due_at, c.id LIMIT 1 FOR UPDATE OF p SKIP LOCKED`)
778 if (!candidate.rows[0]) return false
779 const row = candidate.rows[0]
780 const stream = await this.lock(client, row.tenant_id, row.path)
781 if (stream?.deleted_at && !stream.ref_count) { await this.detach(client, stream); return true }
782 if (stream?.expired && !stream.deleted_at) { await this.retire(client, stream, 'expired'); return true }
783 return false
784 })
785 if (!cleaned) break
786 retired++
787 }
788 const chunks = this.chunks ? await this.chunks.maintain(options) : { frozen: 0, sealed: 0 }
789 const collected = await this.reclamation.maintain(!this.consumesChanges)
790 const { worked: reclamationWorked, ...counts } = collected
791 return { ...chunks, retired, ...counts, reclamationWorked }
792 }
793​
794 /** One bounded query per watched generation, shared by all local readers. */
795 async headVersion(tenant: string, id: string): Promise<string | null> {
796 await this.guard.check()
797 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
798 AND (expires_at IS NULL OR expires_at > clock_timestamp())
799 AND (ttl_seconds IS NULL OR accessed_at + ttl_seconds * interval '1 second' > clock_timestamp())`, [tenant, id])
800 return result.rows[0]?.change_version ?? null
801 }
802​
803 async delete(tenant: string, path: string): Promise<void> {
804 await this.withStream(tenant, path, (client, stream) => this.retire(client, stream, 'deleted'))
805 }