Open History to see the last commit
1import { compareSequence, parseEnvelope, ShapeProtocolError } from './index'
2import type { Envelope, Sequence } from './index'
3
4export interface Checkpoint {
5 /** Durable Streams response-end offset. Not a sequence or a WAL LSN. */
6 offset: string
7 cursor?: string
8}
9
10export interface ConsumerState {
11 appliedSeq: Sequence
12 ready: boolean
13 checkpoint: Checkpoint
14}
15
16/**
17 * One consumer per handle. A failed batch keeps its earlier byte checkpoint,
18 * while successfully applied logical events are suppressed on replay.
19 */
20export class EnvelopeConsumer {
21 #state: ConsumerState
22 #busy = false
23
24 constructor(state?: ConsumerState) {
25 this.#state = state
26 ? { ...state, checkpoint: { ...state.checkpoint } }
27 : { appliedSeq: '0', ready: false, checkpoint: { offset: '-1' } }
28 }
29
30 get state(): ConsumerState {
31 return { ...this.#state, checkpoint: { ...this.#state.checkpoint } }
32 }
33
34 async consume(
35 batch: { items: readonly unknown[]; offset: string; cursor?: string },
36 apply: (envelope: Envelope) => Promise<void>
37 ): Promise<void> {
38 if (this.#busy)
39 throw new ShapeProtocolError('Concurrent envelope consumption')
40 this.#busy = true
41 try {
42 const envelopes = batch.items.map(parseEnvelope)
43 for (const envelope of envelopes) {
44 if (compareSequence(envelope.seq, this.#state.appliedSeq) <= 0) continue
45 if (
46 BigInt(envelope.seq) !==
47 BigInt(this.#state.appliedSeq) + BigInt(1)
48 ) {
49 throw new ShapeProtocolError('Gap in shape envelope sequence')
50 }
51 if (
52 envelope.kind === 'initializing' &&
53 this.#state.appliedSeq !== '0'
54 ) {
55 throw new ShapeProtocolError(
56 'Initialization inside an existing history'
57 )
58 }
59 if (
60 this.#state.appliedSeq === '0' &&
61 envelope.kind !== 'initializing'
62 ) {
63 throw new ShapeProtocolError('History must start with initialization')
64 }
65 if (envelope.kind === 'snapshot-chunk' && this.#state.ready) {
66 throw new ShapeProtocolError(
67 'Snapshot chunk after baseline completion'
68 )
69 }
70 if (envelope.kind === 'snapshot-complete' && this.#state.ready) {
71 throw new ShapeProtocolError('Repeated baseline completion')
72 }
73 if (
74 (envelope.kind === 'publication' || envelope.kind === 'progress') &&
75 !this.#state.ready
76 ) {
77 throw new ShapeProtocolError(
78 'Live evidence before baseline completion'
79 )
80 }
81 if (
82 'coveredSeq' in envelope &&
83 envelope.coveredSeq !== this.#state.appliedSeq
84 ) {
85 throw new ShapeProtocolError(
86 'Evidence must cover the preceding installed boundary'
87 )
88 }
89 await apply(envelope)
90 this.#state.appliedSeq = envelope.seq
91 if (envelope.kind === 'snapshot-complete') this.#state.ready = true
92 }
93 this.#state.checkpoint = { offset: batch.offset, cursor: batch.cursor }
94 } finally {
95 this.#busy = false
96 }
97 }
98}