@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
@@ -1 +0,0 @@
1
- {"version":3,"file":"shape-sync.d.ts","sourceRoot":"","sources":["../src/shape-sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EACL,KAAK,SAAS,EACd,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EAEvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,E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ric-sql/pglite";
2
- import { type ElectricSyncOptions, type SyncShapesToTablesOptions, type SyncShapesToTablesResult, type SyncShapeToTableOptions, type SyncShapeToTableResult } from "./types";
3
- export * from "./types";
4
- /**
5
- * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine
6
- * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it
7
- * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`
8
- * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the
9
- * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit
10
- * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked
11
- * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).
12
- */
13
- export declare function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions): Promise<{
14
- namespace: {
15
- initMetadataTables: () => Promise<void>;
16
- syncShapesToTables: ({ key, registry, shapes, sessionScoped, initialInsertMethod, onInitialSync, onError, onSyncError, onSyncActivity, dbReady, bootStamp, maxCommitRetries, commitRetryDelayMs, }: SyncShapesToTablesOptions) => Promise<SyncShapesToTablesResult>;
17
- syncShapeToTable: (options: SyncShapeToTableOptions) => Promise<SyncShapeToTableResult>;
18
- deleteSubscription: (key: string) => Promise<void>;
19
- };
20
- close: () => Promise<void>;
21
- }>;
22
- /**
23
- * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,
24
- * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type
25
- * follows the object.
26
- */
27
- export type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;
28
- export type SyncNamespaceObj = SyncEngine["namespace"];
29
- export type PGliteWithSync = PGliteInterface & {
30
- sync: SyncNamespaceObj;
31
- };
32
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sync/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AA2C5D,OAAO,EAEL,KAAK,mBAAmB,EAIxB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC5B,MAAM,SAAS,CAAC;AAEjB,cAAc,SAAS,CAAC;AAgDxB;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,mBAAmB;;kCA+BxD,OAAO,CAAC,IAAI,CAAC;4MA2BzC,yBAAyB,KAAG,OAAO,CAAC,wBAAwB,CAAC;oCAi2BvB,uBAAuB,KAAG,OAAO,CAAC,sBAAsB,CAAC;kCAsC3D,MAAM;;;GAgC9C;AAED;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC,CAAC;AACtE,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAEvD,MAAM,MAAM,cAAc,GAAG,eAAe,GAAG;IAC7C,IAAI,EAAE,gBAAgB,CAAC;CACxB,CAAC"}
@@ -1,49 +0,0 @@
1
- /**
2
- * How long a hold must PERSIST before the first nudge round fires. A cross-shape transaction's halves
3
- * arrive milliseconds apart even on a healthy stack, so every grouped commit passes through a
4
- * transient "held" instant — nudging on it immediately ABORTS the sibling's long-poll that was about
5
- * to deliver the other half, turning a millisecond hold into an abort/refetch disruption loop
6
- * (regression caught by the sync-e2e integration lane on local Electric). A hold that outlives this
7
- * grace is the real thing: a quiet sibling parked in a multi-second poll. On Electric Cloud this adds
8
- * ~1s to a path that saves ~40s; on local stacks it means the nudge simply never fires.
9
- */
10
- export declare const NUDGE_HOLD_GRACE_MS = 1000;
11
- /**
12
- * Max nudge rounds before a dead / genuinely-still-polling sibling degrades back to the old behavior
13
- * (wait out its live long-poll) instead of being nudged forever — so a stuck sibling never becomes a
14
- * refresh storm.
15
- */
16
- export declare const NUDGE_MAX_ROUNDS = 3;
17
- /**
18
- * Polling step while waiting for a nudge round's forced catch-ups to advance the group frontier. The
19
- * `forceDisconnectAndRefresh()` promise settles BEFORE the refreshed catch-up response lands (field
20
- * measurement: round 2 fired ~750ms into round 1's still-in-flight requests when the wait keyed off that
21
- * promise alone), so the watchdog instead polls the frontier at this step, up to
22
- * {@link NUDGE_ROUND_WAIT_MS} per round, breaking out the moment the target is reached.
23
- */
24
- export declare const NUDGE_ROUND_GRACE_MS = 100;
25
- /**
26
- * Max wait per nudge round for the forced catch-ups to return and advance the frontier. A nudged
27
- * catch-up measures ~0.9–1.4s through a warm deployed edge proxy but >3.5s against a cold one — and
28
- * a next round's refresh ABORTS a still-in-flight round (the abort-and-reconnect is the mechanism),
29
- * so an early re-nudge throws away an almost-done response. The wait therefore covers the cold-edge
30
- * tail; worst case to exhaustion stays NUDGE_MAX_ROUNDS × this ≈ 12s, still far under a ~41s hold.
31
- */
32
- export declare const NUDGE_ROUND_WAIT_MS = 4000;
33
- /**
34
- * Wrap a `fetchClient` so a pending one-shot nudge token defeats the CDN on the nudged sibling's catch-up.
35
- *
36
- * A nudge's `forceDisconnectAndRefresh` issues a NON-live catch-up (Electric sets `canLongPoll: false`),
37
- * which is CDN-cacheable — a HIT would return the SAME stale watermark that made the sibling lag, defeating
38
- * the nudge. So the watchdog drops a per-shape token into `nudgeBusters` just before it nudges; this wrapper
39
- * consumes that token on the sibling's next NON-live request, appending `cache-buster=<token>` to force a
40
- * CDN miss. It is one-shot (the token is deleted on use) and skips LIVE (`live=true`) long-polls — the token
41
- * is meant for the catch-up that follows the aborted poll, not the poll itself, which is left to be retained
42
- * for that catch-up. An already-present `cache-buster` param is overwritten. When no token is pending this is
43
- * a straight passthrough, so the off-path pays only this closure.
44
- *
45
- * Exported for unit testing; composed in the engine as the OUTER wrapper around `instrumentShapeFetch`, so
46
- * the buster stamps the URL BEFORE instrumentation logs it (the debug rail then shows `BUSTED`).
47
- */
48
- export declare function withNudgeBuster(fetchClient: typeof fetch, nudgeBusters: Map<string, string>, shapeName: string): typeof fetch;
49
- //# sourceMappingURL=nudge.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"nudge.d.ts","sourceRoot":"","sources":["../../src/sync/nudge.ts"],"names":[],"mappings":"AAeA;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,OAAQ,CAAC;AAEzC;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAExC;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,OAAQ,CAAC;AAYzC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,OAAO,KAAK,EACzB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EACjC,SAAS,EAAE,MAAM,GAChB,OAAO,KAAK,CA6Bd"}
@@ -1,215 +0,0 @@
1
- import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
- import type { InsertChangeMessage, Lsn } from "./types";
3
- /**
4
- * The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's
5
- * Electric subscription and the Sync applier. It buffers each shape's change messages keyed by
6
- * LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the
7
- * applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014
8
- * per-PK fold that will live here) property-testable against an ordered per-row apply oracle.
9
- *
10
- * One inbox owns all shapes in a consistency group; the group commits atomically at the lowest
11
- * complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays
12
- * with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).
13
- *
14
- * COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live
15
- * here and they are deliberately NOT the same number:
16
- *
17
- * - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below
18
- * it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor
19
- * (below) but above its raw frontier is still buffered, never dropped.
20
- * - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see
21
- * {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in
22
- * {@link lowestCompleteLsn}; it never gates ingestion.
23
- *
24
- * Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable
25
- * (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its
26
- * `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up
27
- * can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the
28
- * group min-frontier below changes already delivered on the busy shape, holding them buffered until the
29
- * quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The
30
- * alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at
31
- * catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose
32
- * cached catch-up omitted it is still ingested and committed rather than dropped.
33
- */
34
- export declare class ShapeInbox {
35
- private readonly changes;
36
- private readonly completeLsns;
37
- private readonly moveOuts;
38
- private readonly moveIns;
39
- private readonly epochs;
40
- private readonly snapshotAccepted;
41
- private readonly upToDateSeen;
42
- private readonly lastUpToDateLsn;
43
- private readonly commitFloors;
44
- private aligned;
45
- private lastAlignedFloor;
46
- constructor(shapeNames: Iterable<string>);
47
- /**
48
- * Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from
49
- * registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The
50
- * commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver
51
- * them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.
52
- */
53
- acceptsSnapshotRowsFor(shapeName: string): boolean;
54
- /** The complete-LSN frontier for one shape (the already-seen dedup threshold). */
55
- completeLsnFor(shapeName: string): Lsn;
56
- /**
57
- * The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it
58
- * back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so
59
- * the reset's own truncate+rebuild path owns that shape's post-reset state.
60
- */
61
- epochFor(shapeName: string): number;
62
- /**
63
- * Buffer a change message. A message at or below the shape's current complete frontier is
64
- * already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.
65
- */
66
- ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void;
67
- /** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */
68
- commitFloorFor(shapeName: string): Lsn;
69
- /**
70
- * A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —
71
- * the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity
72
- * {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),
73
- * and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.
74
- */
75
- effectiveLsnFor(shapeName: string): Lsn;
76
- /**
77
- * Whether this shape has reported `up-to-date` at least once since registration / its last
78
- * {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:
79
- * a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.
80
- */
81
- hasReportedUpToDate(shapeName: string): boolean;
82
- /** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */
83
- alignedFloor(): Lsn;
84
- /**
85
- * Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the
86
- * one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.
87
- *
88
- * Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on
89
- * that transition); `false` on every other call.
90
- */
91
- ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean;
92
- /** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */
93
- ingestMoveOut(shapeName: string, patterns: MovePattern[]): void;
94
- /** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */
95
- drainMoveOuts(shapeName: string): MovePattern[][];
96
- /**
97
- * Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs
98
- * with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)
99
- * only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the
100
- * revocations buffered rather than silently losing them.
101
- */
102
- peekMoveOuts(shapeName: string): MovePattern[][];
103
- /**
104
- * Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit
105
- * that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the
106
- * peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)
107
- * buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a
108
- * {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so
109
- * this no-ops rather than splicing the post-reset replacement.
110
- */
111
- ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void;
112
- /** Whether any shape has a buffered `move-out` awaiting a commit. */
113
- hasPendingMoveOuts(): boolean;
114
- /** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */
115
- ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void;
116
- /** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */
117
- drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
118
- /** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */
119
- peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
120
- /**
121
- * Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see
122
- * {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a
123
- * mid-commit {@link resetShape}), so the post-reset replacement rows survive.
124
- */
125
- ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void;
126
- /** Whether any shape has a buffered `move-in` awaiting a commit. */
127
- hasPendingMoveIns(): boolean;
128
- /** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */
129
- resetShape(shapeName: string): void;
130
- /**
131
- * The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's
132
- * effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup
133
- * frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global
134
- * head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy
135
- * shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'
136
- * first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw
137
- * {@link completeLsns}), so a late sub-floor change is still ingested and then committed.
138
- */
139
- lowestCompleteLsn(): Lsn;
140
- /**
141
- * Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit
142
- * loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed
143
- * target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change
144
- * below the floor while the group frontier already sits at (or above) it, so no new frontier advance
145
- * would otherwise trigger a commit for it.
146
- */
147
- hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean;
148
- /**
149
- * Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN
150
- * order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs
151
- * with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks
152
- * (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)
153
- * holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.
154
- */
155
- peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
156
- /**
157
- * Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a
158
- * matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured
159
- * at peek time; a shape whose epoch has since changed is **skipped entirely**.
160
- *
161
- * The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only
162
- * advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit
163
- * {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at
164
- * LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop
165
- * the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.
166
- */
167
- ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void;
168
- /** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */
169
- snapshotEpochs(): Map<string, number>;
170
- /**
171
- * Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order
172
- * ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty
173
- * array where nothing drained).
174
- */
175
- drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
176
- }
177
- /**
178
- * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
179
- * Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a
180
- * *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk
181
- * apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs
182
- * three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is
183
- * what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest
184
- * of the order is irrelevant within the atomic commit.
185
- */
186
- export interface FoldedShapeBatch {
187
- /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
188
- deletes: ChangeMessage<Row<unknown>>[];
189
- /** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */
190
- inserts: InsertChangeMessage[];
191
- /** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */
192
- updates: ChangeMessage<Row<unknown>>[];
193
- }
194
- /**
195
- * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
196
- * (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …
197
- * SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when
198
- * the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:
199
- *
200
- * - **trailing `delete`** ⇒ a single DELETE;
201
- * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
202
- * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert);
203
- * - **only `update`s** ⇒ a single UPDATE with merged values;
204
- * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
205
- * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
206
- * would collide with the row the dropped delete was meant to remove);
207
- * - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream
208
- * (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently
209
- * dropping it.
210
- *
211
- * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
212
- * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
213
- */
214
- export declare function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch;
215
- //# sourceMappingURL=shape-inbox.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"shape-inbox.d.ts","sourceRoot":"","sources":["../../src/sync/shape-inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,UAAU;IAErB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8D;IAEtF,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA0B;IAIvD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsC;IAK/D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoD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M,EAAE,MAAM,CAAC,GAAG,IAAI,CAY/D;IAED,sGAAsG;IACtG,cAAc,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAEpC;IAED;;;;OAIG;IACH,SAAS,CAAC,SAAS,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAKpE;CACF;AAID;;;;;;;;GAQG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;IACvC,mGAAmG;IACnG,OAAO,EAAE,mBAAmB,EAAE,CAAC;IAC/B,mGAAmG;IACnG,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;CACxC;AAgBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAgBzF"}
@@ -1,142 +0,0 @@
1
- import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
3
- import type { ApplyTarget } from "../local-tables";
4
- /**
5
- * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
6
- * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)
7
- * streams two extra things the plain change path ignores:
8
- *
9
- * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per
10
- * grant/membership), plus `removed_tags` on an update;
11
- * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — "the tag whose component at
12
- * index `pos` equals `value` is withdrawn", i.e. that grant was revoked.
13
- *
14
- * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`
15
- * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one
16
- * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an
17
- * Electric change.
18
- *
19
- * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:
20
- * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.
21
- */
22
- /**
23
- * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.
24
- * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so
25
- * the desync path (which is outside the engine) can key the tag store by this same constant.
26
- */
27
- export declare const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
28
- /**
29
- * Validate the metadata schema name at engine construction. The name is interpolated RAW into two
30
- * positions a double-quoted identifier cannot cover:
31
- * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
32
- * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
33
- * accept a quoted identifier the way a table/column position does, so the name cannot be safely
34
- * quoted there.
35
- * - the `CREATE SCHEMA <schema>` DDL identifier position.
36
- * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
37
- * lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
38
- */
39
- export declare function assertValidMetadataSchema(metadataSchema: string): void;
40
- /**
41
- * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config
42
- * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by
43
- * `migrateSubscriptionMetadataTables`, which renders that same pgTable.
44
- */
45
- export declare function shapeRowTagsTableName(metadataSchema: string): string;
46
- /**
47
- * The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session
48
- * `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind
49
- * {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.
50
- */
51
- export declare function shapeRowTagsSessionTableName(): string;
52
- /** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
53
- export declare function shapeTableId(schema: string | undefined, table: string): string;
54
- /**
55
- * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
56
- * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
57
- * caller/test that builds the local schema without booting the sync engine that creates the store). The
58
- * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
59
- * guarded.
60
- */
61
- export declare function buildClearShapeTagsSql(shapeTable: string, metadataSchema?: string): string;
62
- /**
63
- * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
64
- * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
65
- * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
66
- */
67
- export declare function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string;
68
- /**
69
- * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
70
- * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
71
- * two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
72
- * `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
73
- *
74
- * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
75
- * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
76
- */
77
- export declare function splitTagComponents(tag: string): string[];
78
- /**
79
- * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
80
- * of the shape's tag structure (one position per subquery condition that references it), so the event
81
- * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
82
- * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
83
- * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
84
- * matches nothing.
85
- */
86
- export declare function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean;
87
- interface TagSyncOptions {
88
- pg: PGliteInterface | Transaction;
89
- metadataSchema: string;
90
- shapeTable: string;
91
- messages: ChangeMessage<Row<unknown>>[];
92
- primaryKey: string[];
93
- /** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */
94
- sessionScoped?: boolean;
95
- }
96
- /**
97
- * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
98
- * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
99
- * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
100
- * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
101
- * eviction in the same commit, so an add-then-remove within one batch resolves correctly.
102
- */
103
- export declare function applyShapeTagSync({ pg, metadataSchema, shapeTable, messages, primaryKey, sessionScoped, }: TagSyncOptions): Promise<void>;
104
- /**
105
- * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
106
- * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
107
- * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
108
- * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
109
- * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
110
- * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
111
- * A row with no `tags` (a non-subquery shape) is a no-op.
112
- */
113
- export declare function addShapeRowTags({ pg, metadataSchema, shapeTable, messages, primaryKey, sessionScoped, }: TagSyncOptions): Promise<void>;
114
- interface MoveOutOptions {
115
- pg: PGliteInterface | Transaction;
116
- metadataSchema: string;
117
- shapeTable: string;
118
- /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
119
- target: ApplyTarget;
120
- /** One entry per buffered `move-out` event, each its own pattern set. */
121
- patternSets: MovePattern[][];
122
- debug: boolean;
123
- /** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */
124
- sessionScoped?: boolean;
125
- }
126
- /**
127
- * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
128
- * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
129
- * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
130
- * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
131
- */
132
- export declare function applyShapeMoveOut({ pg, metadataSchema, shapeTable, target, patternSets, debug, sessionScoped, }: MoveOutOptions): Promise<number>;
133
- /** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
134
- export declare function clearShapeTags({ pg, metadataSchema, shapeTable, sessionScoped, }: {
135
- pg: PGliteInterface | Transaction;
136
- metadataSchema: string;
137
- shapeTable: string;
138
- /** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */
139
- sessionScoped?: boolean;
140
- }): Promise<void>;
141
- export {};
142
- //# sourceMappingURL=tags.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/sync/tags.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAMzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAKnD;;;;;;;;;;;;;;;;;GAiBG;AAEH;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,cAAc,CAAC;AAQnD;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAStE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAGpE;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CAGrD;AAED,uGAAuG;AACvG,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM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,WAAW,CAAC;IACpB,yEAAyE;IACzE,WAAW,EAAE,WAAW,EAAE,EAAE,CAAC;IAC7B,KAAK,EAAE,OAAO,CAAC;IACf,uGAAuG;IACvG,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,EAAE,EACF,cAAc,EACd,UAAU,EACV,MAAM,EACN,WAAW,EACX,KAAK,EACL,aAAqB,GACtB,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CA0ElC;AAED,0HAA0H;AAC1H,wBAAsB,cAAc,CAAC,EACnC,EAAE,EACF,cAAc,EACd,UAAU,EACV,aAAqB,GACtB,EAAE;IACD,EAAE,EAAE,eAAe,GAAG,WAAW,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,uGAAuG;IACvG,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGhB"}
@@ -1,53 +0,0 @@
1
- import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
2
- /** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
3
- type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
4
- /**
5
- * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
6
- * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
7
- * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
8
- * expires.
9
- *
10
- * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
11
- * Electric resolves header-value functions on every request *and every retry*
12
- * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
13
- * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
14
- *
15
- * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
16
- * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
17
- * single-flight, so an N-shape consistency group does not trigger N refreshes.
18
- */
19
- /**
20
- * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
21
- * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
22
- * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
23
- * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
24
- * whenever *either* a token provider or static headers are present, so a credential-only consumer
25
- * (no per-request token) still sends its headers.
26
- */
27
- export declare function buildShapeHeaders(input: {
28
- getAuthToken?: () => Promise<string | undefined>;
29
- requestHeaders?: Record<string, string>;
30
- }): ExternalHeadersRecord;
31
- /** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
32
- export declare function buildAuthShapeHeaders(getAuthToken: () => Promise<string | undefined>, requestHeaders?: Record<string, string>): ExternalHeadersRecord;
33
- /**
34
- * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
35
- * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
36
- * read-path identity (ADR-0013) and read-stream error surfacing (#4):
37
- *
38
- * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
39
- * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
40
- * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
41
- * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
42
- * makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
43
- * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
44
- * of silently believing the read path is live), then retry transient faults ({@link
45
- * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
46
- * later successful fetch (`onSyncActivity`) clears the degraded status back to live.
47
- */
48
- export declare function createShapeErrorHandler(options?: {
49
- onAuthError?: () => void;
50
- onReadStreamError?: (error: Error) => void;
51
- }): ShapeStreamErrorHandler;
52
- export {};
53
- //# sourceMappingURL=sync-auth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync-auth.d.ts","sourceRoot":"","sources":["../src/sync-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAEtF,yFAAyF;AACzF,KAAK,uBAAuB,GAAG,WAAW,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;GAcG;AACH;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC,GAAG,qBAAqB,CAYxB;AAED,wGAAwG;AACxG,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,EAC/C,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACtC,qBAAqB,CAEvB;AAuCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CAAO,GACrF,uBAAuB,CASzB"}