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

shape-log.ts

176 lines5.5 KB

1import {
2 parseEnvelope,
3 type Envelope,
4 type Sequence,
5} from '@neon/realtime-electric-protocol'
6​
7export interface LogBoundary {
8 offset: string
9 afterSeq: Sequence
10 baselineComplete: boolean
12export interface LogRead<T = Envelope> {
13 boundary: LogBoundary
14 end: LogBoundary
15 envelopes: T[]
16 atTail: boolean
18export interface JsonLog<T> {
19 readonly head: LogBoundary
20 readonly disposed?: Promise<void>
21 append(value: T): LogBoundary
22 inspect(offset: string, limit?: number): Omit<LogRead<T>, 'envelopes'>
23 read(
24 offset: string,
25 limit?: number,
26 signal?: AbortSignal
27 ): LogRead<T> | Promise<LogRead<T>>
28 wait(offset: string, signal: AbortSignal, timeoutMs: number): Promise<void>
29 close(): void
31export type ShapeLog = JsonLog<Envelope>
32​
33export class InvalidLogOffsetError extends Error {}
34export class LogStorageError extends Error {}
35​
36export interface LogEntry {
37 boundary: LogBoundary
38 /** Removed only after the storage backend has durably accepted these bytes. */
39 encoded?: string
40 bytes: number
42export interface LogSelection {
43 index: number
44 entries: LogEntry[]
45 boundary: LogBoundary
46 end: LogBoundary
47 atTail: boolean
49​
50/** Validation and shape evidence, independent of storage and HTTP framing. */
51export interface LogCodec<T> {
52 parse(value: unknown): T
53 advance(value: T, previous: LogBoundary): Omit<LogBoundary, 'offset'>
54 validateRead(value: T, boundary: LogBoundary): void
56​
57export const shapeLogCodec: LogCodec<Envelope> = {
58 parse: parseEnvelope,
59 advance(envelope, previous) {
60 if (BigInt(envelope.seq) !== BigInt(previous.afterSeq) + 1n)
61 throw new Error('Shape append sequence is not contiguous')
62 if (
63 (envelope.kind === 'progress' || envelope.kind === 'snapshot-complete') &&
64 BigInt(envelope.coveredSeq) > BigInt(previous.afterSeq)
65 )
66 throw new Error('Shape evidence precedes covered data')
67 return {
68 afterSeq: envelope.seq,
69 baselineComplete:
70 previous.baselineComplete || envelope.kind === 'snapshot-complete',
71 }
72 },
73 validateRead(value, boundary) {
74 if (value.seq !== boundary.afterSeq)
75 throw new Error('Sealed range sequence mismatch')
76 },
78​
79/** Shared byte index and waiters. The codec adds shape sequence/evidence checks. */
80export abstract class IndexedJsonLog<T> implements JsonLog<T> {
81 constructor(protected readonly codec: LogCodec<T>) {}
82 protected readonly entries: LogEntry[] = []
83 readonly #index = new Map<string, number>([['-1', 0]])
84 readonly #waiters = new Set<() => void>()
85 #bytes = 0n
86 #closed = false
87 readonly initial: Readonly<LogBoundary> = Object.freeze({
88 offset: '-1',
89 afterSeq: '0',
90 baselineComplete: false,
91 })
92​
93 get head(): LogBoundary {
94 return { ...(this.entries.at(-1)?.boundary ?? this.initial) }
95 }
96 append(value: T): LogBoundary {
97 if (this.#closed) throw new Error('Shape log is closed')
98 const parsed = this.codec.parse(value)
99 const metadata = this.codec.advance(parsed, this.head)
100 const encoded = JSON.stringify(parsed)
101 const bytes = Buffer.byteLength(encoded) + 1
102 this.#bytes += BigInt(bytes)
103 const boundary: LogBoundary = {
104 offset: `0000000000000000_${String(this.#bytes).padStart(16, '0')}`,
105 ...metadata,
106 }
107 this.entries.push({ encoded, bytes, boundary })
108 this.#index.set(boundary.offset, this.entries.length)
109 this.#wake()
110 return { ...boundary }
111 }
112 protected select(offset: string, limit = 128): LogSelection {
113 if (!Number.isInteger(limit) || limit < 1)
114 throw new Error('Read limit must be a positive integer')
115 const index = this.#index.get(offset)
116 if (index === undefined)
117 throw new InvalidLogOffsetError('Invalid shape offset')
118 const entries = this.entries.slice(index, index + limit)
119 const boundary = index ? this.entries[index - 1].boundary : this.initial
120 return {
121 index,
122 entries,
123 boundary: { ...boundary },
124 end: { ...(entries.at(-1)?.boundary ?? boundary) },
125 atTail: index + entries.length === this.entries.length,
126 }
127 }
128 inspect(offset: string, limit?: number): Omit<LogRead<T>, 'envelopes'> {
129 const { entries: _, index: __, ...metadata } = this.select(offset, limit)
130 return metadata
131 }
132 abstract read(
133 offset: string,
134 limit?: number,
135 signal?: AbortSignal
136 ): LogRead<T> | Promise<LogRead<T>>
137 async wait(
138 offset: string,
139 signal: AbortSignal,
140 timeoutMs: number
141 ): Promise<void> {
142 signal.throwIfAborted()
143 if (this.head.offset !== offset || this.#closed) return
144 await new Promise<void>((resolve, reject) => {
145 let timer: ReturnType<typeof setTimeout>
146 const finish = (error?: unknown) => {
147 clearTimeout(timer)
148 signal.removeEventListener('abort', abort)
149 this.#waiters.delete(done)
150 if (error !== undefined) reject(error)
151 else resolve()
152 }
153 const done = () => finish()
154 const abort = () => finish(signal.reason ?? new Error('Read aborted'))
155 this.#waiters.add(done)
156 signal.addEventListener('abort', abort, { once: true })
157 timer = setTimeout(done, timeoutMs)
158 if (signal.aborted) abort()
159 else if (this.head.offset !== offset || this.#closed) done()
160 })
161 }
162 close(): void {
163 this.#closed = true
164 this.#wake()
165 }
166 #wake(): void {
167 for (const wake of [...this.#waiters]) wake()
168 }
170​
171/** Shape-specialized index retained for existing custom storage implementations. */
172export abstract class IndexedShapeLog extends IndexedJsonLog<Envelope> {
173 constructor() {
174 super(shapeLogCodec)
175 }