Open History to see the last commit
1import { createHash } from 'node:crypto'
2import type { Envelope } from '@neon/realtime-electric-protocol'
3import {
4 IndexedJsonLog,
5 shapeLogCodec,
6 type LogCodec,
7 LogStorageError,
8 type LogBoundary,
9 type LogRead,
10} from './shape-log.js'
11
12/** Small injectable boundary, implemented by the real S3 adapter and fault fixtures. */
13export interface LogObjectStore {
14 put(key: string, bytes: Uint8Array, signal?: AbortSignal): Promise<void>
15 get(key: string, signal?: AbortSignal): Promise<Uint8Array>
16 delete(key: string): Promise<void>
17}
18export interface ObjectLogOptions {
19 store: LogObjectStore
20 /** Dedicated prefix for this handle, including its absolute expiry. */
21 prefix: string
22 sealBytes?: number
23 maxResidentBytes?: number
24}
25interface SealedRange {
26 key: string
27 checksum: string
28 start: number
29 count: number
30}
31
32/** Immutable sealed JSON ranges plus a resident tail; the index never moves. */
33export class ObjectJsonLog<T> extends IndexedJsonLog<T> {
34 readonly #ranges: SealedRange[] = []
35 readonly #attemptedKeys = new Set<string>()
36 readonly #abort = new AbortController()
37 readonly #sealBytes: number
38 readonly #maxResidentBytes: number
39 #residentBytes = 0
40 #sealedCount = 0
41 #scheduled = false
42 #stopped = false
43 #pending: Promise<void> = Promise.resolve()
44 #disposal: Promise<void> = Promise.resolve()
45 #uploadError?: Error
46
47 constructor(
48 private readonly options: ObjectLogOptions,
49 codec: LogCodec<T>
50 ) {
51 super(codec)
52 this.#sealBytes = options.sealBytes ?? 256 * 1024
53 this.#maxResidentBytes = options.maxResidentBytes ?? 8 * 1024 * 1024
54 if (!options.prefix || options.prefix.endsWith('/'))
55 throw new Error(
56 'Object log needs a nonempty handle prefix without a trailing slash'
57 )
58 if (
59 !Number.isSafeInteger(this.#sealBytes) ||
60 this.#sealBytes < 1 ||
61 !Number.isSafeInteger(this.#maxResidentBytes) ||
62 this.#maxResidentBytes < this.#sealBytes
63 )
64 throw new Error('Invalid object log byte limits')
65 }
66 get residentBytes(): number {
67 return this.#residentBytes
68 }
69 get sealedRanges(): number {
70 return this.#ranges.length
71 }
72 get uploadError(): Error | undefined {
73 return this.#uploadError
74 }
75 /** Await cleanup to observe deletion failures; close also observes its rejection. */
76 get disposed(): Promise<void> {
77 return this.#disposal
78 }
79
80 override append(value: T): LogBoundary {
81 const parsed = this.codec.parse(value)
82 const bytes = Buffer.byteLength(JSON.stringify(parsed)) + 1
83 if (this.#residentBytes + bytes > this.#maxResidentBytes) {
84 throw new LogStorageError(
85 'Object log resident byte limit exceeded; refetch required'
86 )
87 }
88 const boundary = super.append(parsed)
89 this.#residentBytes += bytes
90 this.#schedule()
91 return boundary
92 }
93
94 /** Seal everything committed at this call's boundary. Retries preserve keys/bytes. */
95 flush(): Promise<void> {
96 const target = this.entries.length
97 const operation = this.#pending
98 .catch(() => {})
99 .then(() => this.#sealThrough(target))
100 this.#pending = operation
101 return operation
102 }
103 async #sealThrough(target: number): Promise<void> {
104 while (!this.#stopped && this.#sealedCount < target) {
105 const start = this.#sealedCount
106 let end = start
107 let size = 0
108 while (end < target && (size < this.#sealBytes || end === start)) {
109 size += this.entries[end].bytes
110 end++
111 }
112 const bytes = Buffer.from(
113 this.entries
114 .slice(start, end)
115 .map((e) => e.encoded! + '\n')
116 .join('')
117 )
118 const checksum = digest(bytes)
119 const key = `${this.options.prefix}/${this.entries[start].boundary.afterSeq}-${this.entries[end - 1].boundary.afterSeq}-${checksum}.ndjson`
120 this.#attemptedKeys.add(key)
121 try {
122 await this.options.store.put(key, bytes, this.#abort.signal)
123 } catch (error) {
124 this.#uploadError = asError(error)
125 throw error
126 }
127 // Publish the range descriptor before releasing resident record bytes.
128 this.#ranges.push({ key, checksum, start, count: end - start })
129 for (let i = start; i < end; i++) this.entries[i].encoded = undefined
130 this.#sealedCount = end
131 this.#residentBytes -= size
132 this.#uploadError = undefined
133 }
134 }
135 #schedule(): void {
136 if (
137 this.#scheduled ||
138 this.#stopped ||
139 this.#residentBytes < this.#sealBytes
140 )
141 return
142 this.#scheduled = true
143 void this.flush().then(
144 () => {
145 this.#scheduled = false
146 this.#schedule()
147 },
148 () => {
149 // Bytes remain available locally. A subsequent append or explicit flush
150 // retries; the resident cap bounds growth during a storage outage.
151 this.#scheduled = false
152 }
153 )
154 }
155
156 async read(
157 offset: string,
158 limit?: number,
159 signal?: AbortSignal
160 ): Promise<LogRead<T>> {
161 const readSignal = signal
162 ? AbortSignal.any([signal, this.#abort.signal])
163 : this.#abort.signal
164 readSignal.throwIfAborted()
165 const { entries, index, ...metadata } = this.select(offset, limit)
166 // Capture resident bytes before awaiting a storage read/eviction.
167 const records = entries.map((entry, i) => ({
168 encoded: entry.encoded,
169 index: index + i,
170 }))
171 const loaded = new Map<SealedRange, T[]>()
172 const envelopes: T[] = []
173 try {
174 for (const record of records) {
175 readSignal.throwIfAborted()
176 if (record.encoded !== undefined) {
177 const value = this.codec.parse(JSON.parse(record.encoded))
178 this.codec.validateRead(value, this.entries[record.index].boundary)
179 envelopes.push(value)
180 continue
181 }
182 const range = this.#ranges.find(
183 (r) => record.index >= r.start && record.index < r.start + r.count
184 )
185 if (!range) throw new Error('Missing sealed range index')
186 let values = loaded.get(range)
187 if (!values) {
188 const bytes = await this.options.store.get(range.key, readSignal)
189 if (digest(bytes) !== range.checksum)
190 throw new Error('Sealed range checksum mismatch')
191 const text = Buffer.from(bytes).toString('utf8')
192 if (!text.endsWith('\n')) throw new Error('Truncated sealed range')
193 values = text
194 .slice(0, -1)
195 .split('\n')
196 .map((line) => this.codec.parse(JSON.parse(line)))
197 if (values.length !== range.count)
198 throw new Error('Invalid sealed range count')
199 for (let i = 0; i < values.length; i++) {
200 this.codec.validateRead(
201 values[i],
202 this.entries[range.start + i].boundary
203 )
204 }
205 loaded.set(range, values)
206 }
207 envelopes.push(values[record.index - range.start])
208 }
209 readSignal.throwIfAborted()
210 return { ...metadata, envelopes }
211 } catch (error) {
212 signal?.throwIfAborted()
213 throw new LogStorageError(
214 'Sealed shape range unavailable; refetch required',
215 { cause: error }
216 )
217 }
218 }
219 override close(): void {
220 if (this.#stopped) return
221 this.#stopped = true
222 this.#abort.abort(new Error('Shape log stopped'))
223 super.close()
224 this.#disposal = this.#pending
225 .catch(() => {})
226 .then(async () => {
227 // Include attempted keys: a network failure may follow a successful put.
228 const results = await Promise.allSettled(
229 [...this.#attemptedKeys].map((key) => this.options.store.delete(key))
230 )
231 const errors = results
232 .filter((r): r is PromiseRejectedResult => r.status === 'rejected')
233 .map((r) => r.reason)
234 if (errors.length)
235 throw new AggregateError(errors, 'Shape object cleanup failed')
236 })
237 void this.#disposal.catch(() => {})
238 }
239}
240export class ObjectShapeLog extends ObjectJsonLog<Envelope> {
241 constructor(options: ObjectLogOptions) {
242 super(options, shapeLogCodec)
243 }
244}
245
246function digest(bytes: Uint8Array): string {
247 return createHash('sha256').update(bytes).digest('hex')
248}
249function asError(error: unknown): Error {
250 return error instanceof Error ? error : new Error(String(error))
251}