@pgxsinkit/client 0.2.6 → 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.
- package/README.md +2 -1
- package/dist/boot-report.d.ts +5 -2
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +35 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +90 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.d.ts.map +1 -1
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +47 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6258 -6443
- package/dist/index.js.map +26 -26
- package/dist/local-tables.d.ts +1 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +13 -21
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +8 -8
- package/dist/sync/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +21 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +2 -2
- package/dist/worker/attach-sync-client.d.ts +3 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/package.json +6 -7
- package/skills/core/SKILL.md +72 -55
- package/skills/operating/SKILL.md +120 -120
- package/src/boot-report.ts +4 -3
- package/src/circuits/envelope-to-change.ts +102 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +165 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +641 -0
- package/src/debug.ts +1 -85
- package/src/export-dump.ts +3 -2
- package/src/index.ts +290 -273
- package/src/lazy-guard.ts +1 -1
- package/src/local-tables.ts +9 -2
- package/src/schema.ts +2 -11
- package/src/sync/apply.ts +72 -110
- package/src/sync/copy.ts +15 -15
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +42 -1
- package/src/sync/subscription-state.ts +21 -3
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +8 -1
- package/src/worker/define-sync-worker.ts +122 -13
- package/src/worker/engine-control.ts +89 -0
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
package/src/index.ts
CHANGED
|
@@ -11,7 +11,6 @@ import type {
|
|
|
11
11
|
RegistryRelations,
|
|
12
12
|
RegistryTables,
|
|
13
13
|
RegistryViews,
|
|
14
|
-
SyncConfigInput,
|
|
15
14
|
SyncRuntimeStatus,
|
|
16
15
|
SyncTableCreateInput,
|
|
17
16
|
SyncTableEntry,
|
|
@@ -24,7 +23,6 @@ import type {
|
|
|
24
23
|
} from "@pgxsinkit/contracts";
|
|
25
24
|
import {
|
|
26
25
|
fingerprintRegistry,
|
|
27
|
-
getSyncRegistrySchema,
|
|
28
26
|
getSyncRegistryStorage,
|
|
29
27
|
isClaimsDependentRowFilter,
|
|
30
28
|
resolveStorageDeclaration,
|
|
@@ -35,6 +33,7 @@ import {
|
|
|
35
33
|
import type { CreateOpfsRepackedPGliteOptions, OpfsRepackedPGlite } from "@pgxsinkit/pglite-opfs-repacked";
|
|
36
34
|
|
|
37
35
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
36
|
+
import { startCircuitsSync, type CircuitsGroupSyncResult } from "./circuits/group-sync";
|
|
38
37
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
39
38
|
import { syncDebug, timeAsync } from "./debug";
|
|
40
39
|
import { describeErrorChain } from "./error-chain";
|
|
@@ -91,7 +90,6 @@ import {
|
|
|
91
90
|
generateEphemeralLocalSchemaSql,
|
|
92
91
|
generateLocalSchemaSql,
|
|
93
92
|
} from "./schema";
|
|
94
|
-
import { startConfiguredSync } from "./shape-sync";
|
|
95
93
|
import {
|
|
96
94
|
resolveDeniedBootAuthority,
|
|
97
95
|
type ResolveStoreBootOptions,
|
|
@@ -117,8 +115,8 @@ import {
|
|
|
117
115
|
storeTargetExists,
|
|
118
116
|
type StorePathInput,
|
|
119
117
|
} from "./store-path";
|
|
120
|
-
import {
|
|
121
|
-
import {
|
|
118
|
+
import { DEFAULT_METADATA_SCHEMA } from "./sync/metadata-tables";
|
|
119
|
+
import { deleteSubscriptionState, migrateSubscriptionMetadataTables } from "./sync/subscription-state";
|
|
122
120
|
import { LiveRowsMaterializer } from "./worker/live-diff";
|
|
123
121
|
import {
|
|
124
122
|
createLiveQueryManager,
|
|
@@ -214,6 +212,12 @@ export {
|
|
|
214
212
|
type EngineRelocatedOutcome,
|
|
215
213
|
type ExecutionLimitConfig,
|
|
216
214
|
ExecutionLimitMismatchError,
|
|
215
|
+
PROVISION_STALLED_CODE,
|
|
216
|
+
// The typed refusal a stalled spare-store adoption raises — the companion to `ProvisionExpiredError`
|
|
217
|
+
// above: that one bounds the PROVISION call, this one bounds an ATTACH waiting on the spare.
|
|
218
|
+
ProvisionStalledError,
|
|
219
|
+
provisionStalledFromWire,
|
|
220
|
+
type ProvisionStalledWire,
|
|
217
221
|
} from "./worker/engine-control";
|
|
218
222
|
export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
219
223
|
export {
|
|
@@ -243,7 +247,7 @@ export {
|
|
|
243
247
|
createConvergenceDriver,
|
|
244
248
|
createIntervalConvergenceTrigger,
|
|
245
249
|
} from "./convergence";
|
|
246
|
-
export {
|
|
250
|
+
export { setSyncDebugSink, syncDebug, timeAsync } from "./debug";
|
|
247
251
|
export {
|
|
248
252
|
type AttachedSyncClient,
|
|
249
253
|
attachSyncClient,
|
|
@@ -301,6 +305,34 @@ export {
|
|
|
301
305
|
// The Outbox's object NAMES are public contract like its shape (ADR-0053 decision 2) — inspection
|
|
302
306
|
// surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
|
|
303
307
|
export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
|
|
308
|
+
|
|
309
|
+
// The Circuits-native read transport (ADR-0055 decision 10). Reads terminate on durable-streams
|
|
310
|
+
// through the edge; everything above the transport stays ours.
|
|
311
|
+
export { createTokenRecovery, readShapeStream, STREAM_START } from "./circuits/stream-source";
|
|
312
|
+
export type { ShapeStreamSubscription, StreamBatch, StreamSourceOptions } from "./circuits/stream-source";
|
|
313
|
+
export { createShapeGroup } from "./circuits/shape-group";
|
|
314
|
+
export type { GroupShapeSpec, ShapeGroup, ShapeGroupBatch, ShapeGroupOptions } from "./circuits/shape-group";
|
|
315
|
+
export { envelopeToChange, primaryKeyFromStreamKey } from "./circuits/envelope-to-change";
|
|
316
|
+
export type { ChangeLike } from "./circuits/envelope-to-change";
|
|
317
|
+
export { StreamInbox } from "./circuits/stream-inbox";
|
|
318
|
+
export type { BufferedBatch } from "./circuits/stream-inbox";
|
|
319
|
+
export { createBarrierReader, openSubscriptionSession } from "./circuits/subscription-client";
|
|
320
|
+
export type {
|
|
321
|
+
GrantedStream,
|
|
322
|
+
RefusedStream,
|
|
323
|
+
ShapeSubscriptionRequest,
|
|
324
|
+
SubscriptionClientOptions,
|
|
325
|
+
SubscriptionSession,
|
|
326
|
+
} from "./circuits/subscription-client";
|
|
327
|
+
export { startCircuitsSync } from "./circuits/group-sync";
|
|
328
|
+
export type { CircuitsGroupSyncOptions, CircuitsGroupSyncResult, CircuitsTableSyncResult } from "./circuits/group-sync";
|
|
329
|
+
export { syncCircuitsShapes } from "./circuits/sync-engine";
|
|
330
|
+
export type {
|
|
331
|
+
CircuitsShapeSpec,
|
|
332
|
+
CircuitsSyncHandle,
|
|
333
|
+
CircuitsSyncOptions,
|
|
334
|
+
ConvergenceBarrier,
|
|
335
|
+
} from "./circuits/sync-engine";
|
|
304
336
|
export {
|
|
305
337
|
type AllMutationsView,
|
|
306
338
|
getAllMutationsView,
|
|
@@ -359,11 +391,11 @@ export class ClientDisposedError extends Error {
|
|
|
359
391
|
}
|
|
360
392
|
}
|
|
361
393
|
|
|
362
|
-
// The store carries PGlite's own `live` extension
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
//
|
|
366
|
-
export type ClientPGlite = PGliteWithLive
|
|
394
|
+
// The store carries PGlite's own `live` extension and nothing else. The pgxsinkit sync runtime is not an
|
|
395
|
+
// extension at all (ADR-0032 S1): `createSyncClient` starts it BESIDE the store (`startCircuitsSync`)
|
|
396
|
+
// rather than attaching a namespace to the instance, so a store's type is exactly PGlite + `live`
|
|
397
|
+
// whether or not sync ever runs on it.
|
|
398
|
+
export type ClientPGlite = PGliteWithLive;
|
|
367
399
|
|
|
368
400
|
/**
|
|
369
401
|
* The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
|
|
@@ -451,19 +483,22 @@ const OPFS_OPEN_BACKOFF_MS = 100;
|
|
|
451
483
|
/** The opfs-repacked store extent size (ADR-0049 step 10a). */
|
|
452
484
|
const OPFS_STORE_EXTENT_SIZE = 65536;
|
|
453
485
|
/**
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
|
|
458
|
-
const READ_STREAM_UNREACHABLE = "read stream unreachable: a shape fetch failed and is retrying with backoff";
|
|
459
|
-
/**
|
|
460
|
-
* Default {@link CreateSyncClientOptions.readSilenceMs}. A healthy Electric read path is never silent —
|
|
461
|
-
* the live long-poll cycles roughly every 20-25s with at least a bare up-to-date, and every cycle fires
|
|
462
|
-
* `onSyncActivity` — so two full cycles of nothing while claiming `ready` is evidence, not caution.
|
|
486
|
+
* Default {@link CreateSyncClientOptions.readSilenceMs}. A healthy read path is never silent — the live
|
|
487
|
+
* long-poll returns on every hold, `204` with `stream-up-to-date` when nothing arrived, and every
|
|
488
|
+
* response fires `onSyncActivity` — so two full cycles of nothing while claiming `ready` is evidence,
|
|
489
|
+
* not caution.
|
|
463
490
|
*/
|
|
464
491
|
const READ_SILENCE_MS = 45_000;
|
|
465
492
|
/** `status.lastError` for the read-silence watchdog: nothing failed — that is exactly the problem. */
|
|
466
493
|
const READ_STREAM_SILENT = "read stream silent: no server response inside the silence window while reporting ready";
|
|
494
|
+
/** `status.lastError` while subscribe keeps failing for a reason the subject cannot act on. */
|
|
495
|
+
const CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is failing and retrying";
|
|
496
|
+
/**
|
|
497
|
+
* `status.lastError` while a live read has died and its group is re-subscribing (ADR-0056 decision 7,
|
|
498
|
+
* backlog 0010). Distinct from {@link READ_STREAM_SILENT}, which is the opposite evidence: nothing
|
|
499
|
+
* failed, and that is the problem.
|
|
500
|
+
*/
|
|
501
|
+
const STREAM_LOST = "read stream lost; re-subscribing";
|
|
467
502
|
/**
|
|
468
503
|
* Non-enumerable brand stamped on an opfs-repacked instance {@link createClientPGlite} mints (ADR-0049): the
|
|
469
504
|
* opfs-repacked VFS owns its store on a dedicated OPFS directory and reports NO `dataDir` (a custom VFS, the
|
|
@@ -506,7 +541,7 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
|
|
|
506
541
|
|
|
507
542
|
/**
|
|
508
543
|
* Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
|
|
509
|
-
* {@link createSyncClient} makes internally (the `
|
|
544
|
+
* {@link createSyncClient} makes internally (the `live` extension, pre-warmed boot-asset
|
|
510
545
|
* consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
|
|
511
546
|
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
512
547
|
* instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
|
|
@@ -582,16 +617,24 @@ export async function createClientPGlite(
|
|
|
582
617
|
const createOpfsRepacked =
|
|
583
618
|
options?.pgliteFactories?.createOpfsRepacked ??
|
|
584
619
|
(await import("@pgxsinkit/pglite-opfs-repacked")).createOpfsRepackedPGlite;
|
|
620
|
+
// A create that never returns used to leave the rail at `boot pglite.create start` with nothing after
|
|
621
|
+
// it — indistinguishable from a lost worker. These four phase lines split the create into its long
|
|
622
|
+
// steps (module load, directory handle, handle acquisition, PGlite boot), so a stall is attributable.
|
|
623
|
+
syncDebug("boot pglite.create phase", { phase: "module-loaded" });
|
|
585
624
|
const getStoreDirectoryHandle =
|
|
586
625
|
options?.pgliteFactories?.getStoreDirectoryHandle ??
|
|
587
626
|
(() => createOpfsEffects(storePath).getStoreDirectoryHandle());
|
|
588
627
|
const directory = await getStoreDirectoryHandle();
|
|
628
|
+
syncDebug("boot pglite.create phase", { phase: "directory-ready" });
|
|
589
629
|
return openWithBoundedRetries(
|
|
590
630
|
() =>
|
|
591
631
|
createOpfsRepacked({
|
|
592
632
|
directory: directory as CreateOpfsRepackedPGliteOptions["directory"],
|
|
593
633
|
durability: relaxedDurability ? "relaxed" : "strict",
|
|
594
634
|
extentSize: OPFS_STORE_EXTENT_SIZE,
|
|
635
|
+
// The factory's own two phases: handles acquired (`vfs-opened`) and PGlite booted
|
|
636
|
+
// (`pglite-ready`). Same rail line, so one grep shows the whole create.
|
|
637
|
+
onPhase: (phase) => syncDebug("boot pglite.create phase", { phase }),
|
|
595
638
|
// The store is engine-less by construction (only `live` is a create-time extension); the sync
|
|
596
639
|
// engine attaches post-create (ADR-0032 S1). Restore + pre-warmed boot assets ride the same
|
|
597
640
|
// `pglite` sub-options the idb path uses.
|
|
@@ -631,11 +674,11 @@ export async function createClientPGlite(
|
|
|
631
674
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
632
675
|
// create (the store initdbs empty).
|
|
633
676
|
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
634
|
-
// Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync
|
|
635
|
-
// (ADR-0032 S1) — it
|
|
636
|
-
//
|
|
637
|
-
//
|
|
638
|
-
//
|
|
677
|
+
// Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync runtime is NOT
|
|
678
|
+
// (ADR-0032 S1) — `createSyncClient` starts it beside the store, never on it. So a store minted here
|
|
679
|
+
// is deliberately SYNC-LESS by construction: a spare/pre-warmed store (e.g. the board's login-screen
|
|
680
|
+
// mint) carries no subscription session, no shape streams, and no open stream connections until it
|
|
681
|
+
// is claimed and handed to `createSyncClient`.
|
|
639
682
|
extensions: {
|
|
640
683
|
live,
|
|
641
684
|
},
|
|
@@ -646,8 +689,8 @@ export async function createClientPGlite(
|
|
|
646
689
|
// Stamp the resolved durability mode + store scheme so every boot-rail capture shows the mode and lane the
|
|
647
690
|
// store was created under (ADR-0047 diagnosability).
|
|
648
691
|
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
649
|
-
// `as unknown as` because the raw store is deliberately
|
|
650
|
-
// extension);
|
|
692
|
+
// `as unknown as` because the raw store is deliberately sync-less here (only `live` is a create-time
|
|
693
|
+
// extension); the sync runtime never lands on the instance at all (ADR-0032 S1).
|
|
651
694
|
)) as unknown as ClientPGlite;
|
|
652
695
|
return pglite;
|
|
653
696
|
}
|
|
@@ -921,7 +964,23 @@ export async function fallbackVirginCandidateToIdb(
|
|
|
921
964
|
|
|
922
965
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
923
966
|
registry: TRegistry;
|
|
924
|
-
|
|
967
|
+
/**
|
|
968
|
+
* The pgxsinkit control plane: where a client subscribes, re-mints its stream token, and reads the
|
|
969
|
+
* engine convergence barrier (ADR-0055). Required, with {@link streamBaseUrl}.
|
|
970
|
+
*
|
|
971
|
+
* The client does not CONSTRUCT stream URLs, it **asks** and is told. Which shapes a subject may
|
|
972
|
+
* read — and, on the shared tier, which scopes each expands to — is not something the client can
|
|
973
|
+
* express at all, which is what removes shape selection from the wire.
|
|
974
|
+
*/
|
|
975
|
+
controlPlaneUrl: string;
|
|
976
|
+
/**
|
|
977
|
+
* The edge that serves durable-streams reads. Granted stream paths are appended to it.
|
|
978
|
+
*
|
|
979
|
+
* Separate from {@link controlPlaneUrl} because they are different deployments: the control plane
|
|
980
|
+
* is a small authenticated origin, and this is the CDN-frontable read surface the shared tier
|
|
981
|
+
* exists to make cacheable.
|
|
982
|
+
*/
|
|
983
|
+
streamBaseUrl: string;
|
|
925
984
|
batchWriteUrl: string;
|
|
926
985
|
getAuthToken?: () => Promise<string | undefined>;
|
|
927
986
|
/**
|
|
@@ -933,22 +992,23 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
933
992
|
requestHeaders?: Record<string, string>;
|
|
934
993
|
/**
|
|
935
994
|
* Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
|
|
936
|
-
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`).
|
|
937
|
-
* see these. The seam exists because the two ingress points have opposite geometry:
|
|
938
|
-
* function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header)
|
|
939
|
-
* chatty function→DB protocol on a ~1ms loop; the read
|
|
940
|
-
*
|
|
941
|
-
*
|
|
942
|
-
* (e.g. `apikey`) in
|
|
995
|
+
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Control-plane and stream
|
|
996
|
+
* requests never see these. The seam exists because the two ingress points have opposite geometry:
|
|
997
|
+
* the write function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header)
|
|
998
|
+
* keeps its chatty function→DB protocol on a ~1ms loop; the read path terminates on the stream edge
|
|
999
|
+
* in front of durable-streams, so pinning reads to the database's region rather than the caller's
|
|
1000
|
+
* pays an intercontinental round trip on every catch-up hop and every long-poll cycle. Put
|
|
1001
|
+
* region/DB-affinity headers here; keep gateway credentials the reads also need (e.g. `apikey`) in
|
|
1002
|
+
* the shared {@link requestHeaders}.
|
|
943
1003
|
*/
|
|
944
1004
|
writeRequestHeaders?: Record<string, string>;
|
|
945
1005
|
syncEnabled?: boolean;
|
|
946
1006
|
/**
|
|
947
1007
|
* The read-silence window (ms) after which a runtime claiming `ready` drops to `degraded` (reason
|
|
948
|
-
* "stream"). A pulled cable HANGS the live long-poll — nothing fails
|
|
949
|
-
*
|
|
950
|
-
*
|
|
951
|
-
*
|
|
1008
|
+
* "stream"). A pulled cable HANGS the live long-poll — nothing fails, nothing delivers — so without this
|
|
1009
|
+
* a session that once reached `ready` would report "up to date" for as long as the outage lasts. A
|
|
1010
|
+
* healthy stream is never silent: durable-streams answers every long-poll hold that times out with a
|
|
1011
|
+
* bare up-to-date response, so the default of 45s spans several cycles. Self-recovering: the next delivered batch
|
|
952
1012
|
* returns `ready`. Status honesty only — nothing is retired or torn down.
|
|
953
1013
|
*/
|
|
954
1014
|
readSilenceMs?: number;
|
|
@@ -1786,6 +1846,39 @@ export function replAdapter(
|
|
|
1786
1846
|
};
|
|
1787
1847
|
}
|
|
1788
1848
|
|
|
1849
|
+
/**
|
|
1850
|
+
* The read transport this boot runs on: the control plane that grants subscriptions, and the edge that
|
|
1851
|
+
* serves the streams it names.
|
|
1852
|
+
*
|
|
1853
|
+
* Both, resolved once at boot. They are separate deployments (ADR-0055 decision 8) and neither is
|
|
1854
|
+
* usable without the other, so a missing one is refused rather than defaulted — a client that derived
|
|
1855
|
+
* the other would sync against an ingress its caller never named, which is precisely the class of
|
|
1856
|
+
* mistake the native path's ask-don't-construct inversion exists to remove.
|
|
1857
|
+
*/
|
|
1858
|
+
interface ReadTransport {
|
|
1859
|
+
controlPlaneUrl: string;
|
|
1860
|
+
streamBaseUrl: string;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
function resolveReadTransport(options: { controlPlaneUrl?: string; streamBaseUrl?: string }): ReadTransport {
|
|
1864
|
+
if (options.controlPlaneUrl == null || options.controlPlaneUrl === "") {
|
|
1865
|
+
throw new Error(
|
|
1866
|
+
"[pgxsinkit] createSyncClient needs `controlPlaneUrl` + `streamBaseUrl` — the control plane grants " +
|
|
1867
|
+
"the streams this client may read, and the edge serves them.",
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
if (options.streamBaseUrl == null || options.streamBaseUrl === "") {
|
|
1871
|
+
throw new Error(
|
|
1872
|
+
"[pgxsinkit] `controlPlaneUrl` needs `streamBaseUrl` beside it: the control plane grants stream " +
|
|
1873
|
+
"paths and the edge serves them, and they are separate deployments.",
|
|
1874
|
+
);
|
|
1875
|
+
}
|
|
1876
|
+
return { controlPlaneUrl: options.controlPlaneUrl, streamBaseUrl: options.streamBaseUrl };
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
/** What a started sync exposes to the client. */
|
|
1880
|
+
type SyncGroupsRuntime = CircuitsGroupSyncResult;
|
|
1881
|
+
|
|
1789
1882
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1790
1883
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1791
1884
|
): Promise<SyncClient<TRegistry>> {
|
|
@@ -1854,10 +1947,15 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1854
1947
|
// ledger. The decision is taken in the restore recovery block below (it needs the quarantine count) and
|
|
1855
1948
|
// honours an explicit `syncEnabled: false`. A normal boot resolves its final value here, up front.
|
|
1856
1949
|
let syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1857
|
-
//
|
|
1858
|
-
//
|
|
1859
|
-
//
|
|
1860
|
-
const
|
|
1950
|
+
// Which read transport this boot uses. Resolved once, up front, and REFUSED when the answer is
|
|
1951
|
+
// ambiguous: two transports configured is a contradiction and none is an omission, and picking a
|
|
1952
|
+
// winner for either would silently sync against something the caller did not name.
|
|
1953
|
+
const readTransport = resolveReadTransport(options);
|
|
1954
|
+
// ADR-0032 S4 overlap prefetch is NOT available on the native read path: it works by holding commits
|
|
1955
|
+
// on a `dbReady` gate while the streams prefetch, and the native engine has no such gate. Boot is
|
|
1956
|
+
// strictly sequential until it grows one (backlog 0012). Kept as a named constant rather than deleted
|
|
1957
|
+
// because the boot report and several branches below are written against the concept.
|
|
1958
|
+
const overlapPrefetch = false;
|
|
1861
1959
|
// How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
|
|
1862
1960
|
// backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
|
|
1863
1961
|
// everything else is a warm (existing persisted) store. Restore wins — a restore boot is never "fresh".
|
|
@@ -2142,17 +2240,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2142
2240
|
}
|
|
2143
2241
|
|
|
2144
2242
|
// Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths
|
|
2145
|
-
// (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time
|
|
2146
|
-
// extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
|
|
2147
|
-
// `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
|
|
2148
|
-
// structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
|
|
2149
|
-
// BEFORE the schema/prepare steps below so a `prepareLocalDbAfterSchema` hook sees the same `.electric` it did when
|
|
2150
|
-
// the extension provided it at create time. `engine.close` (the former extension close hook — abort every
|
|
2151
|
-
// shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
|
|
2152
|
-
// `pglite.close()` used to trigger it.
|
|
2153
|
-
const engine: SyncEngine = await createSyncEngine(pglite);
|
|
2154
|
-
(pglite as { electric: SyncEngine["namespace"] }).electric = engine.namespace;
|
|
2155
|
-
|
|
2156
2243
|
// Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to
|
|
2157
2244
|
// the right steady-state phase (`ready` if already caught up, else `syncing`).
|
|
2158
2245
|
let initialSyncCompleted = false;
|
|
@@ -2191,157 +2278,125 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2191
2278
|
}, readSilenceMs);
|
|
2192
2279
|
};
|
|
2193
2280
|
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2281
|
+
/**
|
|
2282
|
+
* The native path's auth adapter.
|
|
2283
|
+
*
|
|
2284
|
+
* The SAME token lifecycle the write path uses (ADR-0003/ADR-0013), resolved per request rather
|
|
2285
|
+
* than captured — a subscription outlives its token by design. The static `requestHeaders` ride
|
|
2286
|
+
* along for the deployment gateway; a resolved `Authorization` wins over anything they carry, so a
|
|
2287
|
+
* gateway credential can never shadow the subject's own.
|
|
2288
|
+
*/
|
|
2289
|
+
const nativeAuthHeaders = async (): Promise<Record<string, string>> => {
|
|
2290
|
+
const headers: Record<string, string> = { ...(options.requestHeaders ?? {}) };
|
|
2291
|
+
const token = await options.getAuthToken?.();
|
|
2292
|
+
if (token != null && token !== "") headers["Authorization"] = `Bearer ${token}`;
|
|
2293
|
+
return headers;
|
|
2294
|
+
};
|
|
2208
2295
|
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
|
|
2234
|
-
// Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and
|
|
2235
|
-
// re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).
|
|
2236
|
-
onGroupReady: (groupKey) => {
|
|
2237
|
-
status.groups = { ...(status.groups ?? {}), [groupKey]: true };
|
|
2238
|
-
options.onStatusChange?.(status);
|
|
2239
|
-
},
|
|
2240
|
-
onInitialSync: () => {
|
|
2241
|
-
initialSyncCompleted = true;
|
|
2242
|
-
status.phase = "ready";
|
|
2243
|
-
options.onStatusChange?.(status);
|
|
2244
|
-
// Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp
|
|
2245
|
-
// closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).
|
|
2246
|
-
syncDebug("boot client ready");
|
|
2247
|
-
// Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`
|
|
2248
|
-
// rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own
|
|
2249
|
-
// finalize below never double-fires it.
|
|
2250
|
-
finalizeBootReport();
|
|
2251
|
-
resolveReady();
|
|
2252
|
-
// `ready` is now a CLAIM the watchdog holds to account: silence past the window drops it back to
|
|
2253
|
-
// degraded — the "up to date offline" lie a hung long-poll otherwise sustains.
|
|
2254
|
-
armReadSilenceWatchdog();
|
|
2255
|
-
},
|
|
2256
|
-
onSyncError: (error) => {
|
|
2257
|
-
// A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than
|
|
2258
|
-
// letting the read cache silently diverge from the server. Sticky (see below).
|
|
2259
|
-
status.phase = "degraded";
|
|
2260
|
-
degradedReason = "commit";
|
|
2261
|
-
// The cause chain, not just the wrapper: a drizzle "Failed query" message hides the actual
|
|
2262
|
-
// database error (SQLSTATE, detail) on `.cause`.
|
|
2263
|
-
status.lastError = describeErrorChain(error);
|
|
2264
|
-
options.onStatusChange?.(status);
|
|
2265
|
-
options.onSyncError?.(error);
|
|
2266
|
-
},
|
|
2267
|
-
// #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting
|
|
2268
|
-
// healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a
|
|
2269
|
-
// commit-failure degraded. Cleared on the next successful batch below.
|
|
2270
|
-
onReadStreamError: (error) => {
|
|
2271
|
-
// Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is
|
|
2272
|
-
// the more serious signal — a stream blip must not overwrite it).
|
|
2273
|
-
if (status.phase === "auth-needed") return;
|
|
2274
|
-
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2275
|
-
// Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most
|
|
2276
|
-
// recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one
|
|
2277
|
-
// way then another reports the current cause (observability).
|
|
2278
|
-
status.phase = "degraded";
|
|
2279
|
-
degradedReason = "stream";
|
|
2280
|
-
status.lastError = describeErrorChain(error);
|
|
2281
|
-
options.onStatusChange?.(status);
|
|
2282
|
-
},
|
|
2283
|
-
// Board ADR-0010: a shape FETCH ATTEMPT failed and Electric is retrying it inside its own backoff
|
|
2284
|
-
// wrapper. This is the only signal an outage produces — a rejected fetch is retryable, so it never
|
|
2285
|
-
// escapes to `onError` and `onReadStreamError` above is never called (Electric retries forever:
|
|
2286
|
-
// "clients may go offline and come back"). Without this the runtime reports `syncing` for as long as
|
|
2287
|
-
// the machine is offline, and a consumer keying off the phase can never say "connection needed". The
|
|
2288
|
-
// two seams partition the failures (see `read-stream-stall.ts`), so this can never pre-empt the
|
|
2289
|
-
// richer classification: an auth 4xx escapes the wrapper and lands on `onAuthError`, not here.
|
|
2290
|
-
//
|
|
2291
|
-
// TRANSITION-only: Electric calls this on every retry tick for as long as the outage lasts, so
|
|
2292
|
-
// re-entering `degraded` would re-emit to every status listener (and, in worker mode, re-broadcast to
|
|
2293
|
-
// every attached tab) roughly once a second, forever. Precedence matches `onReadStreamError`: never
|
|
2294
|
-
// mask `auth-needed` (more actionable) nor a commit-failure degraded (more serious).
|
|
2295
|
-
onReadStreamStalled: () => {
|
|
2296
|
-
if (status.phase === "auth-needed" || status.phase === "degraded") return;
|
|
2297
|
-
status.phase = "degraded";
|
|
2298
|
-
degradedReason = "stream";
|
|
2299
|
-
status.lastError = READ_STREAM_UNREACHABLE;
|
|
2300
|
-
options.onStatusChange?.(status);
|
|
2301
|
-
},
|
|
2302
|
-
// Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
|
|
2303
|
-
// again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,
|
|
2304
|
-
// so only `onSyncError` clearing (a clean commit) would lift it.
|
|
2305
|
-
onSyncActivity: () => {
|
|
2306
|
-
if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
|
|
2307
|
-
degradedReason = null;
|
|
2308
|
-
status.phase = initialSyncCompleted ? "ready" : "syncing";
|
|
2296
|
+
/**
|
|
2297
|
+
* Start sync on whichever read transport this boot resolved.
|
|
2298
|
+
*
|
|
2299
|
+
* The single place the read path is started. Everything above it — status, readiness, the boot
|
|
2300
|
+
* report, the activation replay — is written against {@link SyncGroupsRuntime}.
|
|
2301
|
+
*/
|
|
2302
|
+
const startSyncRuntime = (promotedGroups: ReadonlySet<string>): Promise<SyncGroupsRuntime> =>
|
|
2303
|
+
startCircuitsSync(pglite, {
|
|
2304
|
+
registry: options.registry,
|
|
2305
|
+
controlPlaneUrl: readTransport.controlPlaneUrl,
|
|
2306
|
+
streamBaseUrl: readTransport.streamBaseUrl,
|
|
2307
|
+
metadataSchema: DEFAULT_METADATA_SCHEMA,
|
|
2308
|
+
promotedGroups,
|
|
2309
|
+
// ADR-0034: the per-group rows of the boot report. Only the boot starts open an accumulator.
|
|
2310
|
+
bootCollector: bootReportBuilder,
|
|
2311
|
+
// Teardown must be able to reach the read path BEFORE this promise resolves. A stop while the
|
|
2312
|
+
// first subscribe is still in flight has no runtime handle to unsubscribe — and that is exactly
|
|
2313
|
+
// the window where a stop is most likely, since an unreachable control plane is why the boot is
|
|
2314
|
+
// still running. Without this, `stop()` waits on a TCP connect to a host that is not answering.
|
|
2315
|
+
signal: readPathAbort.signal,
|
|
2316
|
+
...(options.getAuthToken || options.requestHeaders ? { authHeaders: nativeAuthHeaders } : {}),
|
|
2317
|
+
onInitialSync: () => {
|
|
2318
|
+
initialSyncCompleted = true;
|
|
2319
|
+
status.phase = "ready";
|
|
2309
2320
|
options.onStatusChange?.(status);
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2321
|
+
syncDebug("boot client ready");
|
|
2322
|
+
finalizeBootReport();
|
|
2323
|
+
resolveReady();
|
|
2324
|
+
armReadSilenceWatchdog();
|
|
2325
|
+
},
|
|
2326
|
+
onGroupReady: (groupKey: string) => {
|
|
2327
|
+
status.groups = { ...(status.groups ?? {}), [groupKey]: true };
|
|
2328
|
+
options.onStatusChange?.(status);
|
|
2329
|
+
},
|
|
2330
|
+
onSyncError: (error: Error) => {
|
|
2331
|
+
status.phase = "degraded";
|
|
2332
|
+
degradedReason = "commit";
|
|
2333
|
+
status.lastError = describeErrorChain(error);
|
|
2334
|
+
options.onStatusChange?.(status);
|
|
2335
|
+
options.onSyncError?.(error);
|
|
2336
|
+
},
|
|
2337
|
+
// A subscribe that keeps failing on the deployment's side. Recoverable, so it takes the
|
|
2338
|
+
// `stream` reason rather than `commit`: the first delivered batch clears it.
|
|
2339
|
+
//
|
|
2340
|
+
// Precedence, and both halves matter. It never masks `auth-needed` (more actionable — the
|
|
2341
|
+
// subject can fix that one themselves), and it never masks a commit-failure degraded (more
|
|
2342
|
+
// serious — its `lastError` names a store that is diverging, which a transport blip must not
|
|
2343
|
+
// overwrite, and which the delivered-batch recovery must not then lift).
|
|
2344
|
+
//
|
|
2345
|
+
// It DOES refresh a stream-degraded status on each new fault rather than freezing on the
|
|
2346
|
+
// first, so a control plane that fails one way and then another reports its current cause.
|
|
2347
|
+
onSubscribeError: (error: Error) => {
|
|
2348
|
+
if (status.phase === "auth-needed") return;
|
|
2349
|
+
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2350
|
+
status.phase = "degraded";
|
|
2351
|
+
degradedReason = "stream";
|
|
2352
|
+
status.lastError = `${CONTROL_PLANE_UNREACHABLE}: ${describeErrorChain(error)}`;
|
|
2353
|
+
options.onStatusChange?.(status);
|
|
2354
|
+
},
|
|
2355
|
+
// A live read that ended — a stream the engine evicted, a `403` past a re-mint, a lost
|
|
2356
|
+
// connection — with the group already re-subscribing behind it. Same precedence and the same
|
|
2357
|
+
// recovery as `onSubscribeError`, because it is the same kind of fault: the transport, not the
|
|
2358
|
+
// store. It never masks `auth-needed` (the subject can fix that one) and never masks a
|
|
2359
|
+
// commit-failure degraded (that one names a store that is diverging), and the next delivered
|
|
2360
|
+
// batch clears it.
|
|
2361
|
+
onStreamError: (error: Error) => {
|
|
2362
|
+
if (status.phase === "auth-needed") return;
|
|
2363
|
+
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2364
|
+
status.phase = "degraded";
|
|
2365
|
+
degradedReason = "stream";
|
|
2366
|
+
status.lastError = `${STREAM_LOST}: ${describeErrorChain(error)}`;
|
|
2367
|
+
options.onStatusChange?.(status);
|
|
2368
|
+
},
|
|
2369
|
+
// ADR-0013: a persistent read-path auth failure is its own status — the app prompts re-login
|
|
2370
|
+
// while subscribe keeps retrying for a fresh token. Only wired when a token provider exists;
|
|
2371
|
+
// without one there is no auth lifecycle to track.
|
|
2372
|
+
...(options.getAuthToken
|
|
2373
|
+
? {
|
|
2374
|
+
onAuthError: () => {
|
|
2375
|
+
if (status.phase === "auth-needed") return;
|
|
2322
2376
|
status.phase = "auth-needed";
|
|
2377
|
+
delete status.lastError;
|
|
2323
2378
|
options.onStatusChange?.(status);
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2379
|
+
},
|
|
2380
|
+
}
|
|
2381
|
+
: {}),
|
|
2382
|
+
onSyncActivity: () => {
|
|
2383
|
+
// A delivered batch is proof of life, so the two RECOVERABLE statuses clear here: an
|
|
2384
|
+
// `auth-needed` whose fresh token has started working (ADR-0013), and a `degraded` whose
|
|
2385
|
+
// reason was the read stream. Never a commit failure — that one is sticky by design
|
|
2386
|
+
// (ADR-0009 d5), because a fetch can keep succeeding while applies keep failing, and
|
|
2387
|
+
// clearing it on traffic would report healthy while the store diverges.
|
|
2388
|
+
if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
|
|
2389
|
+
status.phase = initialSyncCompleted ? "ready" : "syncing";
|
|
2390
|
+
degradedReason = null;
|
|
2391
|
+
delete status.lastError;
|
|
2392
|
+
options.onStatusChange?.(status);
|
|
2326
2393
|
}
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
let earlySync: ReturnType<typeof startConfiguredSync> | null = null;
|
|
2334
|
-
let earlySyncStartedAt = 0;
|
|
2335
|
-
if (overlapPrefetch) {
|
|
2336
|
-
status.isRunning = true;
|
|
2337
|
-
status.phase = "syncing";
|
|
2338
|
-
options.onStatusChange?.(status);
|
|
2339
|
-
earlySyncStartedAt = performance.now();
|
|
2340
|
-
earlySync = startConfiguredSync(
|
|
2341
|
-
pglite as unknown as Parameters<typeof startConfiguredSync>[0],
|
|
2342
|
-
buildStartOptions(new Set()),
|
|
2343
|
-
);
|
|
2344
|
-
}
|
|
2394
|
+
armReadSilenceWatchdog();
|
|
2395
|
+
},
|
|
2396
|
+
onLazyActivated: (groupKey: string) => {
|
|
2397
|
+
void writeLazyGroupActivation(pglite, options.registry, groupKey);
|
|
2398
|
+
},
|
|
2399
|
+
});
|
|
2345
2400
|
|
|
2346
2401
|
if (!options.pgliteInstance) {
|
|
2347
2402
|
if (options.prepareLocalDbBeforeSchema) {
|
|
@@ -2514,7 +2569,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2514
2569
|
// Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
|
|
2515
2570
|
const lazyGuardIndex = buildLazyGuardIndex(options.registry);
|
|
2516
2571
|
|
|
2517
|
-
let sync:
|
|
2572
|
+
let sync: SyncGroupsRuntime | null = null;
|
|
2518
2573
|
let convergenceDriver: ConvergenceDriver | null = null;
|
|
2519
2574
|
let eventFlushDriver: EventFlushDriver | null = null;
|
|
2520
2575
|
|
|
@@ -2538,6 +2593,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2538
2593
|
// to tell "sync disabled" (trivially ready) apart from "sync pending" (not yet ready / hydrating).
|
|
2539
2594
|
const isSyncPending = (): boolean => syncEnabled && sync == null && !disposed;
|
|
2540
2595
|
|
|
2596
|
+
/** Aborts the read path's control-plane traffic on teardown — see `haltActivity`. */
|
|
2597
|
+
const readPathAbort = new AbortController();
|
|
2598
|
+
|
|
2541
2599
|
// Quiesce the background write/sync tail before a teardown (ADR-0041 BLOCKER 2). `stop()`/`destroy()` can be
|
|
2542
2600
|
// called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails
|
|
2543
2601
|
// at its next stage boundary (never starting sync after this), gracefully release any read seam parked on
|
|
@@ -2576,7 +2634,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2576
2634
|
// The Event lane's in-flight POST is aborted on the same synchronous edge as the write path's: a flush
|
|
2577
2635
|
// must not still be settling verdicts into a store the teardown is about to close.
|
|
2578
2636
|
eventLane?.abortInFlight();
|
|
2579
|
-
|
|
2637
|
+
// Covers the read path whether or not sync has finished starting: `sync` is still null while the
|
|
2638
|
+
// first subscribe is in flight, and that is the case this abort exists for.
|
|
2639
|
+
readPathAbort.abort();
|
|
2640
|
+
sync?.unsubscribe();
|
|
2580
2641
|
void convergenceDriver?.stop();
|
|
2581
2642
|
void eventFlushDriver?.stop();
|
|
2582
2643
|
};
|
|
@@ -2605,23 +2666,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2605
2666
|
if (disposed) return;
|
|
2606
2667
|
status.isRunning = true;
|
|
2607
2668
|
|
|
2608
|
-
//
|
|
2609
|
-
//
|
|
2610
|
-
//
|
|
2611
|
-
|
|
2669
|
+
// Provision the subscription metadata store BEFORE anything reads it. The removed ingest engine did
|
|
2670
|
+
// this inside its own construction; the native path has no engine object, so it belongs here.
|
|
2671
|
+
//
|
|
2672
|
+
// Unconditional, outside the `syncEnabled` branch, for two reasons. Every sync-enabled boot reads a
|
|
2673
|
+
// cursor whether or not a reset was asked for — and `desync`/`discardEphemeral` clear one on a
|
|
2674
|
+
// client that may have booted with sync off, so the relations cannot be a function of a runtime
|
|
2675
|
+
// flag. It is also cheap and idempotent: `IF NOT EXISTS` throughout, and the session-scoped halves
|
|
2676
|
+
// (ADR-0042) have to be re-created every boot regardless, since they live in `pg_temp`.
|
|
2677
|
+
await migrateSubscriptionMetadataTables({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA });
|
|
2678
|
+
if (disposed) return;
|
|
2612
2679
|
|
|
2613
2680
|
if (syncEnabled) {
|
|
2614
|
-
|
|
2615
|
-
//
|
|
2616
|
-
//
|
|
2617
|
-
// `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
|
|
2618
|
-
// off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
|
|
2619
|
-
sync = await earlySync;
|
|
2620
|
-
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
2621
|
-
bootReportBuilder.markSyncStartDone();
|
|
2622
|
-
} else {
|
|
2623
|
-
// Sequential path (warm store / no fresh hint): apply any explicit subscription resets, promote
|
|
2624
|
-
// durable lazy groups, then start (catch-up strictly after the local phases).
|
|
2681
|
+
{
|
|
2682
|
+
// Apply any explicit subscription resets, promote durable lazy groups, then start — catch-up
|
|
2683
|
+
// strictly after the local phases (ADR-0032 S4's overlap has no native form; backlog 0012).
|
|
2625
2684
|
const resetKeys =
|
|
2626
2685
|
versionEvent?.status === "rebuilt"
|
|
2627
2686
|
? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
|
|
@@ -2639,12 +2698,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2639
2698
|
const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
|
|
2640
2699
|
if (disposed) return;
|
|
2641
2700
|
|
|
2642
|
-
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
|
|
2643
|
-
startConfiguredSync(
|
|
2644
|
-
pglite as unknown as Parameters<typeof startConfiguredSync>[0],
|
|
2645
|
-
buildStartOptions(promotedGroups),
|
|
2646
|
-
),
|
|
2647
|
-
);
|
|
2701
|
+
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startSyncRuntime(promotedGroups));
|
|
2648
2702
|
bootReportBuilder.markSyncStartDone();
|
|
2649
2703
|
}
|
|
2650
2704
|
// If a stop landed DURING the sync-start await, unsubscribe the just-started streams here rather than
|
|
@@ -2928,7 +2982,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2928
2982
|
// The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both
|
|
2929
2983
|
// revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes
|
|
2930
2984
|
// unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted
|
|
2931
|
-
//
|
|
2985
|
+
// stream subscription (so re-activation re-streams from scratch), then clean-truncate every member's
|
|
2932
2986
|
// local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own
|
|
2933
2987
|
// diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.
|
|
2934
2988
|
const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {
|
|
@@ -2950,7 +3004,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2950
3004
|
}
|
|
2951
3005
|
|
|
2952
3006
|
const activeSync = sync;
|
|
2953
|
-
// The group key IS the
|
|
3007
|
+
// The group key IS the read-path subscription key (`consistencyGroup ?? shapeKey`); fall back to the
|
|
2954
3008
|
// registry derivation when sync is disabled.
|
|
2955
3009
|
const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
|
|
2956
3010
|
// Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and
|
|
@@ -2958,7 +3012,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2958
3012
|
// holds the relation dormant again.
|
|
2959
3013
|
if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
|
|
2960
3014
|
if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
|
|
2961
|
-
// CRITICAL: delete the group's persisted
|
|
3015
|
+
// CRITICAL: delete the group's persisted stream subscription so a later re-activation re-streams the
|
|
2962
3016
|
// shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
|
|
2963
3017
|
// truncate below — leaving the relation permanently missing its pre-desync data.
|
|
2964
3018
|
if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
|
|
@@ -3184,7 +3238,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3184
3238
|
// Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
|
|
3185
3239
|
// point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
|
|
3186
3240
|
// preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
|
|
3187
|
-
|
|
3241
|
+
sync?.unsubscribe();
|
|
3188
3242
|
// Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any
|
|
3189
3243
|
// keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
|
|
3190
3244
|
await liveManager.dispose();
|
|
@@ -3238,7 +3292,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3238
3292
|
await pglite.exec(buildWipeLocalStoreSql(options.registry));
|
|
3239
3293
|
// Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
|
|
3240
3294
|
// the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
|
|
3241
|
-
|
|
3295
|
+
sync?.unsubscribe();
|
|
3242
3296
|
// Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as
|
|
3243
3297
|
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
3244
3298
|
await liveManager.dispose();
|
|
@@ -3283,7 +3337,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3283
3337
|
options.registry,
|
|
3284
3338
|
computeLocalSchemaFingerprint(options.registry),
|
|
3285
3339
|
);
|
|
3286
|
-
// Reset the
|
|
3340
|
+
// Reset the read-path subscriptions so the rebuilt synced tables re-stream from scratch
|
|
3287
3341
|
// rather than the bookkeeping believing they are already caught up (ADR-0006).
|
|
3288
3342
|
await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
|
|
3289
3343
|
})
|
|
@@ -3623,8 +3677,12 @@ async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[
|
|
|
3623
3677
|
return;
|
|
3624
3678
|
}
|
|
3625
3679
|
|
|
3626
|
-
|
|
3627
|
-
await Promise.all(
|
|
3680
|
+
// No migrate here: boot provisions the metadata relations unconditionally, before this can run.
|
|
3681
|
+
await Promise.all(
|
|
3682
|
+
uniqueKeys.map((key) =>
|
|
3683
|
+
deleteSubscriptionState({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
|
|
3684
|
+
),
|
|
3685
|
+
);
|
|
3628
3686
|
}
|
|
3629
3687
|
|
|
3630
3688
|
function createDrizzleDatabase<TRegistry extends SyncTableRegistry>(
|
|
@@ -3701,44 +3759,3 @@ function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
|
|
|
3701
3759
|
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3702
3760
|
return (client) => createDatabase({ client, relations });
|
|
3703
3761
|
}
|
|
3704
|
-
|
|
3705
|
-
function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
|
|
3706
|
-
registry: TRegistry,
|
|
3707
|
-
electricUrl: string,
|
|
3708
|
-
): SyncConfigInput {
|
|
3709
|
-
return {
|
|
3710
|
-
electricUrl,
|
|
3711
|
-
localSchema: getSyncRegistrySchema(registry),
|
|
3712
|
-
tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),
|
|
3713
|
-
};
|
|
3714
|
-
}
|
|
3715
|
-
|
|
3716
|
-
function buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {
|
|
3717
|
-
const clientProjection = getClientProjection(entry, tableKey);
|
|
3718
|
-
|
|
3719
|
-
return {
|
|
3720
|
-
name: tableKey,
|
|
3721
|
-
mode: entry.mode,
|
|
3722
|
-
primaryKey: entry.primaryKey,
|
|
3723
|
-
...(entry.shape !== undefined ? { shape: entry.shape } : {}),
|
|
3724
|
-
clientProjection,
|
|
3725
|
-
// The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the
|
|
3726
|
-
// registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /
|
|
3727
|
-
// `classifyTableApplyStrategy` on the model, never carried through this config surface.
|
|
3728
|
-
// Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables
|
|
3729
|
-
// onto one MultiShapeStream; absent → singleton group.
|
|
3730
|
-
...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),
|
|
3731
|
-
// Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager
|
|
3732
|
-
// boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).
|
|
3733
|
-
...(entry.subscription ? { subscription: entry.subscription } : {}),
|
|
3734
|
-
...(entry.retention ? { retention: entry.retention } : {}),
|
|
3735
|
-
};
|
|
3736
|
-
}
|
|
3737
|
-
|
|
3738
|
-
function getClientProjection(entry: SyncTableEntry, tableKey: string) {
|
|
3739
|
-
if (!entry.clientProjection) {
|
|
3740
|
-
throw new Error(`clientProjection is required for client table ${tableKey}`);
|
|
3741
|
-
}
|
|
3742
|
-
|
|
3743
|
-
return entry.clientProjection;
|
|
3744
|
-
}
|