@pgxsinkit/client 0.2.7 → 0.3.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 (94) hide show
  1. package/README.md +2 -1
  2. package/dist/boot-report.d.ts +5 -2
  3. package/dist/boot-report.d.ts.map +1 -1
  4. package/dist/circuits/envelope-to-change.d.ts +35 -0
  5. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  6. package/dist/circuits/group-sync.d.ts +123 -0
  7. package/dist/circuits/group-sync.d.ts.map +1 -0
  8. package/dist/circuits/shape-group.d.ts +77 -0
  9. package/dist/circuits/shape-group.d.ts.map +1 -0
  10. package/dist/circuits/stream-inbox.d.ts +126 -0
  11. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  12. package/dist/circuits/stream-source.d.ts +90 -0
  13. package/dist/circuits/stream-source.d.ts.map +1 -0
  14. package/dist/circuits/subscription-client.d.ts +143 -0
  15. package/dist/circuits/subscription-client.d.ts.map +1 -0
  16. package/dist/circuits/sync-engine.d.ts +131 -0
  17. package/dist/circuits/sync-engine.d.ts.map +1 -0
  18. package/dist/debug.d.ts +0 -10
  19. package/dist/debug.d.ts.map +1 -1
  20. package/dist/export-dump.d.ts.map +1 -1
  21. package/dist/index.d.ts +47 -19
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +6258 -6443
  24. package/dist/index.js.map +26 -26
  25. package/dist/local-tables.d.ts +1 -1
  26. package/dist/local-tables.d.ts.map +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/sync/apply.d.ts +13 -21
  29. package/dist/sync/apply.d.ts.map +1 -1
  30. package/dist/sync/copy.d.ts +8 -8
  31. package/dist/sync/fold.d.ts +40 -0
  32. package/dist/sync/fold.d.ts.map +1 -0
  33. package/dist/sync/metadata-tables.d.ts +25 -1
  34. package/dist/sync/metadata-tables.d.ts.map +1 -1
  35. package/dist/sync/subscription-state.d.ts +21 -2
  36. package/dist/sync/subscription-state.d.ts.map +1 -1
  37. package/dist/sync/types.d.ts +9 -129
  38. package/dist/sync/types.d.ts.map +1 -1
  39. package/dist/testing.js +3 -3
  40. package/dist/testing.js.map +2 -2
  41. package/dist/worker/attach-sync-client.d.ts +3 -1
  42. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  43. package/dist/worker/define-sync-worker.d.ts +17 -1
  44. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  45. package/dist/worker/engine-control.d.ts +53 -0
  46. package/dist/worker/engine-control.d.ts.map +1 -1
  47. package/package.json +4 -5
  48. package/skills/core/SKILL.md +72 -55
  49. package/skills/operating/SKILL.md +120 -120
  50. package/src/boot-report.ts +4 -3
  51. package/src/circuits/envelope-to-change.ts +102 -0
  52. package/src/circuits/group-sync.ts +1047 -0
  53. package/src/circuits/shape-group.ts +158 -0
  54. package/src/circuits/stream-inbox.ts +225 -0
  55. package/src/circuits/stream-source.ts +165 -0
  56. package/src/circuits/subscription-client.ts +353 -0
  57. package/src/circuits/sync-engine.ts +641 -0
  58. package/src/debug.ts +1 -85
  59. package/src/export-dump.ts +3 -2
  60. package/src/index.ts +290 -273
  61. package/src/lazy-guard.ts +1 -1
  62. package/src/local-tables.ts +9 -2
  63. package/src/schema.ts +2 -11
  64. package/src/sync/apply.ts +72 -110
  65. package/src/sync/copy.ts +15 -15
  66. package/src/sync/fold.ts +94 -0
  67. package/src/sync/metadata-tables.ts +42 -1
  68. package/src/sync/subscription-state.ts +21 -3
  69. package/src/sync/types.ts +13 -141
  70. package/src/testing.ts +2 -2
  71. package/src/worker/attach-sync-client.ts +8 -1
  72. package/src/worker/define-sync-worker.ts +122 -13
  73. package/src/worker/engine-control.ts +89 -0
  74. package/dist/read-stream-stall.d.ts +0 -54
  75. package/dist/read-stream-stall.d.ts.map +0 -1
  76. package/dist/shape-sync.d.ts +0 -207
  77. package/dist/shape-sync.d.ts.map +0 -1
  78. package/dist/sync/index.d.ts +0 -32
  79. package/dist/sync/index.d.ts.map +0 -1
  80. package/dist/sync/nudge.d.ts +0 -49
  81. package/dist/sync/nudge.d.ts.map +0 -1
  82. package/dist/sync/shape-inbox.d.ts +0 -215
  83. package/dist/sync/shape-inbox.d.ts.map +0 -1
  84. package/dist/sync/tags.d.ts +0 -142
  85. package/dist/sync/tags.d.ts.map +0 -1
  86. package/dist/sync-auth.d.ts +0 -53
  87. package/dist/sync-auth.d.ts.map +0 -1
  88. package/src/read-stream-stall.ts +0 -102
  89. package/src/shape-sync.ts +0 -533
  90. package/src/sync/index.ts +0 -1124
  91. package/src/sync/nudge.ts +0 -110
  92. package/src/sync/shape-inbox.ts +0 -566
  93. package/src/sync/tags.ts +0 -390
  94. package/src/sync-auth.ts +0 -117
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  The [pgxsinkit](https://pgxsinkit.github.io) client: `createSyncClient` stages writes
4
4
  into a local PGlite overlay and a durable mutation journal, flushes them to the write
5
- API, and subscribes to Electric shapes that land in local PGlite.
5
+ API, and subscribes through the read path's control plane to read durable-streams into
6
+ local PGlite.
6
7
 
7
8
  ```bash
8
9
  bun add @pgxsinkit/client @pgxsinkit/contracts
@@ -1,3 +1,6 @@
1
+ /** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */
2
+ /** The monotonic clock every boot offset and duration in this module is measured on. */
3
+ export declare const nowMs: () => number;
1
4
  /**
2
5
  * A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:
3
6
  * additive fields keep it, a breaking reshape bumps it. All durations are milliseconds; all `*AtMs` are
@@ -80,7 +83,7 @@ export interface BootReport {
80
83
  journalRecoveryMs: number;
81
84
  storeVersionReconcileMs: number;
82
85
  /**
83
- * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
86
+ * `startCircuitsSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
84
87
  * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema, journal
85
88
  * recovery, and registry reconciliation, so this includes that shared wall. Structurally 0 when the boot
86
89
  * is ready inside the
@@ -161,7 +164,7 @@ export interface GroupBootStamp {
161
164
  /** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */
162
165
  markReady: () => void;
163
166
  }
164
- /** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */
167
+ /** The seam `startCircuitsSync` uses to open a boot group's accumulator (implemented by the builder). */
165
168
  export interface BootStampCollector {
166
169
  beginGroup: (groupKey: string, tables: number) => GroupBootStamp;
167
170
  }
@@ -1 +1 @@
1
- {"version":3,"file":"boot-report.d.ts","sourceRoot":"","sources":["../src/boot-report.ts"],"names":[],"mappings":"AAeA;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,aAAa,EAAE,CAAC,CAAC;IACjB,qGAAqG;IACrG,IAAI,EAAE,YAAY,GAAG,QAAQ,CAAC;IAC9B,iGAAiG;IACjG,UAAU,EAAE,OAAO,CAAC;IACpB;;;;;;OAMG;IACH,SAAS,EAAE,OAAO,GAAG,MAAM,GAAG,UAAU,CAAC;IACzC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,eAAe,GAAG,OAAO,GAAG,YAAY,GAAG,QAAQ,CAAC;IACrE;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,eAAe,GAAG,gBAAgB,GAAG,YAAY,CAAC;IAC/D;;;;;;;OAOG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,6EAA6E;IAC7E,eAAe,EAAE,OAAO,CAAC;IACzB,+GAA+G;IAC/G,mBAAmB,EAAE,MAAM,CAAC;IAC5B,0GAA0G;IAC1G,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,OAAO,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC;;;;OAIG;IACH,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;;;OAIG;IACH,SAAS,EAAE;QACT,uEAAuE;QACvE,QAAQ,EAAE,MAAM,CAAC;QACjB,4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MAAM,IAAI,CAAC;IAC9B,6GAA6G;IAC7G,QAAQ,EAAE,MAAM,UAAU,CAAC;IAC3B,6FAA6F;IAC7F,MAAM,EAAE,MAAM,UAAU,GAAG,IAAI,CAAC;CACjC;AAED,uFAAuF;AACvF,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;IACzB,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IACnC;;;OAGG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC,YAAY,CAAC,CAAC;IACtC,eAAe,EAAE,OAAO,CAAC;IACzB,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,cAAc,GAAG,iBAAiB,CA0H/E"}
@@ -0,0 +1,35 @@
1
+ import type { StreamEnvelope, SyncOperation } from "@pgxsinkit/contracts";
2
+ import type { ApplyTarget } from "../local-tables";
3
+ /** The applier's message shape, once an envelope has been resolved against its table. */
4
+ export interface ChangeLike {
5
+ key: string;
6
+ value: Record<string, unknown>;
7
+ headers: {
8
+ operation: SyncOperation;
9
+ };
10
+ }
11
+ /**
12
+ * Rebuild the primary-key columns of a row from the stream key.
13
+ *
14
+ * Composite keys are joined in **primary-key declaration order**, which is the order `ApplyTarget`
15
+ * already holds — so the two must agree. A count mismatch is thrown rather than tolerated: a
16
+ * silently short split would produce a `WHERE` over only part of the key, and a delete matching more
17
+ * rows than it should is data loss, not a stale row.
18
+ */
19
+ export declare function primaryKeyFromStreamKey(target: ApplyTarget, key: string): Record<string, unknown>;
20
+ /**
21
+ * Translate a Circuits envelope into the message the applier consumes.
22
+ *
23
+ * There is no operation mapping to do — {@link SyncOperation} is the wire's own vocabulary. What
24
+ * this function carries is the one structural difference: **a delete has no row body**, only its
25
+ * key, so the pk columns are reconstructed here. That is a privacy improvement (an eviction
26
+ * discloses the key and nothing else) and an implementation hazard in the same change, which is why
27
+ * the reconstruction is a named, tested function rather than an inline split.
28
+ *
29
+ * An `upsert` carries the **complete projected row** every time — the engine's `row_to_json_cols`
30
+ * emits every column of the shape's `out_cols`, never a changed-column subset — which is what lets
31
+ * the apply path refresh every non-pk column from `excluded` without knowing whether the row already
32
+ * existed locally.
33
+ */
34
+ export declare function envelopeToChange(target: ApplyTarget, envelope: StreamEnvelope): ChangeLike;
35
+ //# sourceMappingURL=envelope-to-change.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope-to-change.d.ts","sourceRoot":"","sources":["../../src/circuits/envelope-to-change.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAe,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAUnD,yFAAyF;AACzF,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,EAAE;QAAE,SAAS,EAAE,aAAa,CAAA;KAAE,CAAC;CACvC;AA0BD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAejG;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,GAAG,UAAU,CAmB1F"}
@@ -0,0 +1,123 @@
1
+ import type { PGliteInterface } from "@electric-sql/pglite";
2
+ import type { PredicateValue, SyncTableRegistry } from "@pgxsinkit/contracts";
3
+ import type { BootStampCollector } from "../boot-report";
4
+ import { ControlPlaneError, type RefusedStream } from "./subscription-client";
5
+ export interface CircuitsGroupSyncOptions {
6
+ registry: SyncTableRegistry;
7
+ /** Base URL of the control plane — where subscribe, re-mint and the barrier live. */
8
+ controlPlaneUrl: string;
9
+ /** Base URL the edge serves streams from. */
10
+ streamBaseUrl: string;
11
+ /** The caller's own auth headers, resolved per request — the same adapter the write path uses. */
12
+ authHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
13
+ metadataSchema: string;
14
+ /**
15
+ * Lazy groups whose activation persisted from a previous boot (ADR-0021), started eagerly here.
16
+ */
17
+ promotedGroups?: ReadonlySet<string>;
18
+ /**
19
+ * Boot observability (ADR-0034). Only the BOOT starts (eager + promoted) open an accumulator, so an
20
+ * on-demand lazy activation never enters a finalized report.
21
+ */
22
+ bootCollector?: BootStampCollector;
23
+ /** Fired the first time every eager/promoted group has caught up. */
24
+ onInitialSync?: () => void;
25
+ onGroupReady?: (groupKey: string) => void;
26
+ onSyncError?: (error: Error) => void;
27
+ onSyncActivity?: () => void;
28
+ /** Called when a durable lazy group is activated on demand, so the next boot can promote it. */
29
+ onLazyActivated?: (groupKey: string) => void;
30
+ /**
31
+ * Called with the scopes the control plane refused or later revoked.
32
+ *
33
+ * Fired AFTER the refused scopes' local rows have been cleared, never before. Losing entitlement
34
+ * means losing the subscription, not keeping the rows (ADR-0055 decision 6), and an app that reacts
35
+ * to this — re-rendering, prompting, navigating away — must not be handed a store that still shows
36
+ * what the subject may no longer read.
37
+ */
38
+ onRefused?: (refused: readonly RefusedStream[]) => void;
39
+ /**
40
+ * The subject's own credential was refused by the control plane (401/403), and subscribe is still
41
+ * retrying (ADR-0013). The app prompts for re-login; nothing here needs restarting, because the
42
+ * auth adapter is consulted fresh on every attempt.
43
+ *
44
+ * Distinct from `onSyncError`, which reports a fault the subject cannot act on.
45
+ */
46
+ onAuthError?: (error: ControlPlaneError) => void;
47
+ /**
48
+ * Subscribe failed for a reason the subject cannot act on — the control plane is down, degraded,
49
+ * or unreachable — and is still retrying.
50
+ *
51
+ * Separate from `onSyncError` because the two recover differently: a failed subscribe clears the
52
+ * moment a batch is delivered, while a commit failure is sticky by design (ADR-0009 decision 5) —
53
+ * reads can keep succeeding while applies keep failing.
54
+ */
55
+ onSubscribeError?: (error: Error) => void;
56
+ /**
57
+ * A live stream ended or could not be opened — a `403` that survived a re-mint, a `404`/`410` on an
58
+ * evicted stream, `Stream-Closed`, a lost connection — and the group is re-subscribing with
59
+ * backoff.
60
+ *
61
+ * Recoverable, and it clears on the next delivered batch. Distinct from `onSubscribeError` (the
62
+ * CONTROL PLANE could not be reached, so there is nothing to read from yet) and from `onSyncError`
63
+ * (a COMMIT failed, which is sticky by design because reads can keep succeeding while applies keep
64
+ * failing).
65
+ */
66
+ onStreamError?: (error: Error) => void;
67
+ live?: boolean;
68
+ /**
69
+ * Tears the whole read path down from OUTSIDE, including mid-boot.
70
+ *
71
+ * `unsubscribe()` cannot cover that window: it lives on the handle this function returns, and a boot
72
+ * whose control plane is unreachable has not returned one yet. A client stopped in that window would
73
+ * otherwise sit on a TCP connect with nothing able to cancel it — which is precisely when a stop is
74
+ * most likely, because the network being down is why the boot is still running.
75
+ */
76
+ signal?: AbortSignal;
77
+ fetch?: typeof fetch;
78
+ }
79
+ export interface CircuitsTableSyncResult {
80
+ readonly isUpToDate: boolean;
81
+ }
82
+ export interface CircuitsGroupSyncResult {
83
+ unsubscribe: () => void;
84
+ tables: Record<string, CircuitsTableSyncResult>;
85
+ /**
86
+ * Start a held lazy group. Idempotent and single-flight; resolves once it has caught up — EXCEPT
87
+ * for an already-promoted group, which resolves at once because it is durable and boot-started
88
+ * (ADR-0021 §2), so its catch-up must not gate a read.
89
+ */
90
+ ensureGroupStarted: (groupKey: string) => Promise<void>;
91
+ /**
92
+ * Tear a group's streams down and return it to dormant, so a later start re-subscribes. Also drops
93
+ * the group's promotion for this session — a desync truncates the local copy, so the group is held
94
+ * again and re-activates (and re-persists its flag) on its next reference.
95
+ */
96
+ stopGroup: (groupKey: string) => void;
97
+ groupKeyForTable: (tableKey: string) => string | undefined;
98
+ /**
99
+ * Whether the table's group is STARTED — a durable subscription for it exists, so reads of it are
100
+ * meaningful. NOT the same question as caught up, which is {@link CircuitsGroupSyncResult.isGroupReady}:
101
+ * a promoted group is started from boot even while its first subscribe is still retrying.
102
+ */
103
+ isTableStarted: (tableKey: string) => boolean;
104
+ groupReady: (groupKey: string) => Promise<void>;
105
+ isGroupReady: (groupKey: string) => boolean;
106
+ groupKeys: () => string[];
107
+ }
108
+ /**
109
+ * The name one READER of a stream is known by, within its group and across boots.
110
+ *
111
+ * A grant's shape key plus its scope, because neither alone identifies a reader. A shared shape fans
112
+ * out to one grant per entitled scope (ADR-0055 decision 6), so shape keys are not unique within a
113
+ * group; and the STREAM PATH is not unique either, which is the sharper of the two. Circuits
114
+ * ref-counts byte-identical shape definitions, so two distinct read projections that compile to the
115
+ * same table, columns and predicate come back as one path — keying on it dropped the second
116
+ * projection's reader outright and left its local table empty forever.
117
+ *
118
+ * Exported for the tests that pin that naming: it is also the key of a persisted cursor entry, so it
119
+ * is the thing a later subscribe matches a grant against.
120
+ */
121
+ export declare function logicalShapeName(shapeKey: string, scope?: readonly PredicateValue[]): string;
122
+ export declare function startCircuitsSync(pg: PGliteInterface, options: CircuitsGroupSyncOptions): Promise<CircuitsGroupSyncResult>;
123
+ //# sourceMappingURL=group-sync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"group-sync.d.ts","sourceRoot":"","sources":["../../src/circuits/group-sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,KAAK,EAAE,cAAc,EAAkB,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9F,OAAO,KAAK,EAAE,kBAAkB,EAAkB,MAAM,gBAAgB,CAAC;AASzE,OAAO,EACL,iBAAiB,EAGjB,KAAK,aAAa,EAEnB,MAAM,uBAAuB,CAAC;AA4F/B,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,qFAAqF;IACrF,eAAe,EAAE,MAAM,CAAC;IACxB,6CAA6C;IAC7C,aAAa,EAAE,MAAM,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MAAM,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC,CAAC;IAChD;;;;OAIG;IACH,kBAAkB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACxD;;;;OAIG;IACH,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IACtC,gBAAgB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAC3D;;;;OAIG;IACH,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;IAC9C,UAAU,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;IAC5C,SAAS,EAAE,MAAM,MAAM,EAAE,CAAC;CAC3B;AA6ED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,SAAS,cAAc,EAAE,GAAG,MAAM,CAE5F;AAgED,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,eAAe,EACnB,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,uBAAuB,CAAC,CA+pBlC"}
@@ -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,iBAAiB,CAA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rorHandler } 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
+ * The transport only. Everything above it — the fold, apply modes, the boot gate — stays
86
+ * pgxsinkit's, which is ADR-0009's precedent applied to a new substrate: keep the transport,
87
+ * internalize the semantics.
88
+ */
89
+ export declare function readShapeStream(options: StreamSourceOptions, onBatch: (batch: StreamBatch) => void | Promise<void>, onEnd?: (error: Error | null) => void): Promise<ShapeStreamSubscription>;
90
+ //# 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,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