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

storage.ts

330 lines20.6 KB

1import { randomUUID } from 'node:crypto'
2import type { Pool, PoolClient } from 'pg'
3import { chunkDigest, decodeChunk, ChunkIntegrityError } from './chunk-codec.js'
4import type { ChunkFrame } from './chunk-codec.js'
5import { encodeBlockObject, decodeBlock, unpackBlockDirectory } from './block-codec.js'
6import { StorageCompatibilityError } from './errors.js'
7import { validateSchema } from './path.js'
8import { InstallationGuard } from './installation.js'
9import { assertReplayDeadline, replayPipeline } from './replay.js'
10import { VerifiedChunkCache } from './chunk-cache.js'
11import { isSuccessor, parseOffset } from './offset.js'
12import type { StoredFrame, ObjectRange } from './replay-plan.js'
13​
14export interface ChunkInventoryPage {
15 readonly objects: readonly { readonly key: string; readonly size: number }[]
16 readonly cursor: string | null
18export class ChunkNotFoundError extends Error { override readonly name = 'ChunkNotFoundError' }
19/** Half-open physical interval in one immutable object of the stated size. */
20export interface ChunkByteRange {
21 readonly start: number
22 readonly end: number
23 readonly totalBytes: number
25​
26/** Immutable-key storage. Collection capabilities are used only by enabled policy. */
27export interface ChunkStorage {
28 /** Stable identity of this branch/bucket/namespace, excluding credentials. */
29 readonly identity: string
30 readonly put: (key: string, bytes: Uint8Array) => Promise<void>
31 /** Transfers ownership of a buffer that the adapter will never mutate or reuse. */
32 readonly get: (key: string, maxBytes: number, signal?: AbortSignal) => Promise<Buffer>
33 readonly getRange: (key: string, range: ChunkByteRange, signal?: AbortSignal) => Promise<Buffer>
34 /** Delivers ordered fragments under backpressure without buffering the range. */
35 readonly readRange?: ((key: string, range: ChunkByteRange, consume: (bytes: Uint8Array) => void | Promise<void>, signal?: AbortSignal) => Promise<void>) | undefined
36 readonly delete?: (key: string) => Promise<void>
37 readonly list?: (prefix: string, cursor: string | null, limit: number) => Promise<ChunkInventoryPage>
39export interface StorageOptions {
40 readonly objects: ChunkStorage
41 readonly targetChunkBytes?: number
42 readonly maxChunkFrames?: number
43 readonly workerLeaseMs?: number
44 /** Maximum hot residency from the first append, independent of cron cadence. */
45 readonly maxChunkAgeMs?: number
46 /** Per-server verified-object cache budget; zero disables retention. */
47 readonly cacheBytes?: number
48 /** Encoded byte target for independently verified object ranges. */
49 readonly blockBytes?: number
50 /** At most one following object/range may overlap the current read. */
51 readonly readAhead?: 0 | 1
53interface FrozenClaim {
54 readonly id: string
55 readonly stream_id: string
56 readonly start_offset: string
57 readonly end_offset: string
58 readonly state: 'frozen'
59 readonly frame_count: number
60 readonly payload_bytes: string
61 readonly claim_token: string
62 readonly claim_epoch: string
64interface PreparedChunk {
65 readonly claim: FrozenClaim
66 readonly identity: { readonly installationId: string; readonly streamId: string; readonly chunkId: string }
67 readonly bytes: Buffer
68 readonly blockDirectory: Buffer
69 readonly digest: string
70 readonly key: string
72type VerifiedChunk = PreparedChunk
73​
74/** Durable claims and immutable FROZEN frames make upload retries deterministic. */
75export class ChunkManager {
76 private readonly schema: string
77 private readonly target: number
78 private readonly maximumFrames: number
79 private readonly blockBytes: number
80 private readonly readAhead: 0 | 1
81 private readonly lease: number
82 readonly maxAgeMs: number
83 private readonly cache: VerifiedChunkCache
84 private installationId?: string
85 close(): void { this.cache.close() }
86 constructor(private readonly pool: Pool, schema: string, private readonly options: StorageOptions, private readonly guard = new InstallationGuard(pool, schema)) {
87 this.schema = validateSchema(schema)
88 this.target = options.targetChunkBytes ?? 4 * 1024 * 1024
89 this.maximumFrames = options.maxChunkFrames ?? 8192
90 this.blockBytes = options.blockBytes ?? 65536
91 this.readAhead = options.readAhead ?? 0
92 this.lease = options.workerLeaseMs ?? 120_000
93 this.maxAgeMs = options.maxChunkAgeMs ?? 3_600_000
94 this.cache = new VerifiedChunkCache(options.cacheBytes ?? 32 * 1024 * 1024)
95 if (!Number.isSafeInteger(this.target) || this.target < 1 || this.target > 16 * 1024 * 1024
96 || !Number.isSafeInteger(this.maximumFrames) || this.maximumFrames < 1 || this.maximumFrames > 131072
97 || !Number.isSafeInteger(this.blockBytes) || this.blockBytes < 4096 || this.blockBytes > 16 * 1024 * 1024
98 || (this.readAhead !== 0 && this.readAhead !== 1)
99 || !Number.isSafeInteger(this.lease) || this.lease < 1000 || this.lease > 300_000
100 || !Number.isSafeInteger(this.maxAgeMs) || this.maxAgeMs < 1 || this.maxAgeMs > 604_800_000
101 || !options.objects.identity || options.objects.identity.length > 2048) throw new RangeError('Invalid storage options')
102 }
103 async assertBinding(): Promise<void> {
104 await this.guard.check()
105 const result = await this.pool.query<{ id: string; storage_identity: string | null }>(`SELECT id, storage_identity FROM ${this.schema}.installation`)
106 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')
107 this.installationId = result.rows[0]!.id
108 }
109 /** Caller holds the stream lock; rotation never performs network I/O. */
110 async freeze(client: PoolClient, streamId: string, force = false): Promise<boolean> {
111 const head = (await client.query<{ hot_bytes: string; hot_frames: number; hot_start_offset: string }>(`SELECT hot_bytes,hot_frames,hot_start_offset FROM ${this.schema}.streams WHERE id=$1`, [streamId])).rows[0]
112 if (!head || !head.hot_frames || (!force && BigInt(head.hot_bytes)<BigInt(this.target) && head.hot_frames<this.maximumFrames)) return false
113 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
114 WHERE stream_id=$1 AND end_offset>$3 ORDER BY end_offset LIMIT $2`, [streamId, this.maximumFrames,head.hot_start_offset])
115 if (!frames.rows.length) throw new Error('Hot chunk counters have no staging range')
116 // Bound an old installation's backlog as well as fresh append-time rotations.
117 const selected = []
118 let bytes = 0
119 for (const frame of frames.rows) {
120 if (selected.length && parseOffset(frame.end_offset).history !== parseOffset(selected[0]!.end_offset).history) break
121 selected.push(frame); bytes += frame.payload_bytes
122 if (bytes >= this.target) break
123 }
124 const first = selected[0]!, last = selected[selected.length - 1]!
125 let previous=head.hot_start_offset
126 for (const frame of selected) {
127 if (frame.start_offset!==previous || !isSuccessor(previous,frame.end_offset)) throw new Error('Hot staging range is not contiguous')
128 previous=frame.end_offset
129 }
130 if (selected.length>head.hot_frames || BigInt(bytes)>BigInt(head.hot_bytes)) throw new Error('Hot staging range differs from counters')
131 const id = randomUUID()
132 await client.query(`INSERT INTO ${this.schema}.chunks (id, stream_id, start_offset, end_offset, state, frame_count, payload_bytes)
133 VALUES ($1, $2, $3, $4, 'frozen', $5, $6)`, [id, streamId, first.start_offset, last.end_offset, selected.length, bytes])
134 await client.query(`UPDATE ${this.schema}.streams SET hot_bytes=hot_bytes-$2,hot_frames=hot_frames-$3,hot_start_offset=$4 WHERE id=$1`, [streamId,bytes,selected.length,last.end_offset])
135 await client.query(`DELETE FROM ${this.schema}.hot_chunks h USING ${this.schema}.streams s WHERE h.stream_id=$1 AND s.id=h.stream_id AND s.hot_frames=0`, [streamId])
136 return true
137 }
138​
139 async maintain(input: { readonly maxChunks?: number; readonly forceHot?: boolean } = {}): Promise<{ frozen: number; sealed: number }> {
140 const maximum = input.maxChunks ?? 8
141 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid maintenance batch')
142 await this.assertBinding()
143 let frozen = 0, sealed = 0
144 for (let i = 0; i < maximum; i++) {
145 const rotated = await this.guard.run({}, async (client) => {
146 const stream = await client.query<{ id: string }>(`SELECT s.id FROM ${this.schema}.hot_chunks h JOIN ${this.schema}.streams s ON s.id=h.stream_id
147 WHERE ${input.forceHot ? 'true' : 'h.due_at<=clock_timestamp()'} AND (s.deleted_at IS NULL OR s.ref_count > 0)
148 ORDER BY h.due_at,h.stream_id LIMIT 1 FOR NO KEY UPDATE OF s SKIP LOCKED`)
149 return stream.rows[0] ? this.freeze(client, stream.rows[0].id, true) : false
150 })
151 if (rotated) frozen++
152 const claim = await this.claimFrozen()
153 if (!claim) { if (!rotated) break; continue }
154 try {
155 const prepared = await this.prepare(claim)
156 if (!await this.recordIntent(prepared)) continue
157 const verified = await this.uploadAndVerify(prepared)
158 if (await this.publish(verified)) sealed++
159 } catch (error) {
160 await this.releaseClaim(claim)
161 throw error
162 }
163 }
164 return { frozen, sealed }
165 }
166​
167 private async claimFrozen(): Promise<FrozenClaim | undefined> {
168 return this.guard.run({}, async (client) => {
169 const candidate = await client.query<{ id: string }>(`SELECT id FROM ${this.schema}.chunks WHERE state = 'frozen'
170 AND retired_at IS NULL
171 AND (claim_until IS NULL OR claim_until <= clock_timestamp()) ORDER BY created_at, id LIMIT 1 FOR UPDATE SKIP LOCKED`)
172 if (!candidate.rows[0]) return undefined
173 const result = await client.query<FrozenClaim>(`UPDATE ${this.schema}.chunks SET claim_token = $2,
174 claim_epoch = claim_epoch + 1, claim_until = clock_timestamp() + $3 * interval '1 millisecond', attempts = attempts + 1
175 WHERE id = $1 RETURNING *`, [candidate.rows[0].id, randomUUID(), this.lease])
176 return result.rows[0]!
177 })
178 }
179 private async prepare(claim: FrozenClaim): Promise<PreparedChunk> {
180 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
181 WHERE stream_id=$1 AND end_offset>$2 AND end_offset<=$3 ORDER BY end_offset`, [claim.stream_id,claim.start_offset,claim.end_offset])
182 const identity = { installationId: this.installationId!, streamId: claim.stream_id, chunkId: claim.id }
183 const frames = source.rows.map((frame) => ({ start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }))
184 if (frames.length !== claim.frame_count || frames[0]?.start !== claim.start_offset || frames.at(-1)?.end !== claim.end_offset
185 || BigInt(frames.reduce((sum, frame) => sum + (frame.payload?.length ?? 0), 0)) !== BigInt(claim.payload_bytes)) throw new Error('Frozen manifest mismatch')
186 const encoded = encodeBlockObject({ ...identity, frames }, this.blockBytes)
187 const bytes = encoded.bytes
188 const digest = chunkDigest(bytes)
189 const key = `v1/${identity.installationId}/${identity.streamId}/${identity.chunkId}/${digest}.ndsc`
190 return { claim, identity, bytes, blockDirectory: encoded.packedDirectory, digest, key }
191 }
192 private async recordIntent({ claim, key, digest, bytes }: PreparedChunk): Promise<boolean> {
193 return this.guard.run({}, async (client) => {
194 const valid = await client.query(`SELECT id FROM ${this.schema}.chunks WHERE id=$1 AND claim_token=$2 AND claim_epoch=$3
195 AND state='frozen' AND retired_at IS NULL AND claim_until>clock_timestamp() FOR UPDATE`, [claim.id, claim.claim_token, claim.claim_epoch])
196 if (!valid.rowCount) return false
197 await client.query(`INSERT INTO ${this.schema}.chunk_objects (object_key,stream_id,chunk_id,sha256,encoded_bytes)
198 VALUES ($1,$2,$3,$4,$5) ON CONFLICT (object_key) DO NOTHING`, [key, claim.stream_id, claim.id, digest, bytes.length])
199 const intent = await client.query(`SELECT 1 FROM ${this.schema}.chunk_objects WHERE object_key=$1 AND retired_at IS NULL
200 AND NOT orphan_candidate AND quarantine_reason IS NULL AND sha256=$2 AND encoded_bytes=$3`, [key, digest, bytes.length])
201 return !!intent.rowCount
202 })
203 }
204 /** Network I/O holds no SQL transaction. Only verified bytes may publish. */
205 private async uploadAndVerify(prepared: PreparedChunk): Promise<VerifiedChunk> {
206 const { claim, key, bytes, identity, digest } = prepared
207 await this.options.objects.put(key, bytes)
208 // Verify the exact uploaded object before discarding any local payload.
209 const verified = await this.options.objects.get(key, bytes.length)
210 if (verified.length !== bytes.length) throw new Error('Published object length differs')
211 const frames = decodeChunk(verified, identity, digest).frames
212 if (frames.length !== claim.frame_count || frames[0]?.start !== claim.start_offset || frames.at(-1)?.end !== claim.end_offset) throw new Error('Uploaded object differs from frozen range')
213 return prepared
214 }
215 private async publish({ claim, key, digest, bytes, blockDirectory }: VerifiedChunk): Promise<boolean> {
216 return this.guard.run({}, async (client) => {
217 const result = await client.query(`UPDATE ${this.schema}.chunks SET state = 'sealed', object_key = $4, sha256 = $5,
218 encoded_bytes = $6, block_directory=$7, sealed_at = clock_timestamp(), claim_until = NULL, claim_token = NULL
219 WHERE id = $1 AND claim_token = $2 AND claim_epoch = $3 AND state = 'frozen' AND claim_until > clock_timestamp()
220 AND retired_at IS NULL RETURNING id`,
221 [claim.id, claim.claim_token, claim.claim_epoch, key, digest, bytes.length, blockDirectory])
222 if (!result.rowCount) return false
223 const cleared = await client.query(`DELETE FROM ${this.schema}.appends WHERE stream_id=$1 AND end_offset>$2 AND end_offset<=$3`, [claim.stream_id,claim.start_offset,claim.end_offset])
224 if (cleared.rowCount !== claim.frame_count) throw new Error('Chunk publication frame mismatch')
225 return true
226 })
227 }
228 private async releaseClaim(claim: FrozenClaim): Promise<void> {
229 // Conditional release cannot unlock a replacement worker after a lost reply.
230 await this.guard.run({}, async (client) => {
231 await client.query(`UPDATE ${this.schema}.chunks SET claim_until = NULL, claim_token = NULL
232 WHERE id = $1 AND claim_token = $2 AND claim_epoch = $3 AND state = 'frozen'`, [claim.id, claim.claim_token, claim.claim_epoch])
233 }).catch(() => {})
234 }
235​
236 /** The replay owner holds its pins; object I/O holds no SQL transaction. */
237 async materialize(frames: readonly StoredFrame[], deadline: number, signal?: AbortSignal): Promise<readonly ChunkFrame[]> {
238 const pages = await replayPipeline(frames, async (frame, readSignal) => {
239 assertReplayDeadline(deadline)
240 if (frame.storage === 'postgres') return [{ start: frame.start_offset, end: frame.end_offset, payload: frame.payload, messageEnds: frame.message_ends }]
241 const selected = await this.readObjectRange(frame, readSignal)
242 assertReplayDeadline(deadline)
243 if (selected.length !== frame.lastFrame - frame.firstFrame + 1 || selected[0]?.start !== frame.start_offset || selected.at(-1)?.end !== frame.end_offset
244 || (frame.exactBytes ? selected.reduce((sum, value) => sum + value.payload.length, 0) !== frame.payload_bytes
245 : selected.reduce((sum, value) => sum + value.payload.length, 0) > frame.payload_bytes)) throw new Error('Sealed object differs from planned range')
246 // The store copies these private views into its response or fork prefix.
247 // Avoid a temporary payload copy between verification and that boundary.
248 return selected
249 }, this.readAhead, signal)
250 return pages.flat()
251 }
252​
253 private async readObjectRange(frame: ObjectRange, signal: AbortSignal): Promise<readonly ChunkFrame[]> {
254 const { manifest } = frame
255 const identity = { installationId: this.installationId!, streamId: frame.stream_id, chunkId: manifest.id }
256 const key = JSON.stringify([this.options.objects.identity, ...Object.values(identity), manifest.sha256, manifest.encodedBytes, chunkDigest(manifest.blockDirectory)])
257 const directory = unpackBlockDirectory(manifest.blockDirectory, manifest.encodedBytes, manifest.frameCount)
258 if (directory[0]!.start !== manifest.start || directory.at(-1)!.end !== manifest.end) throw new Error('Block directory differs from durable range')
259 const blocks = directory.filter((block) => block.firstFrame < frame.lastFrame && block.firstFrame + block.frameCount >= frame.firstFrame)
260 const cached = this.cache.peek(key)
261 if (cached) return cached.frames.slice(frame.firstFrame - 1, frame.lastFrame)
262 if (blocks.length === directory.length) {
263 const whole = await this.cache.get(key, async (sharedSignal) => {
264 const bytes = await this.options.objects.get(manifest.key, manifest.encodedBytes, sharedSignal)
265 if (bytes.length !== manifest.encodedBytes) throw new Error('Sealed object length differs from manifest')
266 const decoded = decodeChunk(bytes, identity, manifest.sha256)
267 const packedLength = bytes.readUInt32BE(64)
268 if (!bytes.subarray(68, 68 + packedLength).equals(manifest.blockDirectory)) throw new Error('Sealed object differs from its manifest')
269 return decoded
270 }, manifest.encodedBytes, signal)
271 return whole.frames.slice(frame.firstFrame - 1, frame.lastFrame)
272 }
273 if (!blocks.length) throw new Error('Replay selected no object blocks')
274 const requests = blocks.map((block) => ({ key: `${key}:${block.byteStart}:${block.sha256}`, encodedBytes: block.byteLength, block }))
275 const byKey = new Map(requests.map((request) => [request.key, request.block]))
276 const decoded = await this.cache.getMany(requests, async (missing, sharedSignal) => {
277 const groups: (typeof blocks)[] = []
278 for (const request of missing) {
279 const block = byKey.get(request.key)!
280 const current = groups.at(-1)
281 const previous = current?.at(-1)
282 if (previous && previous.byteStart + previous.byteLength === block.byteStart) current!.push(block)
283 else groups.push([block])
284 }
285 const loaded = await replayPipeline(groups, async (group, groupSignal) => {
286 const start = group[0]!.byteStart, end = group.at(-1)!.byteStart + group.at(-1)!.byteLength
287 if (this.options.objects.readRange) {
288 const chunks: { installationId: string; streamId: string; chunkId: string; frames: readonly ChunkFrame[] }[] = []
289 let index = 0, position = 0
290 let owned: Buffer | undefined
291 await this.options.objects.readRange(manifest.key, { start, end, totalBytes: manifest.encodedBytes }, (part) => {
292 let consumed = 0
293 while (consumed < part.byteLength) {
294 const block = group[index]
295 if (!block) throw new ChunkIntegrityError('Range returned bytes beyond its last block')
296 owned ??= Buffer.allocUnsafe(block.byteLength)
297 const length = Math.min(part.byteLength - consumed, owned.length - position)
298 owned.set(part.subarray(consumed, consumed + length), position)
299 consumed += length
300 position += length
301 if (position === owned.length) {
302 chunks.push({ ...identity, frames: decodeBlock(owned, block) })
303 owned = undefined
304 position = 0
305 index++
306 }
307 }
308 }, groupSignal)
309 if (index !== group.length || position !== 0) throw new ChunkIntegrityError('Range ended inside a block')
310 return chunks
311 }
312 const bytes = await this.options.objects.getRange(manifest.key, { start, end, totalBytes: manifest.encodedBytes }, groupSignal)
313 if (bytes.length !== end - start) throw new ChunkIntegrityError('Range length differs from requested blocks')
314 return group.map((block) => {
315 const localStart = block.byteStart - start
316 // A retained block must own its allocation independently of the group.
317 const owned = group.length === 1 ? bytes : Buffer.from(bytes.subarray(localStart, localStart + block.byteLength))
318 return { ...identity, frames: decodeBlock(owned, block) }
319 })
320 }, 0, sharedSignal)
321 return loaded.flat()
322 }, signal)
323 const selected: ChunkFrame[] = []
324 for (const [index, chunk] of decoded.entries()) {
325 const block = blocks[index]!
326 selected.push(...chunk.frames.slice(Math.max(0, frame.firstFrame - 1 - block.firstFrame), frame.lastFrame - block.firstFrame))
327 }
328 return selected
329 }