@pgxsinkit/client 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
@@ -0,0 +1,158 @@
1
+ import type { StreamEnvelope } from "@pgxsinkit/contracts";
2
+
3
+ import { readShapeStream, STREAM_START, type ShapeStreamSubscription, type StreamSourceOptions } from "./stream-source";
4
+
5
+ /** One shape a group follows: where to read it, and where to resume. */
6
+ export interface GroupShapeSpec {
7
+ /** Absolute URL of the stream through the edge. */
8
+ url: string;
9
+ /** Resume position; {@link STREAM_START} for a new subscription. */
10
+ offset?: string;
11
+ }
12
+
13
+ /** One delivery, tagged with the shape it came from. */
14
+ export interface ShapeGroupBatch {
15
+ /** The group-local shape name — the engine's per-shape key. */
16
+ shape: string;
17
+ envelopes: readonly StreamEnvelope[];
18
+ /** The offset that acknowledges these envelopes on this shape's stream. */
19
+ offset: string;
20
+ /** Whether this shape has delivered everything the server held when it answered. */
21
+ upToDate: boolean;
22
+ }
23
+
24
+ export interface ShapeGroupOptions {
25
+ shapes: Record<string, GroupShapeSpec>;
26
+ token: StreamSourceOptions["token"];
27
+ onTokenRejected?: StreamSourceOptions["onTokenRejected"];
28
+ live?: boolean;
29
+ fetch?: typeof fetch;
30
+ signal?: AbortSignal;
31
+ /**
32
+ * One shape's read ENDED — `null` for a normal end, an error for a read that died mid-session.
33
+ *
34
+ * Forwarded straight from {@link readShapeStream}'s `onEnd`, and never fired for a stream this
35
+ * group closed itself: `unsubscribeAll` is the caller's own instruction, not a condition to
36
+ * recover from. See `readShapeStream` for why a consumer that ignores this goes permanently quiet
37
+ * instead of failing.
38
+ */
39
+ onStreamEnd?: (shape: string, error: Error | null) => void;
40
+ }
41
+
42
+ /**
43
+ * Run K shape streams as one group.
44
+ *
45
+ * This layer is **ours permanently**, not a bridge to something (ADR-0055 decision 10):
46
+ * `@durable-streams/client` reads one stream and has no multi-stream coordinator, so the K-streams
47
+ * side of decision 4 has to exist either way. What it deliberately does NOT do is imitate Electric's
48
+ * `MultiShapeStream` — it hands back envelopes and per-stream offsets, which is what the native path
49
+ * actually has, rather than reshaping them into a wire format we no longer speak.
50
+ *
51
+ * **Delivery is serialized.** K streams arrive concurrently, but the subscriber is the apply path,
52
+ * whose inbox and commit queue assume one batch at a time. Rather than push that assumption onto
53
+ * every caller, the group chains deliveries: batches are handed over in arrival order, one at a
54
+ * time, and a slow subscriber exerts backpressure on every stream behind it. Per-shape ordering is
55
+ * preserved because each stream's own reader is sequential.
56
+ */
57
+ export function createShapeGroup(options: ShapeGroupOptions) {
58
+ const names = Object.keys(options.shapes);
59
+ const caughtUp = new Set<string>();
60
+ const subscriptions = new Map<string, ShapeStreamSubscription>();
61
+ let closed = false;
62
+ let deliver: (batch: ShapeGroupBatch) => void | Promise<void> = () => {};
63
+ // The serialization chain. Every batch appends to it, so deliveries never overlap regardless of
64
+ // how many streams answer at once.
65
+ let queue: Promise<void> = Promise.resolve();
66
+
67
+ function closeEveryStream(): void {
68
+ closed = true;
69
+ for (const subscription of subscriptions.values()) {
70
+ subscription.close();
71
+ }
72
+ subscriptions.clear();
73
+ }
74
+
75
+ async function openEveryStream(): Promise<void> {
76
+ await Promise.all(
77
+ names.map(async (shape) => {
78
+ const spec = options.shapes[shape]!;
79
+ const subscription = await readShapeStream(
80
+ {
81
+ url: spec.url,
82
+ offset: spec.offset ?? STREAM_START,
83
+ token: options.token,
84
+ live: options.live ?? true,
85
+ ...(options.onTokenRejected ? { onTokenRejected: options.onTokenRejected } : {}),
86
+ ...(options.fetch ? { fetch: options.fetch } : {}),
87
+ ...(options.signal ? { signal: options.signal } : {}),
88
+ },
89
+ (batch) => {
90
+ if (closed) return;
91
+ if (batch.upToDate) caughtUp.add(shape);
92
+ queue = queue.then(() =>
93
+ closed
94
+ ? undefined
95
+ : deliver({ shape, envelopes: batch.envelopes, offset: batch.offset, upToDate: batch.upToDate }),
96
+ );
97
+ return queue;
98
+ },
99
+ (error) => {
100
+ // `closed` here is OUR teardown, not the stream's: a group that closed its streams
101
+ // asked for exactly this, and reporting it would send the caller chasing a recovery.
102
+ if (closed) return;
103
+ options.onStreamEnd?.(shape, error);
104
+ },
105
+ );
106
+ if (closed) {
107
+ subscription.close();
108
+ return;
109
+ }
110
+ subscriptions.set(shape, subscription);
111
+ }),
112
+ );
113
+ }
114
+
115
+ return {
116
+ /**
117
+ * `true` once **every** shape in the group has reported up-to-date at least once — the group
118
+ * catch-up alignment of ADR-0031, which the native path inherits unchanged.
119
+ *
120
+ * Latching, not instantaneous: a live stream that later has new data to deliver has not stopped
121
+ * being caught up, and the boot gate that reads this must not reopen once it has closed.
122
+ */
123
+ get isUpToDate(): boolean {
124
+ return caughtUp.size === names.length;
125
+ },
126
+
127
+ /** Which shapes have not yet caught up — the boot rail's answer to "what are we waiting on?". */
128
+ get pending(): string[] {
129
+ return names.filter((name) => !caughtUp.has(name));
130
+ },
131
+
132
+ subscribe(onBatch: (batch: ShapeGroupBatch) => void | Promise<void>): void {
133
+ deliver = onBatch;
134
+ },
135
+
136
+ /**
137
+ * Open every stream. Resolves once each has produced its first response.
138
+ *
139
+ * A start that FAILS closes whatever it managed to open. K streams open concurrently, so one
140
+ * refusing leaves the others reading a group the caller is about to discard — and since the
141
+ * caller's answer to a failed open is another attempt (`startCircuitsSync`'s restart ladder),
142
+ * every attempt would strand another live reader. The group is spent either way: `closed` latches,
143
+ * and a stream still resolving its first response finds it set and closes itself below.
144
+ */
145
+ async start(): Promise<void> {
146
+ try {
147
+ await openEveryStream();
148
+ } catch (error) {
149
+ closeEveryStream();
150
+ throw error;
151
+ }
152
+ },
153
+
154
+ unsubscribeAll: closeEveryStream,
155
+ };
156
+ }
157
+
158
+ export type ShapeGroup = ReturnType<typeof createShapeGroup>;
@@ -0,0 +1,225 @@
1
+ import type { ChangeLike } from "./envelope-to-change";
2
+
3
+ /** One delivery held for commit, with the offset that acknowledges it on its own stream. */
4
+ export interface BufferedBatch {
5
+ changes: ChangeLike[];
6
+ offset: string;
7
+ }
8
+
9
+ /**
10
+ * The staging buffer between K durable-streams subscriptions and the applier — the offset-keyed
11
+ * successor to the LSN-keyed `ShapeInbox` (ADR-0056).
12
+ *
13
+ * Three things it deliberately no longer has, each because the reason for it was Electric-shaped:
14
+ *
15
+ * **No commit floor.** ADR-0031's floor existed to work around a *cached catch-up body* asserting a
16
+ * stale `global_last_seen_lsn`: a quiet shape's cacheable response could claim a watermark captured
17
+ * before a busy sibling's writes, holding delivered changes buffered until that shape's first live
18
+ * poll. Durable-streams carries up-to-date as a **response header on a live request**, and returns
19
+ * `204` with it set on every long-poll timeout, so a quiet shape re-asserts freshness each cycle.
20
+ * The failure mode the floor compensated for cannot occur, so the floor is deleted rather than
21
+ * ported.
22
+ *
23
+ * **No cross-shape position comparison.** Offsets are per-stream and, per the protocol, comparable
24
+ * only within a stream. So the commit gate is not a `min` over positions but a predicate over
25
+ * reports: commit when **every** shape's most recent response asserted up-to-date. That is the same
26
+ * happens-before argument ADR-0056 makes for alignment, applied per commit — with the caveat
27
+ * {@link StreamInbox.isGroupUpToDate} states: it is a complete argument at alignment, and in the live
28
+ * steady state it bounds cross-shape tearing to two responses' inter-arrival rather than excluding
29
+ * it (`docs/backlog/0014-cross-stream-commit-fence.md`).
30
+ *
31
+ * **No snapshot-acceptance flag.** It existed because a re-snapshot's rows floored to LSN 0 while
32
+ * the frontier might already sit high. A reset here rewinds the applied offset to nothing, and the
33
+ * re-snapshot arrives at real offsets above it, so the problem does not arise.
34
+ */
35
+ export class StreamInbox {
36
+ /** Per shape: batches held for the next commit, in arrival order (which is stream order). */
37
+ private readonly batches = new Map<string, BufferedBatch[]>();
38
+ /**
39
+ * Per shape: the offset already applied and persisted. `null` until the first commit.
40
+ *
41
+ * The dedup threshold and the resume token are **the same value** (ADR-0056 decision 1), rather
42
+ * than an LSN frontier plus an offset that could disagree.
43
+ */
44
+ private readonly appliedOffsets = new Map<string, string | null>();
45
+ /** Per shape: whether its MOST RECENT response asserted up-to-date. The commit gate reads this. */
46
+ private readonly currentlyUpToDate = new Map<string, boolean>();
47
+ /** Per shape: whether it has EVER reported up-to-date since registration/reset. Boot alignment. */
48
+ private readonly reportedUpToDate = new Map<string, boolean>();
49
+ /** Per shape: reset epoch, so an ack from a commit that peeked before a must-refetch no-ops. */
50
+ private readonly epochs = new Map<string, number>();
51
+ /** Whether the one-time boot alignment has run for this registration/reset generation. */
52
+ private alignedOnce = false;
53
+
54
+ constructor(shapeNames: Iterable<string>) {
55
+ for (const shapeName of shapeNames) {
56
+ this.batches.set(shapeName, []);
57
+ this.appliedOffsets.set(shapeName, null);
58
+ this.currentlyUpToDate.set(shapeName, false);
59
+ this.reportedUpToDate.set(shapeName, false);
60
+ this.epochs.set(shapeName, 0);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Buffer one delivery.
66
+ *
67
+ * A batch at or below the applied offset is already applied and dropped. The comparison is
68
+ * lexicographic, which the protocol explicitly sanctions **within a stream** (offsets are opaque
69
+ * but lexicographically sortable and strictly increasing) and equally explicitly does not sanction
70
+ * across streams — which is why nothing here ever compares two shapes' offsets.
71
+ */
72
+ ingestBatch(shapeName: string, changes: ChangeLike[], offset: string, upToDate: boolean): void {
73
+ this.currentlyUpToDate.set(shapeName, upToDate);
74
+ if (upToDate) this.reportedUpToDate.set(shapeName, true);
75
+
76
+ const applied = this.appliedOffsets.get(shapeName) ?? null;
77
+ if (applied !== null && offset <= applied) return;
78
+
79
+ // An up-to-date response with no envelopes still advances the position — that is what a `204`
80
+ // long-poll timeout is — so it is buffered rather than discarded, and the empty batch carries the
81
+ // offset forward on the next commit.
82
+ this.batches.get(shapeName)?.push({ changes, offset });
83
+ }
84
+
85
+ /**
86
+ * The commit gate: every shape's most recent response asserted up-to-date.
87
+ *
88
+ * This is the whole steady-state condition, and it is stronger than it looks in one direction and
89
+ * weaker in another. Stronger: a shape mid-catch-up reports `false`, so a group never commits while
90
+ * any member is still draining backfill, and at alignment the whole held batch commits together.
91
+ * Weaker: once caught up, every shape's flag is LATCHED from its last completed response while its
92
+ * next long poll sits parked — a `204` timeout carries up-to-date too — so this predicate is
93
+ * effectively always true and each delivery commits at once. Two streams carrying halves of one
94
+ * server transaction are answered by two separate polls, so the client can apply one half before
95
+ * the other arrives; the window is their inter-arrival. Nothing here can close that — the engine's
96
+ * per-stream appends carry no cross-stream fence — so it is recorded rather than papered over
97
+ * (`docs/backlog/0014-cross-stream-commit-fence.md`).
98
+ */
99
+ isGroupUpToDate(): boolean {
100
+ for (const upToDate of this.currentlyUpToDate.values()) {
101
+ if (!upToDate) return false;
102
+ }
103
+ return true;
104
+ }
105
+
106
+ /** Whether every shape has reported up-to-date at least once — boot alignment's precondition. */
107
+ everyShapeReported(): boolean {
108
+ for (const reported of this.reportedUpToDate.values()) {
109
+ if (!reported) return false;
110
+ }
111
+ return true;
112
+ }
113
+
114
+ /**
115
+ * Whether the one-time boot alignment still has to run. Alignment additionally requires the engine
116
+ * barrier (ADR-0056 decision 3) — `pendingFlips > 0` with every stream up-to-date is a computed
117
+ * revocation the engine has not yet delivered, and a boot that claimed consistency there would
118
+ * present a store missing an eviction.
119
+ */
120
+ needsAlignment(): boolean {
121
+ return !this.alignedOnce;
122
+ }
123
+
124
+ /** Record that the barrier was satisfied and the group aligned. One-time per reset generation. */
125
+ markAligned(): void {
126
+ this.alignedOnce = true;
127
+ }
128
+
129
+ hasBufferedChanges(): boolean {
130
+ for (const held of this.batches.values()) {
131
+ for (const batch of held) {
132
+ if (batch.changes.length > 0) return true;
133
+ }
134
+ }
135
+ return false;
136
+ }
137
+
138
+ /** Whether any shape holds a batch at all, including the empty position-carrying ones. */
139
+ hasBufferedBatches(): boolean {
140
+ for (const held of this.batches.values()) {
141
+ if (held.length > 0) return true;
142
+ }
143
+ return false;
144
+ }
145
+
146
+ epochFor(shapeName: string): number {
147
+ return this.epochs.get(shapeName) ?? 0;
148
+ }
149
+
150
+ /** Snapshot every shape's epoch at peek time, to be handed back to {@link ackAll}. */
151
+ snapshotEpochs(): Map<string, number> {
152
+ return new Map([...this.epochs.keys()].map((shapeName) => [shapeName, this.epochFor(shapeName)]));
153
+ }
154
+
155
+ /**
156
+ * Peek — without removing — everything held, per shape, in stream order.
157
+ *
158
+ * There is no target position to peek up to. The gate is "every shape has drained", so what is
159
+ * held IS the complete unit: a partial peek could only ever split a batch the server sent whole.
160
+ */
161
+ peekAll(): Map<string, ChangeLike[]> {
162
+ const peeked = new Map<string, ChangeLike[]>();
163
+ for (const [shapeName, held] of this.batches.entries()) {
164
+ peeked.set(
165
+ shapeName,
166
+ held.flatMap((batch) => batch.changes),
167
+ );
168
+ }
169
+ return peeked;
170
+ }
171
+
172
+ /**
173
+ * The offset each shape would resume from if the currently-held batches were committed — the last
174
+ * buffered batch's offset, or the already-applied one where nothing is held.
175
+ *
176
+ * Persisted in the SAME transaction as the rows it acknowledges. Persisted ahead, a crash loses
177
+ * the envelopes in between; persisted behind, they are re-delivered and re-applied. Only the
178
+ * second is survivable.
179
+ */
180
+ pendingOffsets(): Map<string, string> {
181
+ const offsets = new Map<string, string>();
182
+ for (const [shapeName, held] of this.batches.entries()) {
183
+ const last = held.length > 0 ? held[held.length - 1]!.offset : null;
184
+ const offset = last ?? this.appliedOffsets.get(shapeName) ?? null;
185
+ if (offset !== null) offsets.set(shapeName, offset);
186
+ }
187
+ return offsets;
188
+ }
189
+
190
+ /**
191
+ * Drop everything peeked and advance each shape's applied offset — call only after the commit that
192
+ * consumed a matching {@link peekAll} succeeded.
193
+ *
194
+ * A shape whose epoch changed since the peek is skipped entirely: a must-refetch landing
195
+ * mid-commit replaced its buffer with post-reset content that this commit never saw, and acking it
196
+ * would discard the rebuild.
197
+ */
198
+ ackAll(epochsAtPeek: Map<string, number>): void {
199
+ for (const [shapeName, held] of this.batches.entries()) {
200
+ const peekEpoch = epochsAtPeek.get(shapeName);
201
+ if (peekEpoch !== undefined && this.epochFor(shapeName) !== peekEpoch) continue;
202
+ const last = held.length > 0 ? held[held.length - 1]!.offset : null;
203
+ if (last !== null) this.appliedOffsets.set(shapeName, last);
204
+ this.batches.set(shapeName, []);
205
+ }
206
+ }
207
+
208
+ /** The offset a shape has applied and persisted, or `null` before its first commit. */
209
+ appliedOffsetFor(shapeName: string): string | null {
210
+ return this.appliedOffsets.get(shapeName) ?? null;
211
+ }
212
+
213
+ /**
214
+ * Reset a shape on must-refetch: drop its buffer, rewind it to the start of its stream, and re-arm
215
+ * the group's alignment so the barrier is consulted again once every shape has re-reported.
216
+ */
217
+ resetShape(shapeName: string): void {
218
+ this.batches.set(shapeName, []);
219
+ this.appliedOffsets.set(shapeName, null);
220
+ this.currentlyUpToDate.set(shapeName, false);
221
+ this.reportedUpToDate.set(shapeName, false);
222
+ this.alignedOnce = false;
223
+ this.epochs.set(shapeName, this.epochFor(shapeName) + 1);
224
+ }
225
+ }
@@ -0,0 +1,191 @@
1
+ import { stream, type StreamErrorHandler } from "@durable-streams/client";
2
+
3
+ import type { StreamEnvelope } from "@pgxsinkit/contracts";
4
+
5
+ /** The resume position of a fresh subscription — the start of the stream. */
6
+ export const STREAM_START = "-1";
7
+
8
+ /** One delivery from a stream, with the position that acknowledges it. */
9
+ export interface StreamBatch {
10
+ envelopes: readonly StreamEnvelope[];
11
+ /**
12
+ * The offset to resume from. Persist it **with** the applied rows in one transaction: persisted
13
+ * ahead, a crash loses the envelopes between; persisted behind, they are re-applied. The apply
14
+ * path is idempotent so the second is survivable and the first is not, which is why this rides
15
+ * the batch rather than being read off the response afterwards.
16
+ */
17
+ offset: string;
18
+ /** Whether the stream has delivered everything it held when the response was generated. */
19
+ upToDate: boolean;
20
+ }
21
+
22
+ export interface StreamSourceOptions {
23
+ /** Absolute URL of the stream, through the edge — never durable-streams directly. */
24
+ url: string;
25
+ /** Where to resume. {@link STREAM_START} for a new subscription. */
26
+ offset?: string;
27
+ /**
28
+ * The current stream token, re-resolved on **every** request rather than captured once.
29
+ *
30
+ * A live subscription outlives its token by design — the ADR-0055 default lifetime is five
31
+ * minutes and a subscription runs for hours — so a token frozen at open would 403 the whole
32
+ * stream at the first TTL boundary. This is the ADR-0013 read-path refresh seam, and
33
+ * `@durable-streams/client` supports it directly: header values may be async thunks, resolved
34
+ * afresh per request.
35
+ */
36
+ token: () => string | Promise<string>;
37
+ /**
38
+ * Called when the edge rejects the current token (401/403). Return a fresh token to retry once
39
+ * with it, or `null` to stop.
40
+ *
41
+ * Returning `null` is the *right* answer for a revoked entitlement, and the reason this hook
42
+ * exists at all rather than a blanket retry — see {@link createTokenRecovery}.
43
+ */
44
+ onTokenRejected?: (status: number) => string | null | Promise<string | null>;
45
+ /** Long-poll the tail after catching up. `false` reads to the tail and stops. */
46
+ live?: boolean;
47
+ signal?: AbortSignal;
48
+ fetch?: typeof fetch;
49
+ }
50
+
51
+ /**
52
+ * The `onError` handler for a read.
53
+ *
54
+ * `@durable-streams/client`'s retry loop has a sharp edge that a naive handler falls straight off.
55
+ * Returning `{}` re-enters `streamInternal` **immediately** — a bare `while (true) { … continue }`
56
+ * with no backoff of its own — while its backoff wrapper deliberately refuses to back off on any
57
+ * 4xx except 429 (`fetch.ts`: client errors "cannot be backed off on"). So `onError: () => ({})`
58
+ * against a persistently-rejected token is a hot spin, not a slow retry.
59
+ *
60
+ * This handler is therefore **stateful and single-shot**: one re-mint per rejection, and if the
61
+ * fresh token is rejected too, it returns undefined and the error propagates. A revoked entitlement
62
+ * must surface as an error the caller can act on — truncate the scope and unsubscribe (ADR-0055
63
+ * decision 6) — not as a stream that spins.
64
+ */
65
+ export function createTokenRecovery(
66
+ onTokenRejected: NonNullable<StreamSourceOptions["onTokenRejected"]>,
67
+ ): StreamErrorHandler {
68
+ let recovering = false;
69
+ return async (error: Error & { status?: number }) => {
70
+ const status = error.status;
71
+ if (status !== 401 && status !== 403) return undefined;
72
+ // The second consecutive rejection is the answer: the token was refreshed and still refused, so
73
+ // this is a revocation, not an expiry.
74
+ if (recovering) return undefined;
75
+
76
+ recovering = true;
77
+ const fresh = await onTokenRejected(status);
78
+ if (fresh == null) return undefined;
79
+ return { headers: { authorization: `Bearer ${fresh}` } };
80
+ };
81
+ }
82
+
83
+ /** A running subscription. `subscribeJson` is backpressure-aware, so a slow apply throttles reads. */
84
+ export interface ShapeStreamSubscription {
85
+ /** Stop reading and release the connection. */
86
+ close(): void;
87
+ }
88
+
89
+ /**
90
+ * Read one Circuits shape stream, yielding envelopes in stream order.
91
+ *
92
+ * Resolves once the first response has arrived (so an immediate auth failure surfaces here rather
93
+ * than silently on a background loop) and hands back a subscription that keeps delivering until
94
+ * closed.
95
+ *
96
+ * `onEnd` is not optional decoration — without it every mid-session stream death is SILENT.
97
+ * `stream()`'s own `onError` option wraps only the OPENING request; every later long-poll goes
98
+ * through the response's internal `fetchNext`, where a non-2xx throws into the body stream's pull,
99
+ * is marked on the response and ends the `subscribeJson` loop. Nothing calls the batch subscriber
100
+ * again and nothing throws at the caller: the stream simply stops, the rows stay, and nobody
101
+ * re-subscribes. The one place that condition is observable is the response's `closed` promise —
102
+ * it REJECTS on a terminal read error (a `403` past a re-mint, a `404`/`410` on an evicted stream,
103
+ * a lost connection) and RESOLVES on a normal end (`live: false` reaching up-to-date,
104
+ * `Stream-Closed`, or our own {@link ShapeStreamSubscription.close}). So `onEnd(null)` means "this
105
+ * read is over and nothing failed"; `onEnd(error)` is the mid-session reset (ADR-0056 decision 7)
106
+ * that a caller must answer with a re-subscribe.
107
+ *
108
+ * ORDERING GUARANTEE: `onEnd(null)` is called only AFTER `onBatch` has been handed the batch that
109
+ * ends the read (the up-to-date batch of a `live: false` read; the `Stream-Closed` batch of any
110
+ * read). `closed` alone does not give that — it settles when the transport's fetch loop is done,
111
+ * which for a non-live read can be before the subscriber has consumed the final response — so the
112
+ * normal end is reported off the terminal batch, and a caller may close on `onEnd` without losing it.
113
+ *
114
+ * The transport only. Everything above it — the fold, apply modes, the boot gate — stays
115
+ * pgxsinkit's, which is ADR-0009's precedent applied to a new substrate: keep the transport,
116
+ * internalize the semantics.
117
+ */
118
+ export async function readShapeStream(
119
+ options: StreamSourceOptions,
120
+ onBatch: (batch: StreamBatch) => void | Promise<void>,
121
+ onEnd?: (error: Error | null) => void,
122
+ ): Promise<ShapeStreamSubscription> {
123
+ const response = await stream<StreamEnvelope>({
124
+ url: options.url,
125
+ offset: options.offset ?? STREAM_START,
126
+ live: options.live ?? true,
127
+ headers: { authorization: async () => `Bearer ${await options.token()}` },
128
+ ...(options.onTokenRejected ? { onError: createTokenRecovery(options.onTokenRejected) } : {}),
129
+ ...(options.signal ? { signal: options.signal } : {}),
130
+ ...(options.fetch ? { fetch: options.fetch } : {}),
131
+ });
132
+
133
+ const live = options.live ?? true;
134
+
135
+ // Our OWN close is not an end worth reporting: the caller asked for it, and a group tearing its
136
+ // streams down would otherwise hear K "the stream ended" reports and try to recover from a stop it
137
+ // ordered. `cancel()` resolves `closed` rather than rejecting it, so this suppresses a normal end;
138
+ // the flag also covers the race where a close lands while a read error is already in flight.
139
+ let closedByCaller = false;
140
+ let endReported = false;
141
+ const reportEnd = (error: Error | null): void => {
142
+ if (endReported || closedByCaller) return;
143
+ endReported = true;
144
+ onEnd?.(error);
145
+ };
146
+
147
+ const unsubscribe = response.subscribeJson(async (batch) => {
148
+ await onBatch({
149
+ // The server flattens arrays onto the stream (PROTOCOL.md §9.1.2), so a batch's items are
150
+ // already individual envelopes rather than the arrays a producer appended.
151
+ envelopes: batch.items,
152
+ offset: String(batch.offset),
153
+ // `batch.upToDate`, NOT `response.upToDate`. They answer the same question at different times:
154
+ // the batch's flag describes THIS batch ("ends at the current end of the stream"), while the
155
+ // response's is documented as updated *after* each chunk is delivered to the consumer — i.e.
156
+ // after this callback returns. Reading the response's here yields the PREVIOUS batch's answer,
157
+ // which on the first catch-up batch is always `false`. Nothing downstream can recover from
158
+ // that: the commit gate waits for every shape to report up-to-date, so a group whose first
159
+ // batch is misreported never commits and `ready` never resolves, with the rows sitting in the
160
+ // inbox and no error anywhere.
161
+ upToDate: batch.upToDate,
162
+ });
163
+ // THE NORMAL END IS REPORTED HERE, off the batch that ends the read — never off `closed`. The
164
+ // transport settles `closed` when its FETCH loop is done, and for a non-live read whose first
165
+ // response is already up-to-date that is inside `stream()` itself: the response is enqueued and
166
+ // the loop closed in the same tick, BEFORE any subscriber has consumed it. An `onEnd(null)` fired
167
+ // off that moment says "over, nothing failed" while the final batch is still queued, and a caller
168
+ // that (reasonably) closes on it aborts the subscriber loop with the batch undelivered — a
169
+ // `live: false` read of a populated stream then yields nothing, silently. The batch that ends a
170
+ // read is the transport's own stopping rule: a non-live read stops at its first up-to-date
171
+ // response, and any read stops at `Stream-Closed`.
172
+ if (batch.streamClosed === true || (!live && batch.upToDate)) reportEnd(null);
173
+ });
174
+
175
+ void response.closed.then(
176
+ () => {
177
+ // A normal transport close is answered by the terminal batch above, which is already queued
178
+ // for the subscriber. The one normal close with NOTHING queued is the caller's own abort
179
+ // signal, and that one would otherwise wait forever.
180
+ if (options.signal?.aborted) reportEnd(null);
181
+ },
182
+ (error: unknown) => reportEnd(error instanceof Error ? error : new Error(String(error))),
183
+ );
184
+
185
+ return {
186
+ close: () => {
187
+ closedByCaller = true;
188
+ unsubscribe();
189
+ },
190
+ };
191
+ }