@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,77 @@
1
+ import type { StreamEnvelope } from "@pgxsinkit/contracts";
2
+ import { type StreamSourceOptions } from "./stream-source";
3
+ /** One shape a group follows: where to read it, and where to resume. */
4
+ export interface GroupShapeSpec {
5
+ /** Absolute URL of the stream through the edge. */
6
+ url: string;
7
+ /** Resume position; {@link STREAM_START} for a new subscription. */
8
+ offset?: string;
9
+ }
10
+ /** One delivery, tagged with the shape it came from. */
11
+ export interface ShapeGroupBatch {
12
+ /** The group-local shape name — the engine's per-shape key. */
13
+ shape: string;
14
+ envelopes: readonly StreamEnvelope[];
15
+ /** The offset that acknowledges these envelopes on this shape's stream. */
16
+ offset: string;
17
+ /** Whether this shape has delivered everything the server held when it answered. */
18
+ upToDate: boolean;
19
+ }
20
+ export interface ShapeGroupOptions {
21
+ shapes: Record<string, GroupShapeSpec>;
22
+ token: StreamSourceOptions["token"];
23
+ onTokenRejected?: StreamSourceOptions["onTokenRejected"];
24
+ live?: boolean;
25
+ fetch?: typeof fetch;
26
+ signal?: AbortSignal;
27
+ /**
28
+ * One shape's read ENDED — `null` for a normal end, an error for a read that died mid-session.
29
+ *
30
+ * Forwarded straight from {@link readShapeStream}'s `onEnd`, and never fired for a stream this
31
+ * group closed itself: `unsubscribeAll` is the caller's own instruction, not a condition to
32
+ * recover from. See `readShapeStream` for why a consumer that ignores this goes permanently quiet
33
+ * instead of failing.
34
+ */
35
+ onStreamEnd?: (shape: string, error: Error | null) => void;
36
+ }
37
+ /**
38
+ * Run K shape streams as one group.
39
+ *
40
+ * This layer is **ours permanently**, not a bridge to something (ADR-0055 decision 10):
41
+ * `@durable-streams/client` reads one stream and has no multi-stream coordinator, so the K-streams
42
+ * side of decision 4 has to exist either way. What it deliberately does NOT do is imitate Electric's
43
+ * `MultiShapeStream` — it hands back envelopes and per-stream offsets, which is what the native path
44
+ * actually has, rather than reshaping them into a wire format we no longer speak.
45
+ *
46
+ * **Delivery is serialized.** K streams arrive concurrently, but the subscriber is the apply path,
47
+ * whose inbox and commit queue assume one batch at a time. Rather than push that assumption onto
48
+ * every caller, the group chains deliveries: batches are handed over in arrival order, one at a
49
+ * time, and a slow subscriber exerts backpressure on every stream behind it. Per-shape ordering is
50
+ * preserved because each stream's own reader is sequential.
51
+ */
52
+ export declare function createShapeGroup(options: ShapeGroupOptions): {
53
+ /**
54
+ * `true` once **every** shape in the group has reported up-to-date at least once — the group
55
+ * catch-up alignment of ADR-0031, which the native path inherits unchanged.
56
+ *
57
+ * Latching, not instantaneous: a live stream that later has new data to deliver has not stopped
58
+ * being caught up, and the boot gate that reads this must not reopen once it has closed.
59
+ */
60
+ readonly isUpToDate: boolean;
61
+ /** Which shapes have not yet caught up — the boot rail's answer to "what are we waiting on?". */
62
+ readonly pending: string[];
63
+ subscribe(onBatch: (batch: ShapeGroupBatch) => void | Promise<void>): void;
64
+ /**
65
+ * Open every stream. Resolves once each has produced its first response.
66
+ *
67
+ * A start that FAILS closes whatever it managed to open. K streams open concurrently, so one
68
+ * refusing leaves the others reading a group the caller is about to discard — and since the
69
+ * caller's answer to a failed open is another attempt (`startCircuitsSync`'s restart ladder),
70
+ * every attempt would strand another live reader. The group is spent either way: `closed` latches,
71
+ * and a stream still resolving its first response finds it set and closes itself below.
72
+ */
73
+ start(): Promise<void>;
74
+ unsubscribeAll: () => void;
75
+ };
76
+ export type ShapeGroup = ReturnType<typeof createShapeGroup>;
77
+ //# sourceMappingURL=shape-group.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shape-group.d.ts","sourceRoot":"","sources":["../../src/circuits/shape-group.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAA+D,KAAK,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAExH,wEAAwE;AACxE,MAAM,WAAW,cAAc;IAC7B,mDAAmD;IACnD,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wDAAwD;AACxD,MAAM,WAAW,eAAe;IAC9B,+DAA+D;IAC/D,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,SAAS,cAAc,EAAE,CAAC;IACrC,2EAA2E;IAC3E,MAAM,EAAE,MAAM,CAAC;IACf,oFAAoF;IACpF,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACvC,KAAK,EAAE,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACpC,eAAe,CAAC,EAAE,mBAAmB,CAAC,iBAAiB,CAAC,CAAC;IACzD,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,CAAC;CAC5D;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB;IA2DvD;;;;;;OAMG;aACC,UAAU,EAAI,OAAO;IAIzB,iGAAiG;aAC7F,OAAO,EAAI,MAAM,EAAE;IAIvB,SAAS,UAAU,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAI1E;;;;;;;;OAQG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAS5B,cAAc,QAvFa,IAAI;EAyFlC;AAED,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC"}
@@ -0,0 +1,126 @@
1
+ import type { ChangeLike } from "./envelope-to-change";
2
+ /** One delivery held for commit, with the offset that acknowledges it on its own stream. */
3
+ export interface BufferedBatch {
4
+ changes: ChangeLike[];
5
+ offset: string;
6
+ }
7
+ /**
8
+ * The staging buffer between K durable-streams subscriptions and the applier — the offset-keyed
9
+ * successor to the LSN-keyed `ShapeInbox` (ADR-0056).
10
+ *
11
+ * Three things it deliberately no longer has, each because the reason for it was Electric-shaped:
12
+ *
13
+ * **No commit floor.** ADR-0031's floor existed to work around a *cached catch-up body* asserting a
14
+ * stale `global_last_seen_lsn`: a quiet shape's cacheable response could claim a watermark captured
15
+ * before a busy sibling's writes, holding delivered changes buffered until that shape's first live
16
+ * poll. Durable-streams carries up-to-date as a **response header on a live request**, and returns
17
+ * `204` with it set on every long-poll timeout, so a quiet shape re-asserts freshness each cycle.
18
+ * The failure mode the floor compensated for cannot occur, so the floor is deleted rather than
19
+ * ported.
20
+ *
21
+ * **No cross-shape position comparison.** Offsets are per-stream and, per the protocol, comparable
22
+ * only within a stream. So the commit gate is not a `min` over positions but a predicate over
23
+ * reports: commit when **every** shape's most recent response asserted up-to-date. That is the same
24
+ * happens-before argument ADR-0056 makes for alignment, applied per commit — with the caveat
25
+ * {@link StreamInbox.isGroupUpToDate} states: it is a complete argument at alignment, and in the live
26
+ * steady state it bounds cross-shape tearing to two responses' inter-arrival rather than excluding
27
+ * it (`docs/backlog/0014-cross-stream-commit-fence.md`).
28
+ *
29
+ * **No snapshot-acceptance flag.** It existed because a re-snapshot's rows floored to LSN 0 while
30
+ * the frontier might already sit high. A reset here rewinds the applied offset to nothing, and the
31
+ * re-snapshot arrives at real offsets above it, so the problem does not arise.
32
+ */
33
+ export declare class StreamInbox {
34
+ /** Per shape: batches held for the next commit, in arrival order (which is stream order). */
35
+ private readonly batches;
36
+ /**
37
+ * Per shape: the offset already applied and persisted. `null` until the first commit.
38
+ *
39
+ * The dedup threshold and the resume token are **the same value** (ADR-0056 decision 1), rather
40
+ * than an LSN frontier plus an offset that could disagree.
41
+ */
42
+ private readonly appliedOffsets;
43
+ /** Per shape: whether its MOST RECENT response asserted up-to-date. The commit gate reads this. */
44
+ private readonly currentlyUpToDate;
45
+ /** Per shape: whether it has EVER reported up-to-date since registration/reset. Boot alignment. */
46
+ private readonly reportedUpToDate;
47
+ /** Per shape: reset epoch, so an ack from a commit that peeked before a must-refetch no-ops. */
48
+ private readonly epochs;
49
+ /** Whether the one-time boot alignment has run for this registration/reset generation. */
50
+ private alignedOnce;
51
+ constructor(shapeNames: Iterable<string>);
52
+ /**
53
+ * Buffer one delivery.
54
+ *
55
+ * A batch at or below the applied offset is already applied and dropped. The comparison is
56
+ * lexicographic, which the protocol explicitly sanctions **within a stream** (offsets are opaque
57
+ * but lexicographically sortable and strictly increasing) and equally explicitly does not sanction
58
+ * across streams — which is why nothing here ever compares two shapes' offsets.
59
+ */
60
+ ingestBatch(shapeName: string, changes: ChangeLike[], offset: string, upToDate: boolean): void;
61
+ /**
62
+ * The commit gate: every shape's most recent response asserted up-to-date.
63
+ *
64
+ * This is the whole steady-state condition, and it is stronger than it looks in one direction and
65
+ * weaker in another. Stronger: a shape mid-catch-up reports `false`, so a group never commits while
66
+ * any member is still draining backfill, and at alignment the whole held batch commits together.
67
+ * Weaker: once caught up, every shape's flag is LATCHED from its last completed response while its
68
+ * next long poll sits parked — a `204` timeout carries up-to-date too — so this predicate is
69
+ * effectively always true and each delivery commits at once. Two streams carrying halves of one
70
+ * server transaction are answered by two separate polls, so the client can apply one half before
71
+ * the other arrives; the window is their inter-arrival. Nothing here can close that — the engine's
72
+ * per-stream appends carry no cross-stream fence — so it is recorded rather than papered over
73
+ * (`docs/backlog/0014-cross-stream-commit-fence.md`).
74
+ */
75
+ isGroupUpToDate(): boolean;
76
+ /** Whether every shape has reported up-to-date at least once — boot alignment's precondition. */
77
+ everyShapeReported(): boolean;
78
+ /**
79
+ * Whether the one-time boot alignment still has to run. Alignment additionally requires the engine
80
+ * barrier (ADR-0056 decision 3) — `pendingFlips > 0` with every stream up-to-date is a computed
81
+ * revocation the engine has not yet delivered, and a boot that claimed consistency there would
82
+ * present a store missing an eviction.
83
+ */
84
+ needsAlignment(): boolean;
85
+ /** Record that the barrier was satisfied and the group aligned. One-time per reset generation. */
86
+ markAligned(): void;
87
+ hasBufferedChanges(): boolean;
88
+ /** Whether any shape holds a batch at all, including the empty position-carrying ones. */
89
+ hasBufferedBatches(): boolean;
90
+ epochFor(shapeName: string): number;
91
+ /** Snapshot every shape's epoch at peek time, to be handed back to {@link ackAll}. */
92
+ snapshotEpochs(): Map<string, number>;
93
+ /**
94
+ * Peek — without removing — everything held, per shape, in stream order.
95
+ *
96
+ * There is no target position to peek up to. The gate is "every shape has drained", so what is
97
+ * held IS the complete unit: a partial peek could only ever split a batch the server sent whole.
98
+ */
99
+ peekAll(): Map<string, ChangeLike[]>;
100
+ /**
101
+ * The offset each shape would resume from if the currently-held batches were committed — the last
102
+ * buffered batch's offset, or the already-applied one where nothing is held.
103
+ *
104
+ * Persisted in the SAME transaction as the rows it acknowledges. Persisted ahead, a crash loses
105
+ * the envelopes in between; persisted behind, they are re-delivered and re-applied. Only the
106
+ * second is survivable.
107
+ */
108
+ pendingOffsets(): Map<string, string>;
109
+ /**
110
+ * Drop everything peeked and advance each shape's applied offset — call only after the commit that
111
+ * consumed a matching {@link peekAll} succeeded.
112
+ *
113
+ * A shape whose epoch changed since the peek is skipped entirely: a must-refetch landing
114
+ * mid-commit replaced its buffer with post-reset content that this commit never saw, and acking it
115
+ * would discard the rebuild.
116
+ */
117
+ ackAll(epochsAtPeek: Map<string, number>): void;
118
+ /** The offset a shape has applied and persisted, or `null` before its first commit. */
119
+ appliedOffsetFor(shapeName: string): string | null;
120
+ /**
121
+ * Reset a shape on must-refetch: drop its buffer, rewind it to the start of its stream, and re-arm
122
+ * the group's alignment so the barrier is consulted again once every shape has re-reported.
123
+ */
124
+ resetShape(shapeName: string): void;
125
+ }
126
+ //# sourceMappingURL=stream-inbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-inbox.d.ts","sourceRoot":"","sources":["../../src/circuits/stream-inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,4FAA4F;AAC5F,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,WAAW;IACtB,6FAA6F;IAC7F,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsC;IAC9D;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAoC;IACnE,mGAAmG;IACnG,OAAO,CAAC,QAAQ,CAAC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1
+ import { type StreamErrorHandler } from "@durable-streams/client";
2
+ import type { StreamEnvelope } from "@pgxsinkit/contracts";
3
+ /** The resume position of a fresh subscription — the start of the stream. */
4
+ export declare const STREAM_START = "-1";
5
+ /** One delivery from a stream, with the position that acknowledges it. */
6
+ export interface StreamBatch {
7
+ envelopes: readonly StreamEnvelope[];
8
+ /**
9
+ * The offset to resume from. Persist it **with** the applied rows in one transaction: persisted
10
+ * ahead, a crash loses the envelopes between; persisted behind, they are re-applied. The apply
11
+ * path is idempotent so the second is survivable and the first is not, which is why this rides
12
+ * the batch rather than being read off the response afterwards.
13
+ */
14
+ offset: string;
15
+ /** Whether the stream has delivered everything it held when the response was generated. */
16
+ upToDate: boolean;
17
+ }
18
+ export interface StreamSourceOptions {
19
+ /** Absolute URL of the stream, through the edge — never durable-streams directly. */
20
+ url: string;
21
+ /** Where to resume. {@link STREAM_START} for a new subscription. */
22
+ offset?: string;
23
+ /**
24
+ * The current stream token, re-resolved on **every** request rather than captured once.
25
+ *
26
+ * A live subscription outlives its token by design — the ADR-0055 default lifetime is five
27
+ * minutes and a subscription runs for hours — so a token frozen at open would 403 the whole
28
+ * stream at the first TTL boundary. This is the ADR-0013 read-path refresh seam, and
29
+ * `@durable-streams/client` supports it directly: header values may be async thunks, resolved
30
+ * afresh per request.
31
+ */
32
+ token: () => string | Promise<string>;
33
+ /**
34
+ * Called when the edge rejects the current token (401/403). Return a fresh token to retry once
35
+ * with it, or `null` to stop.
36
+ *
37
+ * Returning `null` is the *right* answer for a revoked entitlement, and the reason this hook
38
+ * exists at all rather than a blanket retry — see {@link createTokenRecovery}.
39
+ */
40
+ onTokenRejected?: (status: number) => string | null | Promise<string | null>;
41
+ /** Long-poll the tail after catching up. `false` reads to the tail and stops. */
42
+ live?: boolean;
43
+ signal?: AbortSignal;
44
+ fetch?: typeof fetch;
45
+ }
46
+ /**
47
+ * The `onError` handler for a read.
48
+ *
49
+ * `@durable-streams/client`'s retry loop has a sharp edge that a naive handler falls straight off.
50
+ * Returning `{}` re-enters `streamInternal` **immediately** — a bare `while (true) { … continue }`
51
+ * with no backoff of its own — while its backoff wrapper deliberately refuses to back off on any
52
+ * 4xx except 429 (`fetch.ts`: client errors "cannot be backed off on"). So `onError: () => ({})`
53
+ * against a persistently-rejected token is a hot spin, not a slow retry.
54
+ *
55
+ * This handler is therefore **stateful and single-shot**: one re-mint per rejection, and if the
56
+ * fresh token is rejected too, it returns undefined and the error propagates. A revoked entitlement
57
+ * must surface as an error the caller can act on — truncate the scope and unsubscribe (ADR-0055
58
+ * decision 6) — not as a stream that spins.
59
+ */
60
+ export declare function createTokenRecovery(onTokenRejected: NonNullable<StreamSourceOptions["onTokenRejected"]>): StreamErrorHandler;
61
+ /** A running subscription. `subscribeJson` is backpressure-aware, so a slow apply throttles reads. */
62
+ export interface ShapeStreamSubscription {
63
+ /** Stop reading and release the connection. */
64
+ close(): void;
65
+ }
66
+ /**
67
+ * Read one Circuits shape stream, yielding envelopes in stream order.
68
+ *
69
+ * Resolves once the first response has arrived (so an immediate auth failure surfaces here rather
70
+ * than silently on a background loop) and hands back a subscription that keeps delivering until
71
+ * closed.
72
+ *
73
+ * `onEnd` is not optional decoration — without it every mid-session stream death is SILENT.
74
+ * `stream()`'s own `onError` option wraps only the OPENING request; every later long-poll goes
75
+ * through the response's internal `fetchNext`, where a non-2xx throws into the body stream's pull,
76
+ * is marked on the response and ends the `subscribeJson` loop. Nothing calls the batch subscriber
77
+ * again and nothing throws at the caller: the stream simply stops, the rows stay, and nobody
78
+ * re-subscribes. The one place that condition is observable is the response's `closed` promise —
79
+ * it REJECTS on a terminal read error (a `403` past a re-mint, a `404`/`410` on an evicted stream,
80
+ * a lost connection) and RESOLVES on a normal end (`live: false` reaching up-to-date,
81
+ * `Stream-Closed`, or our own {@link ShapeStreamSubscription.close}). So `onEnd(null)` means "this
82
+ * read is over and nothing failed"; `onEnd(error)` is the mid-session reset (ADR-0056 decision 7)
83
+ * that a caller must answer with a re-subscribe.
84
+ *
85
+ * ORDERING GUARANTEE: `onEnd(null)` is called only AFTER `onBatch` has been handed the batch that
86
+ * ends the read (the up-to-date batch of a `live: false` read; the `Stream-Closed` batch of any
87
+ * read). `closed` alone does not give that — it settles when the transport's fetch loop is done,
88
+ * which for a non-live read can be before the subscriber has consumed the final response — so the
89
+ * normal end is reported off the terminal batch, and a caller may close on `onEnd` without losing it.
90
+ *
91
+ * The transport only. Everything above it — the fold, apply modes, the boot gate — stays
92
+ * pgxsinkit's, which is ADR-0009's precedent applied to a new substrate: keep the transport,
93
+ * internalize the semantics.
94
+ */
95
+ export declare function readShapeStream(options: StreamSourceOptions, onBatch: (batch: StreamBatch) => void | Promise<void>, onEnd?: (error: Error | null) => void): Promise<ShapeStreamSubscription>;
96
+ //# sourceMappingURL=stream-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-source.d.ts","sourceRoot":"","sources":["../../src/circuits/stream-source.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,6EAA6E;AAC7E,eAAO,MAAM,YAAY,OAAO,CAAC;AAEjC,0EAA0E;AAC1E,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,SAAS,cAAc,EAAE,CAAC;IACrC;;;;;OAKG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,2FAA2F;IAC3F,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,qFAAqF;IACrF,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;OAQG;IACH,KAAK,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtC;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC7E,iFAAiF;IACjF,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,WAAW,CAAC,mBAAmB,CAAC,iBAAiB,CAAC,CAAC,GACnE,kBAAkB,CAcpB;AAED,sGAAsG;AACtG,MAAM,WAAW,uBAAuB;IACtC,+CAA+C;IAC/C,KAAK,IAAI,IAAI,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EACrD,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,GACpC,OAAO,CAAC,uBAAuB,CAAC,CAqElC"}
@@ -0,0 +1,143 @@
1
+ import type { PredicateValue } from "@pgxsinkit/contracts";
2
+ import type { ConvergenceBarrier } from "./sync-engine";
3
+ /**
4
+ * One shape the client wants to follow — by declared identity, and nothing else.
5
+ *
6
+ * No scope, deliberately (ADR-0055 decision 6). A shared-tier shape comes back as one grant per
7
+ * scope the subject holds, expanded by the control plane, which is the only side that knows the
8
+ * answer. So K requests can return more than K streams, and a client that tracks them by shapeKey
9
+ * alone will lose all but one.
10
+ */
11
+ export interface ShapeSubscriptionRequest {
12
+ shapeKey: string;
13
+ }
14
+ /** A subscription the control plane granted. */
15
+ export interface GrantedStream {
16
+ shapeKey: string;
17
+ scope?: readonly PredicateValue[];
18
+ shapeId: string;
19
+ /** The durable-streams path, relative to the edge's stream route. */
20
+ streamPath: string;
21
+ /** The absolute URL to read it from, through the edge. */
22
+ streamUrl: string;
23
+ }
24
+ /** A subscription refused, or later revoked, with why. */
25
+ export interface RefusedStream {
26
+ shapeKey: string;
27
+ scope?: readonly PredicateValue[];
28
+ reason: string;
29
+ }
30
+ /**
31
+ * A control-plane call that did not return 2xx, carrying the status so a caller can tell an AUTH
32
+ * failure from an outage.
33
+ *
34
+ * That distinction is the whole reason this is a class rather than a bare `Error`. A 401 means the
35
+ * subject's own credential is stale and an app can fix it by prompting for re-login (ADR-0013); a
36
+ * 503 means the engine is unreachable and only time fixes it. Both retry, but only one of them is
37
+ * worth telling the user about.
38
+ */
39
+ export declare class ControlPlaneError extends Error {
40
+ readonly status: number;
41
+ readonly path: string;
42
+ readonly body: string;
43
+ constructor(status: number, path: string, body: string);
44
+ /** Whether this is the subject's credential failing, rather than the deployment. */
45
+ get isAuthFailure(): boolean;
46
+ }
47
+ export interface SubscriptionClientOptions {
48
+ /** Base URL of the control plane — the pgxsinkit server. */
49
+ controlPlaneUrl: string;
50
+ /** Base URL the edge serves streams from. `streamPath` is appended to it. */
51
+ streamBaseUrl: string;
52
+ /**
53
+ * The caller's own auth headers, resolved per request.
54
+ *
55
+ * The SAME adapter the write path uses (ADR-0003): read and write authorization must not diverge,
56
+ * and a JWT that refreshed for one has refreshed for both.
57
+ */
58
+ authHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
59
+ /**
60
+ * Re-mint this many seconds before the token expires. Default 60 — comfortably inside ADR-0055's
61
+ * 5-minute default lifetime, and large enough that a slow round trip does not race the expiry.
62
+ */
63
+ refreshSkewSeconds?: number;
64
+ /** Called when a scope is revoked. The subscriber truncates that scope and unsubscribes. */
65
+ onRevoked?: (revoked: RefusedStream[]) => void;
66
+ /**
67
+ * Aborts in-flight control-plane requests on teardown.
68
+ *
69
+ * Load-bearing rather than tidy: a client stopped while its control plane is unreachable has a
70
+ * subscribe sitting on a TCP connect that can take minutes to fail, and `stop()` waits for the boot
71
+ * tail. Without this, teardown is held hostage by a network that is already gone.
72
+ */
73
+ signal?: AbortSignal;
74
+ fetch?: typeof fetch;
75
+ }
76
+ export interface SubscriptionSession {
77
+ granted: GrantedStream[];
78
+ refused: RefusedStream[];
79
+ /**
80
+ * The current stream token, re-minted on demand.
81
+ *
82
+ * Hand this straight to the sync engine: it is called per request, so a token that expires mid-poll
83
+ * is replaced without the subscription noticing.
84
+ *
85
+ * It rejects for exactly one reason — every grant was revoked, so there is no bearer left to send.
86
+ * A control plane that could not be reached is NOT that reason: see {@link SubscriptionSession.refresh}.
87
+ */
88
+ token: () => Promise<string>;
89
+ /**
90
+ * Force a re-mint now — what a 403 from the edge should trigger. Null when nothing survived.
91
+ *
92
+ * A re-mint that FAILS (the control plane is down, unreachable, or answering 5xx) resolves with the
93
+ * token already held rather than rejecting. This is the ADR-0013 "the deployment being down is not
94
+ * the subject's problem" rule applied at the one place it is easy to get wrong: this promise is
95
+ * awaited inside `@durable-streams/client`'s header thunk, and a rejection there kills the read
96
+ * with no path back — the very silence backlog 0010 is about. The held token is still good for up
97
+ * to `refreshSkewSeconds`, and when it truly lapses the edge answers 403, the stream ends, and the
98
+ * group re-subscribes (`startCircuitsSync`'s `scheduleRestart`) — which is where a 401 surfaces as
99
+ * `onAuthError` and a 503 as a retried subscribe, both of them recoverable and both of them
100
+ * visible.
101
+ */
102
+ refresh: () => Promise<string | null>;
103
+ /**
104
+ * Close the session and hand its engine shape claims back — **promptly, best-effort**.
105
+ *
106
+ * Synchronous and fire-and-forget by design. Every grant this session was given is a named claim on
107
+ * an engine shape (a `POST /shapes` join), and a live claim blocks both dormancy and eviction, so
108
+ * releasing at close is what lets an idle shape be reclaimed now rather than at the end of its lease
109
+ * window.
110
+ *
111
+ * Not reporting whether it landed is a consequence of WHEN this runs, not of a correctness trade.
112
+ * The release is idempotent — each grant names its own claim, so a repeat is the same act once
113
+ * (fork ADR-0008) — but the most common close is a page unload, which cannot await anything or
114
+ * retry anything. So it fires once, silently, and the lease covers the rest: a release lost with the
115
+ * document leaves claims the engine reclaims within its lease window (`leaseSeconds`), because
116
+ * nothing renews them once the session is gone.
117
+ */
118
+ close: () => void;
119
+ }
120
+ /**
121
+ * The client's half of the native subscribe path (ADR-0055 decisions 6 and 10).
122
+ *
123
+ * The native path inverts how a client finds a stream. On the Electric path it *constructed* a URL
124
+ * (`electricUrl?table=<shapeKey>`) and the proxy resolved it; here it **asks**, and the control plane
125
+ * answers with the streams the subject may actually read. That inversion is what removes shape
126
+ * selection from the wire entirely — there is no client-supplied `where` or `table` left to discard.
127
+ */
128
+ export declare function openSubscriptionSession(options: SubscriptionClientOptions, requests: readonly ShapeSubscriptionRequest[]): Promise<SubscriptionSession>;
129
+ /**
130
+ * Read the engine's convergence barrier through the control plane — the `readBarrier` the sync
131
+ * engine takes.
132
+ *
133
+ * An unreachable barrier throws, and the engine treats that as a DELAY rather than a failure
134
+ * (ADR-0056): the group stays on the pre-alignment gate and tries again on the next delivery. So a
135
+ * control plane that is briefly down costs boot latency, not correctness.
136
+ *
137
+ * A body missing a term throws for the same reason and to the same effect. Defaulting the absent
138
+ * field to zero would let a control plane that CANNOT report lost membership effects be read as one
139
+ * reporting none — a guard that cannot trip, which is protection nobody has. Throwing leaves the
140
+ * group on the pre-alignment gate instead: it never aligns against a barrier it cannot read whole.
141
+ */
142
+ export declare function createBarrierReader(options: Pick<SubscriptionClientOptions, "controlPlaneUrl" | "authHeaders" | "signal" | "fetch">): () => Promise<ConvergenceBarrier>;
143
+ //# sourceMappingURL=subscription-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-client.d.ts","sourceRoot":"","sources":["../../src/circuits/subscription-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExD;;;;;;;GAOG;AACH,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,gDAAgD;AAChD,MAAM,WAAW,aAAa;IAC5B,Q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aAAa,EAAE,CAAC;IACzB,OAAO,EAAE,aAAa,EAAE,CAAC;IACzB;;;;;;;;OAQG;IACH,KAAK,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B;;;;;;;;;;;;OAYG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACtC;;;;;;;;;;;;;;OAcG;IACH,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAID;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,yBAAyB,EAClC,QAAQ,EAAE,SAAS,wBAAwB,EAAE,GAC5C,OAAO,CAAC,mBAAmB,CAAC,CAkK9B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,IAAI,CAAC,yBAAyB,EAAE,iBAAiB,GAAG,aAAa,GAAG,QAAQ,GAAG,OAAO,CAAC,GAC/F,MAAM,OAAO,CAAC,kBAAkB,CAAC,CAuBnC"}
@@ -0,0 +1,131 @@
1
+ import { type PredicateValue, type SyncTableRegistry } from "@pgxsinkit/contracts";
2
+ import type { Pgwasm } from "@pgxsinkit/pgwasm";
3
+ import { type GroupBootStamp } from "../boot-report";
4
+ import { drizzleOverPg } from "../sync/drizzle-executor";
5
+ import type { InitialInsertMethod } from "../sync/types";
6
+ import type { StreamSourceOptions } from "./stream-source";
7
+ /**
8
+ * The engine's convergence barrier, read through the control plane (ADR-0056 decision 4).
9
+ *
10
+ * Never a bare position: `pendingFlips` counts computed-but-undelivered subquery flips — membership
11
+ * move-out and move-in — so a barrier without it reports convergence while a revocation is still in
12
+ * the engine. That is silent staleness on exactly the security-relevant path.
13
+ *
14
+ * `flipFailures` is the term the others cannot express. A flip batch abandoned after its retries
15
+ * carried membership effects that are **gone**, not late: the engine keeps that batch's
16
+ * `pendingFlips` count held forever and latches itself degraded — 503 on `/v1/health` and on every
17
+ * membership-bearing route, subquery streams reaped, recovery only by operator restart. The waiting
18
+ * terms are therefore honest but permanently unsatisfied, which is indistinguishable from a slow
19
+ * engine; this term is how a client tells the two apart.
20
+ *
21
+ * These are the fields of `GET /replication/lsn` this client aligns on. Nothing here is derived, and
22
+ * nothing here is optional — a term the engine does not report is a term this client must not claim
23
+ * to check. The engine's `sync` field is deliberately absent: it is the `__el_sync` sentinel
24
+ * watermark, not a convergence term (see `replicationState` in the server's engine client).
25
+ */
26
+ export interface ConvergenceBarrier {
27
+ /** Deferred subquery flip batches not yet propagated. Read engine-global — conservative. */
28
+ pendingFlips: number;
29
+ /**
30
+ * Flip batches the engine abandoned. Non-zero means membership effects were **lost**, not delayed
31
+ * — unrecoverable in-process, and terminal for any group that reads it.
32
+ */
33
+ flipFailures: number;
34
+ }
35
+ export interface CircuitsShapeSpec {
36
+ /** Absolute URL of this shape's stream through the edge. */
37
+ streamUrl: string;
38
+ /** The registry table key this shape applies into. Several shapes may share one (ADR-0055 d4). */
39
+ tableKey: string;
40
+ /**
41
+ * What this reader IS, as the registry and the control plane name it — persisted alongside the
42
+ * offset so a later subscribe can resolve a stored entry back to its spec.
43
+ *
44
+ * Required, not derived, and the map key is why it cannot be either. That key is a name the caller
45
+ * mints to keep two readers apart; the engine treats it as opaque and has no way to take it apart
46
+ * again. Without this, a persisted entry the next subscribe does NOT find in its grants is
47
+ * unattributable — which is exactly the entry that has to be cleared (ADR-0055 decision 6).
48
+ */
49
+ identity: {
50
+ /** The registry shape key this stream carries. */
51
+ shapeKey: string;
52
+ /** Shared tier only: the scope values the grant named, in the shape's declared column order. */
53
+ scope?: readonly PredicateValue[];
54
+ };
55
+ /**
56
+ * Scoped cache clear for a must-refetch, replacing the default `TRUNCATE`.
57
+ *
58
+ * **Required when several shapes share a `tableKey`**, and the engine refuses the group otherwise:
59
+ * the default truncate would wipe a co-tenant scope's rows. A shared-tier shape derives it from
60
+ * its scope key, so supplying one is mechanical rather than a burden.
61
+ */
62
+ onMustRefetch?: (db: ReturnType<typeof drizzleOverPg>) => Promise<void>;
63
+ /** Per-shape backfill strategy override; otherwise the registry's classification. */
64
+ initialInsertMethod?: InitialInsertMethod;
65
+ }
66
+ export interface CircuitsSyncOptions {
67
+ pg: Pgwasm;
68
+ registry: SyncTableRegistry;
69
+ /** Subscription key for persisted resume state; `null` disables persistence. */
70
+ key: string | null;
71
+ metadataSchema: string;
72
+ shapes: Record<string, CircuitsShapeSpec>;
73
+ token: StreamSourceOptions["token"];
74
+ onTokenRejected?: StreamSourceOptions["onTokenRejected"];
75
+ /** Reads the engine barrier through the control plane. Consulted once per alignment generation. */
76
+ readBarrier: () => Promise<ConvergenceBarrier>;
77
+ sessionScoped?: boolean;
78
+ /**
79
+ * Boot observability (ADR-0034). Present only for a BOOT group — an on-demand lazy activation gets
80
+ * none, so post-boot traffic never enters a finalized report.
81
+ */
82
+ bootStamp?: GroupBootStamp;
83
+ onInitialSync?: () => void;
84
+ onSyncError?: (error: Error) => void;
85
+ onSyncActivity?: () => void;
86
+ /**
87
+ * One shape's read ended — `null` for a normal end, an error for a stream that died mid-session.
88
+ *
89
+ * Passed through from the shape group and deliberately NOT acted on here. Recovery is a
90
+ * re-subscribe, and this engine has no subscription: it is handed URLs and a token by the layer
91
+ * above (ADR-0055 decision 10), which is the only layer that can ask the control plane for a fresh
92
+ * grant. Ignored once `unsubscribe()` has been called — a teardown's own stream closes are not
93
+ * conditions.
94
+ */
95
+ onStreamEnd?: (shapeName: string, error: Error | null) => void;
96
+ /**
97
+ * Long-poll the tail after catching up (default). `false` reads each stream to its tail and stops
98
+ * — a one-shot hydration rather than a live subscription.
99
+ */
100
+ live?: boolean;
101
+ maxCommitRetries?: number;
102
+ commitRetryDelayMs?: (attempt: number) => number;
103
+ debug?: boolean;
104
+ fetch?: typeof fetch;
105
+ }
106
+ export interface CircuitsSyncHandle {
107
+ unsubscribe(): void;
108
+ readonly isUpToDate: boolean;
109
+ }
110
+ /**
111
+ * Sync K Circuits shape streams into one consistency group (ADR-0055 + ADR-0056).
112
+ *
113
+ * The commit gate is the whole of ADR-0056's steady state: **commit when every shape's most recent
114
+ * response asserted up-to-date**. That is a happens-before, not a position comparison. Offsets are
115
+ * per-stream and the protocol only sanctions comparing them within a stream, so no `min` over
116
+ * positions exists to take, and none is taken.
117
+ *
118
+ * The happens-before is airtight at ALIGNMENT — every stream has drained what the server held, and
119
+ * everything held commits together — and weaker in the live steady state, where every stream's report
120
+ * is latched true between parked long polls and each delivery commits on arrival. Two streams
121
+ * carrying halves of one server transaction are answered separately, so the window in which one half
122
+ * is applied and the other is not is their response inter-arrival, normally milliseconds. Closing it
123
+ * needs a fence the engine does not emit — see `docs/backlog/0014-cross-stream-commit-fence.md`.
124
+ *
125
+ * The barrier is consulted **once per alignment generation**, at boot and after any must-refetch.
126
+ * Its job there is narrow and specific: every stream can report drained while the engine still holds
127
+ * a computed revocation, and a boot that claimed consistency in that window would present a store
128
+ * missing an eviction. Mid-session the same condition is just a change arriving late.
129
+ */
130
+ export declare function syncCircuitsShapes(options: CircuitsSyncOptions): Promise<CircuitsSyncHandle>;
131
+ //# sourceMappingURL=sync-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-engine.d.ts","sourceRoot":"","sources":["../../src/circuits/sync-engine.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,mBAAmB,CAAC;AAE7D,OAAO,EAAS,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAU5D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAGzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAIzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,kBAAkB;IACjC,4FAA4F;IAC5F,YAAY,EAAE,MAAM,CAA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E,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,CAAC;IAC/D;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,CAAC;IACjD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IACjC,WAAW,IAAI,IAAI,CAAC;IACpB,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B;AAqBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA2XlG"}
package/dist/debug.d.ts CHANGED
@@ -14,16 +14,6 @@ export declare function setSyncDebugSink(sink: SyncDebugSink | undefined): void;
14
14
  * worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.
15
15
  */
16
16
  export declare function syncDebug(event: string, data?: Record<string, unknown>): void;
17
- /**
18
- * Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start
19
- * line (shape/table, offset, live — derived from the request URL params) and a completion line (status,
20
- * ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return
21
- * runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.
22
- *
23
- * Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base
24
- * so the instrumentation composes rather than replaces.
25
- */
26
- export declare function instrumentShapeFetch(baseFetch?: typeof fetch): typeof fetch;
27
17
  /**
28
18
  * Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When
29
19
  * instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the
@@ -1 +1 @@
1
- {"version":3,"file":"debug.d.ts","sourceRoot":"","sources":["../src/debug.ts"],"names":[],"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