Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import type { Pool, PoolClient } from 'pg'
3import { chunkDigest, decodeChunk, encodeChunk } from './chunk-codec.js'
4import type { ChunkFrame } from './chunk-codec.js'
5import { StorageCompatibilityError } from './errors.js'
6import { validateSchema } from './path.js'
7import { InstallationGuard } from './installation.js'
8import { assertReplayDeadline } from './replay.js'
9
10export interface ChunkInventoryPage {
11 readonly objects: readonly { readonly key: string; readonly size: number }[]
12 readonly cursor: string | null
13}
14export class ChunkNotFoundError extends Error { override readonly name = 'ChunkNotFoundError' }
15
16/** Immutable-key storage. Collection capabilities are used only by enabled policy. */
17export interface ChunkStorage {
18 /** Stable identity of this branch/bucket/namespace, excluding credentials. */
19 readonly identity: string
20 readonly put: (key: string, bytes: Uint8Array) => Promise<void>
21 readonly get: (key: string, maxBytes: number) => Promise<Buffer>
22 readonly delete?: (key: string) => Promise<void>
23 readonly list?: (prefix: string, cursor: string | null, limit: number) => Promise<ChunkInventoryPage>
24}
25export interface StorageOptions {
26 readonly objects: ChunkStorage
27 readonly targetChunkBytes?: number
28 readonly maxChunkFrames?: number
29 readonly workerLeaseMs?: number
30}
31interface Manifest {
32 id: string
33 stream_id: string
34 start_offset: string
35 end_offset: string
36 state: 'frozen' | 'sealed'
37 frame_count: number
38 payload_bytes: string
39 claim_token: string
40 claim_epoch: string
41 object_key: string | null
42 sha256: string | null
43 encoded_bytes: number | null
44}
45export interface StoredFrame {
46 readonly stream_id: string
47 readonly start_offset: string
48 readonly end_offset: string
49 readonly payload: Buffer | null
50 readonly payload_bytes: number
51 readonly message_ends: number[] | null
52 readonly chunk_id: string | null
53 readonly object_key: string | null
54 readonly sha256: string | null
55 readonly encoded_bytes: number | null
56}
57
58/** Durable claims and immutable FROZEN frames make upload retries deterministic. */
59export class ChunkManager {
60 reclamation = false
61 private readonly schema: string
62 private readonly target: number
63 private readonly maximumFrames: number
64 private readonly lease: number
65 private installationId?: string
66 constructor(private readonly pool: Pool, schema: string, private readonly options: StorageOptions, private readonly guard = new InstallationGuard(pool, schema)) {
67 this.schema = validateSchema(schema)
68 this.target = options.targetChunkBytes ?? 4 * 1024 * 1024
69 this.maximumFrames = options.maxChunkFrames ?? 128
70 this.lease = options.workerLeaseMs ?? 120_000
71 if (!Number.isSafeInteger(this.target) || this.target < 1 || this.target > 16 * 1024 * 1024
72 || !Number.isSafeInteger(this.maximumFrames) || this.maximumFrames < 1 || this.maximumFrames > 1024
73 || !Number.isSafeInteger(this.lease) || this.lease < 1000 || this.lease > 300_000
74 || !options.objects.identity || options.objects.identity.length > 2048) throw new RangeError('Invalid storage options')
75 }
76 async assertBinding(): Promise<void> {
77 await this.guard.check()
78 const result = await this.pool.query<{ id: string; storage_identity: string | null }>(`SELECT id, storage_identity FROM ${this.schema}.installation`)
79 if (result.rows.length !== 1 || result.rows[0]!.storage_identity !== this.options.objects.identity) throw new StorageCompatibilityError('Run explicit migrations with the matching storageIdentity before enabling sealed storage')
80 this.installationId = result.rows[0]!.id
81 }
82 /** Caller holds the stream lock; rotation never performs network I/O. */
83 async freeze(client: PoolClient, streamId: string, force = false): Promise<boolean> {
84 if (!force) {
85 const head = await client.query<{ hot_bytes: string; hot_frames: number }>(`SELECT hot_bytes, hot_frames FROM ${this.schema}.streams WHERE id = $1`, [streamId])
86 if (!head.rows.length || (BigInt(head.rows[0]!.hot_bytes) < BigInt(this.target) && head.rows[0]!.hot_frames < this.maximumFrames)) return false
87 }
88 const frames = await client.query<{ start_offset: string; end_offset: string; payload_bytes: number }>(`SELECT start_offset, end_offset, payload_bytes FROM ${this.schema}.appends
89 WHERE stream_id = $1 AND chunk_id IS NULL ORDER BY end_offset LIMIT $2`, [streamId, this.maximumFrames])
90 if (!frames.rows.length) return false
91 // Bound an old installation's backlog as well as fresh append-time rotations.
92 const selected = []
93 let bytes = 0
94 for (const frame of frames.rows) { selected.push(frame); bytes += frame.payload_bytes; if (bytes >= this.target) break }
95 const first = selected[0]!, last = selected[selected.length - 1]!
96 const id = randomUUID()
97 await client.query(`INSERT INTO ${this.schema}.chunks (id, stream_id, start_offset, end_offset, state, frame_count, payload_bytes)
98 VALUES ($1, $2, $3, $4, 'frozen', $5, $6)`, [id, streamId, first.start_offset, last.end_offset, selected.length, bytes])
99 const assigned = await client.query(`UPDATE ${this.schema}.appends SET chunk_id = $2 WHERE stream_id = $1 AND chunk_id IS NULL AND end_offset <= $3`, [streamId, id, last.end_offset])
100 if (assigned.rowCount !== selected.length) throw new Error('Hot chunk rotation invariant failed')
101 await client.query(`UPDATE ${this.schema}.streams SET hot_bytes = hot_bytes - $2, hot_frames = hot_frames - $3, seal_after = clock_timestamp() WHERE id = $1`, [streamId, bytes, selected.length])
102 return true
103 }
104
105 async maintain(input: { readonly maxChunks?: number; readonly freezeHot?: boolean } = {}): Promise<{ frozen: number; sealed: number }> {
106 const maximum = input.maxChunks ?? 8
107 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid maintenance batch')
108 await this.assertBinding()
109 let frozen = 0, sealed = 0
110 for (let i = 0; i < maximum; i++) {
111 const rotated = input.freezeHot === false ? false : await this.guard.run({}, async (client) => {
112 const stream = await client.query<{ id: string }>(`SELECT id FROM ${this.schema}.streams WHERE hot_frames > 0 AND deleted_at IS NULL ORDER BY seal_after, id LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED`)
113 return stream.rows[0] ? this.freeze(client, stream.rows[0].id, true) : false
114 })
115 if (rotated) frozen++
116 const claim = await this.guard.run({}, async (client) => {
117 const candidate = await client.query<{ id: string }>(`SELECT id FROM ${this.schema}.chunks WHERE state = 'frozen'
118 ${this.reclamation ? 'AND retired_at IS NULL' : ''}
119 AND (claim_until IS NULL OR claim_until <= clock_timestamp()) ORDER BY created_at, id LIMIT 1 FOR UPDATE SKIP LOCKED`)
120 if (!candidate.rows[0]) return undefined
121 const result = await client.query<Manifest>(`UPDATE ${this.schema}.chunks SET claim_token = $2,
122 claim_epoch = claim_epoch + 1, claim_until = clock_timestamp() + $3 * interval '1 millisecond', attempts = attempts + 1
123 WHERE id = $1 RETURNING *`, [candidate.rows[0].id, randomUUID(), this.lease])
124 return result.rows[0]!
125 })
126 if (!claim) { if (!rotated) break; continue }
127 try {
128 const source = await this.pool.query<{ start_offset: string; end_offset: string; payload: Buffer; message_ends: number[] | null }>(`SELECT start_offset, end_offset, payload, message_ends FROM ${this.schema}.appends WHERE chunk_id = $1 ORDER BY end_offset`, [claim.id])
129 const identity = { installationId: this.installationId!, streamId: claim.stream_id, chunkId: claim.id }
130 const frames = source.rows.map((frame) => ({ start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }))
131 if (frames.length !== claim.frame_count || frames[0]?.start !== claim.start_offset || frames.at(-1)?.end !== claim.end_offset
132 || BigInt(frames.reduce((sum, frame) => sum + (frame.payload?.length ?? 0), 0)) !== BigInt(claim.payload_bytes)) throw new Error('Frozen manifest mismatch')
133 const bytes = encodeChunk({ ...identity, frames })
134 const digest = chunkDigest(bytes)
135 const key = `v1/${identity.installationId}/${identity.streamId}/${identity.chunkId}/${digest}.ndsc`
136 if (this.reclamation) {
137 const intended = await this.guard.run({}, async (client) => {
138 const valid = await client.query(`SELECT id FROM ${this.schema}.chunks WHERE id=$1 AND claim_token=$2 AND claim_epoch=$3
139 AND state='frozen' AND retired_at IS NULL AND claim_until>clock_timestamp() FOR UPDATE`, [claim.id, claim.claim_token, claim.claim_epoch])
140 if (!valid.rowCount) return false
141 await client.query(`INSERT INTO ${this.schema}.chunk_objects (object_key,stream_id,chunk_id,sha256,encoded_bytes)
142 VALUES ($1,$2,$3,$4,$5) ON CONFLICT (object_key) DO NOTHING`, [key, claim.stream_id, claim.id, digest, bytes.length])
143 const intent = await client.query(`SELECT 1 FROM ${this.schema}.chunk_objects WHERE object_key=$1 AND retired_at IS NULL
144 AND NOT orphan_candidate AND quarantine_reason IS NULL AND sha256=$2 AND encoded_bytes=$3`, [key, digest, bytes.length])
145 return !!intent.rowCount
146 })
147 if (!intended) continue
148 }
149 await this.options.objects.put(key, bytes)
150 // Verify the exact uploaded object before discarding any local payload.
151 decodeChunk(await this.options.objects.get(key, bytes.length), identity, digest)
152 const published = await this.guard.run({}, async (client) => {
153 const result = await client.query(`UPDATE ${this.schema}.chunks SET state = 'sealed', object_key = $4, sha256 = $5,
154 encoded_bytes = $6, sealed_at = clock_timestamp(), claim_until = NULL, claim_token = NULL
155 WHERE id = $1 AND claim_token = $2 AND claim_epoch = $3 AND state = 'frozen' AND claim_until > clock_timestamp()
156 ${this.reclamation ? 'AND retired_at IS NULL' : ''} RETURNING id`,
157 [claim.id, claim.claim_token, claim.claim_epoch, key, digest, bytes.length])
158 if (!result.rowCount) return false
159 const cleared = await client.query(`UPDATE ${this.schema}.appends SET payload = NULL, message_ends = NULL WHERE chunk_id = $1 AND payload IS NOT NULL`, [claim.id])
160 if (cleared.rowCount !== claim.frame_count) throw new Error('Chunk publication frame mismatch')
161 return true
162 })
163 if (published) sealed++
164 } catch (error) {
165 // A failed/ambiguous publication can be retried only by obtaining a new
166 // durable claim. This conditional release cannot unlock another worker.
167 await this.guard.run({}, async (client) => {
168 await client.query(`UPDATE ${this.schema}.chunks SET claim_until = NULL, claim_token = NULL
169 WHERE id = $1 AND claim_token = $2 AND claim_epoch = $3 AND state = 'frozen'`, [claim.id, claim.claim_token, claim.claim_epoch])
170 }).catch(() => {})
171 throw error
172 }
173 }
174 return { frozen, sealed }
175 }
176
177 /** The replay owner holds its pins; object I/O holds no SQL transaction. */
178 async materialize(frames: readonly StoredFrame[], deadline: number): Promise<readonly ChunkFrame[]> {
179 let currentChunkId: string | undefined
180 let decoded: readonly ChunkFrame[] | undefined
181 const result: ChunkFrame[] = []
182 for (const frame of frames) {
183 assertReplayDeadline(deadline)
184 if (frame.payload !== null) { result.push({ start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }); continue }
185 if (!frame.chunk_id || !frame.object_key || !frame.sha256 || !frame.encoded_bytes) throw new Error('Sealed frame is missing its manifest')
186 if (currentChunkId !== frame.chunk_id || !decoded) {
187 // A copied response page must not retain whole chunk buffers while
188 // another object is fetched or a slow reader holds the page.
189 decoded = undefined
190 const identity = { installationId: this.installationId!, streamId: frame.stream_id, chunkId: frame.chunk_id }
191 const bytes = await this.options.objects.get(frame.object_key, frame.encoded_bytes)
192 assertReplayDeadline(deadline)
193 if (bytes.length !== frame.encoded_bytes) throw new Error('Sealed object length differs from manifest')
194 decoded = decodeChunk(bytes, identity, frame.sha256).frames
195 currentChunkId = frame.chunk_id
196 }
197 const found = decoded.find((value) => value.start === frame.start_offset && value.end === frame.end_offset)
198 if (!found || found.payload.length !== frame.payload_bytes) throw new Error('Sealed object differs from frame index')
199 result.push({ ...found, payload: Buffer.from(found.payload) })
200 }
201 return result
202 }
203}