@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.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +11 -3
- package/dist/boot-report.d.ts +11 -8
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +39 -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 +96 -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/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +237 -113
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7037 -6665
- package/dist/index.js.map +46 -43
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +59 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +17 -25
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +84 -8
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- 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 +26 -7
- 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.d.ts +1 -1
- package/dist/testing.js +4 -3
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +27 -14
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +52 -19
- 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/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -9
- package/skills/core/SKILL.md +145 -63
- package/skills/operating/SKILL.md +221 -221
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +13 -12
- package/src/circuits/envelope-to-change.ts +211 -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 +191 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +643 -0
- package/src/debug.ts +1 -85
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +24 -28
- package/src/export-store.ts +17 -17
- package/src/index.ts +797 -544
- package/src/lazy-guard.ts +1 -1
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +76 -5
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +126 -29
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +56 -40
- package/src/sync/apply.ts +104 -156
- package/src/sync/copy.ts +116 -21
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +43 -2
- package/src/sync/subscription-state.ts +28 -10
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +4 -4
- package/src/worker/attach-sync-client.ts +150 -57
- package/src/worker/define-sync-worker.ts +325 -87
- package/src/worker/engine-control.ts +89 -0
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +10 -10
- package/src/worker/protocol.ts +38 -7
- 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
|
@@ -389,3 +389,92 @@ export function engineRelocatedFromWire(detail: unknown): EngineRelocatedError |
|
|
|
389
389
|
if (candidate.outcome !== "not-dispatched" && candidate.outcome !== "unknown") return undefined;
|
|
390
390
|
return new EngineRelocatedError(candidate.outcome);
|
|
391
391
|
}
|
|
392
|
+
|
|
393
|
+
// ─── E. ProvisionStalledError (the spare-store adoption budget) ───────────────────
|
|
394
|
+
|
|
395
|
+
/** The stable clone-safe discriminator a stalled spare adoption carries on the wire. Branch on this, never prose. */
|
|
396
|
+
export const PROVISION_STALLED_CODE = "provision-stalled";
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* The clone-safe wire form of a stalled spare adoption. Like the execution-limit and relocation errors it
|
|
400
|
+
* travels inside the EXISTING bridge error `detail` field (the `{ message, detail }` shape `serializeError`
|
|
401
|
+
* produces), so no new protocol field is needed; the attach side calls {@link provisionStalledFromWire} on
|
|
402
|
+
* every bridge error `detail` and rebuilds the CLASS.
|
|
403
|
+
*/
|
|
404
|
+
export interface ProvisionStalledWire {
|
|
405
|
+
code: typeof PROVISION_STALLED_CODE;
|
|
406
|
+
storePath: string;
|
|
407
|
+
elapsedMs: number;
|
|
408
|
+
budgetMs: number;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Thrown at attach when the engine's IN-FLIGHT spare provision (the pre-spawned schemaless store of ADR-0032
|
|
413
|
+
* decision 5) has not settled within the engine's `provisionAdoptionBudgetMs` — measured from the provision
|
|
414
|
+
* attempt's START, not from this attach. The spare is a pure ACCELERATOR, never a boot dependency, so an
|
|
415
|
+
* attach must never hang behind one: past the budget the attach is REFUSED typed, and the host can rebind to
|
|
416
|
+
* a fresh store (or retry) instead of sitting on "starting local database…" forever.
|
|
417
|
+
*
|
|
418
|
+
* What this is NOT: engine-death detection. Nothing is inferred about the engine's liveness from the elapsed
|
|
419
|
+
* time (ADR-0049 D5 refuses timing-based death inference, unchanged). The stalled attempt is deliberately LEFT
|
|
420
|
+
* RUNNING — an in-flight OPFS/IDB store open cannot be safely abandoned, a second open against the same store
|
|
421
|
+
* being an ownership conflict — so a later attach still ADOPTS it if it completes. Abandoning a slow spare
|
|
422
|
+
* costs at most one extra initdb, never data: the spare is schemaless and holds no writes.
|
|
423
|
+
*
|
|
424
|
+
* Survives the worker bridge AS THIS CLASS via the tagged {@link ProvisionStalledWire} `detail` (the same
|
|
425
|
+
* tagged-detail pair the execution-limit and relocation errors use), so a consumer can `instanceof`-branch it.
|
|
426
|
+
*/
|
|
427
|
+
export class ProvisionStalledError extends Error {
|
|
428
|
+
readonly code = PROVISION_STALLED_CODE;
|
|
429
|
+
/** The store whose in-flight spare provision has not settled. */
|
|
430
|
+
readonly storePath: string;
|
|
431
|
+
/** How long that provision attempt has been running, in ms (measured from ITS start). */
|
|
432
|
+
readonly elapsedMs: number;
|
|
433
|
+
/** The budget it outran, in ms (the engine's effective `provisionAdoptionBudgetMs`). */
|
|
434
|
+
readonly budgetMs: number;
|
|
435
|
+
|
|
436
|
+
constructor(init: { storePath: string; elapsedMs: number; budgetMs: number }) {
|
|
437
|
+
super(
|
|
438
|
+
`[pgxsinkit] attach refused for ${JSON.stringify(init.storePath)}: the spare store's create has not ` +
|
|
439
|
+
`settled within ${init.budgetMs}ms (${init.elapsedMs}ms elapsed since the provision started). The ` +
|
|
440
|
+
"spare is a pure ACCELERATOR, never a boot dependency, so the attach is refused instead of waiting " +
|
|
441
|
+
'forever — rebind to a fresh store (or retry the attach) rather than showing an endless "starting ' +
|
|
442
|
+
'local database". The stalled attempt is LEFT RUNNING (an in-flight store open cannot be safely ' +
|
|
443
|
+
"abandoned), so a later attach adopts it if it completes. Nothing is inferred here about the engine " +
|
|
444
|
+
"being alive or dead. Tune or disable the bound with `defineSyncWorker`'s `provisionAdoptionBudgetMs`.",
|
|
445
|
+
);
|
|
446
|
+
this.name = "ProvisionStalledError";
|
|
447
|
+
this.storePath = init.storePath;
|
|
448
|
+
this.elapsedMs = init.elapsedMs;
|
|
449
|
+
this.budgetMs = init.budgetMs;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Encode a {@link ProvisionStalledError} to its clone-safe wire form for the bridge error `detail` field. */
|
|
454
|
+
export function provisionStalledToWire(error: ProvisionStalledError): ProvisionStalledWire {
|
|
455
|
+
return {
|
|
456
|
+
code: PROVISION_STALLED_CODE,
|
|
457
|
+
storePath: error.storePath,
|
|
458
|
+
elapsedMs: error.elapsedMs,
|
|
459
|
+
budgetMs: error.budgetMs,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Reconstruct a typed {@link ProvisionStalledError} from a bridge error's `detail`. STRICT shape check:
|
|
465
|
+
* returns `undefined` for anything that is not exactly the `{ code: "provision-stalled", storePath,
|
|
466
|
+
* elapsedMs, budgetMs }` wire form (a foreign/absent detail, a wrong code, a missing/mistyped field, a
|
|
467
|
+
* non-object), so an unrelated failure is never misclassified as a stalled spare.
|
|
468
|
+
*/
|
|
469
|
+
export function provisionStalledFromWire(detail: unknown): ProvisionStalledError | undefined {
|
|
470
|
+
if (typeof detail !== "object" || detail === null) return undefined;
|
|
471
|
+
const candidate = detail as { code?: unknown; storePath?: unknown; elapsedMs?: unknown; budgetMs?: unknown };
|
|
472
|
+
if (candidate.code !== PROVISION_STALLED_CODE) return undefined;
|
|
473
|
+
if (typeof candidate.storePath !== "string") return undefined;
|
|
474
|
+
if (typeof candidate.elapsedMs !== "number" || typeof candidate.budgetMs !== "number") return undefined;
|
|
475
|
+
return new ProvisionStalledError({
|
|
476
|
+
storePath: candidate.storePath,
|
|
477
|
+
elapsedMs: candidate.elapsedMs,
|
|
478
|
+
budgetMs: candidate.budgetMs,
|
|
479
|
+
});
|
|
480
|
+
}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// On the DEFAULT configuration the retirement signals are the ones that carry actual EVIDENCE of death:
|
|
12
12
|
// the engine control port's `close` event (MessagePort `close` is Baseline, so this covers every current
|
|
13
13
|
// browser), the reported paths owned above this module (worker `error`, spawn failure, tab death), and
|
|
14
|
-
// the teardown handshake. SILENCE IS NEVER A VERDICT HERE (ADR-0049 D5):
|
|
14
|
+
// the teardown handshake. SILENCE IS NEVER A VERDICT HERE (ADR-0049 D5): pgwasm's synchronous WASM work
|
|
15
15
|
// blocks the engine's event loop, so a legitimate long import stalls the control channel exactly as a
|
|
16
16
|
// corpse does. Timing therefore lives entirely behind the OPT-IN execution limit — with it enabled, an
|
|
17
17
|
// unacked `connect-port` and a tab-reported overdue dispatch both hand the question to the probe loop,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Canonical fingerprint for a live query (ADR-0040 decisions 2 & 3). Two identical live queries — same
|
|
2
|
-
// POST-WRAP SQL, same bound params, same key mode — must map to ONE
|
|
3
|
-
// changes what
|
|
2
|
+
// POST-WRAP SQL, same bound params, same key mode — must map to ONE pgwasm registration; anything that
|
|
3
|
+
// changes what pgwasm actually runs (or how the diff is keyed) must map to a DISTINCT one. The fingerprint
|
|
4
4
|
// covers EXECUTION-relevant inputs only: the materialized SQL, a TYPED encoding of the params, and the PK
|
|
5
5
|
// columns (which pick `live.incrementalQuery` vs `live.query` and drive the diff key). `use` is deliberately
|
|
6
6
|
// NOT an input — activation/hydration are per-subscriber pre-steps that never influence the registration
|
|
@@ -111,9 +111,9 @@ export function fingerprintLiveQuery(
|
|
|
111
111
|
params: readonly unknown[],
|
|
112
112
|
pkColumns?: readonly string[],
|
|
113
113
|
): LiveQueryFingerprint {
|
|
114
|
-
// Single-column PK →
|
|
114
|
+
// Single-column PK → pgwasm `live.incrementalQuery`; composite/keyless → `live.query` + worker-side diff.
|
|
115
115
|
// The mode AND the exact pk columns both matter: same SQL with a different pk column is a different
|
|
116
|
-
// registration (different diff key), and incremental vs full are different
|
|
116
|
+
// registration (different diff key), and incremental vs full are different pgwasm machines.
|
|
117
117
|
const mode = pkColumns && pkColumns.length === 1 ? "inc" : "full";
|
|
118
118
|
// ONE `JSON.stringify` over a fixed-shape object of type-tagged encoding STRUCTURES: the SQL is its own JSON
|
|
119
119
|
// string element (cannot bleed into params), and JSON escaping makes the whole key unambiguous — no manual
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The worker-owned live-query manager (ADR-0040). It owns the
|
|
1
|
+
// The worker-owned live-query manager (ADR-0040). It owns the pgwasm `live` registration lifecycle, the
|
|
2
2
|
// single change listener + shared `LiveDiffState` per query, and the awaited-teardown bookkeeping (decision
|
|
3
3
|
// 1). Slice 3 added DEDUPLICATION: identical live queries (same fingerprint — see live-query-fingerprint.ts)
|
|
4
4
|
// share ONE registration and ONE diff computation, fanned out to every subscriber (decision 2). Slice 4 adds
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// effective keep-alive retains the registration for a grace period so a matching resubscribe reuses it
|
|
7
7
|
// verbatim (no ~400 ms re-materialization); retention is bounded by explicit count/row budgets and defaults
|
|
8
8
|
// to OFF (keep-alive 0 → tear down the instant the last subscriber leaves). The 0 default is deliberate:
|
|
9
|
-
// a retained entry still pays a full SQL rerun + diff on every dependent write (
|
|
9
|
+
// a retained entry still pays a full SQL rerun + diff on every dependent write (pgwasm live queries cannot
|
|
10
10
|
// be paused), so keeping one alive is only worthwhile for a genuinely hot, re-mounted query — the default
|
|
11
11
|
// keeps worker memory bounded and never runs surprise standing SQL.
|
|
12
12
|
//
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// are per-subscriber pre-/post-steps that never influence the shared registration or its rows; in particular
|
|
18
18
|
// `use` NEVER reaches here, so differing `use` sets share one registration.
|
|
19
19
|
|
|
20
|
-
import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@
|
|
20
|
+
import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@pgxsinkit/pgwasm/live";
|
|
21
21
|
|
|
22
22
|
import { syncDebug } from "../debug";
|
|
23
23
|
import { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from "./live-diff";
|
|
@@ -76,7 +76,7 @@ export interface LiveQueryPolicy {
|
|
|
76
76
|
* Default retention (ms) for a zero-subscriber entry, floored by each subscriber's own `keepAliveMs` hint.
|
|
77
77
|
* Default 0 — the current route-scoped behaviour (tear a query down the moment its last consumer leaves).
|
|
78
78
|
* The standing argument for 0: a retained zero-subscriber entry STILL pays a full SQL rerun + diff on every
|
|
79
|
-
* dependent-table write —
|
|
79
|
+
* dependent-table write — pgwasm live queries cannot be paused, only torn down — so retention trades that
|
|
80
80
|
* standing cost for avoiding re-materialization, and is only worth it for a genuinely hot, re-mounted query.
|
|
81
81
|
*/
|
|
82
82
|
defaultKeepAliveMs?: number;
|
|
@@ -142,7 +142,7 @@ export interface LiveQueryDiagnostics {
|
|
|
142
142
|
lastUsedAt: number | null;
|
|
143
143
|
/** How long (ms) the entry has been retained (now − lastUsedAt), or `null` when not retained. */
|
|
144
144
|
retainedSinceMs: number | null;
|
|
145
|
-
/** A teardown is in flight (the entry is unsubscribing from
|
|
145
|
+
/** A teardown is in flight (the entry is unsubscribing from pgwasm). */
|
|
146
146
|
teardownPending: boolean;
|
|
147
147
|
}
|
|
148
148
|
|
|
@@ -240,7 +240,7 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
240
240
|
deps.clearTimer ?? ((handle: TimerHandle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
|
|
241
241
|
|
|
242
242
|
// ADR-0040 decision 1 (originally define-sync-worker's Slice 1): a fire-and-forget live `unsubscribe()`
|
|
243
|
-
// still in flight when
|
|
243
|
+
// still in flight when pgwasm closes wedges the process forever. Every teardown promise is retained here so
|
|
244
244
|
// `dispose()` settles them ALL before the caller closes the engine; rejections are swallowed so an
|
|
245
245
|
// interrupted teardown never becomes an unhandled rejection.
|
|
246
246
|
const pendingTeardowns = new Set<Promise<void>>();
|
|
@@ -276,7 +276,7 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
276
276
|
(entry as { setup: Promise<void> }).setup = (async () => {
|
|
277
277
|
const setupStartedAt = now();
|
|
278
278
|
const { materialSql, params, pkColumns } = spec;
|
|
279
|
-
// Single-column PK →
|
|
279
|
+
// Single-column PK → pgwasm's incremental machinery (`live.incrementalQuery`); composite/keyless →
|
|
280
280
|
// `live.query` (full ordered result each fire) + worker-side diff. Identical selection to the pre-dedup
|
|
281
281
|
// path; the fingerprint already encoded this choice as its `mode`.
|
|
282
282
|
const registered =
|
|
@@ -298,8 +298,8 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
298
298
|
}
|
|
299
299
|
}
|
|
300
300
|
// A retained (zero-subscriber) entry stays live and its rows can GROW past the row budget on a write.
|
|
301
|
-
// Re-enforce OUTSIDE this callback (a queued microtask) — eviction's
|
|
302
|
-
// run inside
|
|
301
|
+
// Re-enforce OUTSIDE this callback (a queued microtask) — eviction's pgwasm `unsubscribe()` must not
|
|
302
|
+
// run inside pgwasm's own notification call (ADR-0040 decision 4 — the budget stays authoritative).
|
|
303
303
|
if (retained.has(entry)) queueMicrotask(() => enforceBudgets());
|
|
304
304
|
};
|
|
305
305
|
registered.subscribe(listener);
|
|
@@ -456,10 +456,10 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
456
456
|
`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,
|
|
457
457
|
);
|
|
458
458
|
}
|
|
459
|
-
// Reject a param shape that would trip
|
|
459
|
+
// Reject a param shape that would trip pgwasm bug #1055's broken live-query param inlining BEFORE any
|
|
460
460
|
// fingerprinting or registration (see live-query-params-guard.ts). Synchronous, so every subscriber —
|
|
461
461
|
// in-process and worker alike — fails loudly rather than binding wrong rows or hitting a cryptic
|
|
462
|
-
// `format()` error deep inside
|
|
462
|
+
// `format()` error deep inside pgwasm.
|
|
463
463
|
assertLiveQueryParamsSafe(spec.materialSql, spec.params);
|
|
464
464
|
const keepAliveMs = hint ?? 0;
|
|
465
465
|
const scope = opts?.scope;
|
|
@@ -512,7 +512,7 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
512
512
|
// membership write. A listener fire (computeLiveDiff → deliverDiff) is synchronous, so with no yield here
|
|
513
513
|
// no diff can land between the two: the joiner can neither miss a diff (it would be added to the map
|
|
514
514
|
// first) nor be handed one its snapshot already reflects (the snapshot is taken first). The initial rows
|
|
515
|
-
// come from the diff state, NOT a fresh
|
|
515
|
+
// come from the diff state, NOT a fresh pgwasm read — the registration is already current.
|
|
516
516
|
//
|
|
517
517
|
// Keep-alive GENERATION rule (ADR-0040 decision 4): a 0→1 join opens a new generation and RESETS the
|
|
518
518
|
// entry's generation hint to this joiner's; any later join `max`'s it. The last-out effective keep-alive
|
|
@@ -9,34 +9,34 @@
|
|
|
9
9
|
// - out-of-order placeholders (`… $2 … $1 …`) silently bind params in TEXTUAL order → wrong rows;
|
|
10
10
|
// - a repeated placeholder (`$1 … $1`) throws `too few arguments for format()`;
|
|
11
11
|
// - a skipped placeholder silently mis-binds.
|
|
12
|
-
// The ONLY input shape under which
|
|
12
|
+
// The ONLY input shape under which pgwasm's broken inlining is still correct: the placeholders, read in
|
|
13
13
|
// textual order, are exactly `$1, $2, …, $n` (n = params.length) — each appearing exactly once, strictly
|
|
14
14
|
// ascending. Drizzle-compiled SQL always satisfies this (its serializer numbers params in the same
|
|
15
15
|
// left-to-right pass that emits them); hand-written raw SQL may not.
|
|
16
16
|
//
|
|
17
17
|
// So this guard fails LOUDLY at the client boundary for any other shape, turning a silent wrong-rows /
|
|
18
18
|
// cryptic-`format()` failure into an actionable error naming the upstream bug. It can be DELETED once
|
|
19
|
-
// transcrobes/pgxsinkit pin a
|
|
19
|
+
// transcrobes/pgxsinkit pin a pgwasm release whose `formatQuery` emits the positional `%N$L`.
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
-
* Throw if `sql` + `params` would hit
|
|
22
|
+
* Throw if `sql` + `params` would hit pgwasm bug #1055's broken param inlining (see the module header).
|
|
23
23
|
*
|
|
24
|
-
* `params.length === 0` returns immediately:
|
|
24
|
+
* `params.length === 0` returns immediately: pgwasm skips `formatQuery` entirely in that case, so any `$N`
|
|
25
25
|
* tokens are Postgres's own concern, not this guard's. Otherwise the SQL is scanned with the SAME regex
|
|
26
|
-
*
|
|
27
|
-
* touch. That includes a `$1` sitting inside a string literal:
|
|
28
|
-
* false positive here is a feature, not a bug — it flags SQL
|
|
26
|
+
* pgwasm's rewrite uses (`/\$(\d+)/g`) — deliberately, so the guard sees EXACTLY the tokens pgwasm would
|
|
27
|
+
* touch. That includes a `$1` sitting inside a string literal: pgwasm would corrupt that too, so a loud
|
|
28
|
+
* false positive here is a feature, not a bug — it flags SQL pgwasm cannot inline safely regardless.
|
|
29
29
|
*
|
|
30
30
|
* Safe iff the collected numbers (in textual order) are exactly `[1, 2, …, params.length]`. Anything else —
|
|
31
31
|
* out-of-order, repeated, skipped, or a count mismatch in either direction — throws.
|
|
32
32
|
*/
|
|
33
33
|
export function assertLiveQueryParamsSafe(sql: string, params: readonly unknown[]): void {
|
|
34
|
-
// No params →
|
|
34
|
+
// No params → pgwasm never calls formatQuery, so its broken inlining never runs. Placeholders without
|
|
35
35
|
// params are Postgres's problem to report, not this guard's.
|
|
36
36
|
if (params.length === 0) return;
|
|
37
37
|
|
|
38
|
-
// The SAME regex
|
|
39
|
-
// including any `$N` inside a string literal (which
|
|
38
|
+
// The SAME regex pgwasm's `formatQuery` applies — so we see exactly the tokens its rewrite would touch,
|
|
39
|
+
// including any `$N` inside a string literal (which pgwasm would corrupt too; flagging it is intentional).
|
|
40
40
|
const numbers: number[] = [];
|
|
41
41
|
for (const match of sql.matchAll(/\$(\d+)/g)) numbers.push(Number(match[1]));
|
|
42
42
|
|
package/src/worker/protocol.ts
CHANGED
|
@@ -106,7 +106,7 @@ export interface AuthTokenSnapshot {
|
|
|
106
106
|
|
|
107
107
|
/**
|
|
108
108
|
* tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the
|
|
109
|
-
* login screen against the freshly-named spare worker: the worker only runs
|
|
109
|
+
* login screen against the freshly-named spare worker: the worker only runs pgwasm `create`/initdb
|
|
110
110
|
* (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token
|
|
111
111
|
* — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.
|
|
112
112
|
* Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning
|
|
@@ -154,7 +154,7 @@ export interface ProvisionAckPayload {
|
|
|
154
154
|
export interface RestoreArtefactWire {
|
|
155
155
|
/** The backup tarball bytes — transferred, not copied. */
|
|
156
156
|
buffer: ArrayBuffer;
|
|
157
|
-
/** The backup file name (informational;
|
|
157
|
+
/** The backup file name (informational; pgwasm's `loadDataDir` reads the bytes, not the name). */
|
|
158
158
|
fileName: string;
|
|
159
159
|
/** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */
|
|
160
160
|
mimeType: string;
|
|
@@ -252,6 +252,15 @@ export interface AttachAckPayload {
|
|
|
252
252
|
*/
|
|
253
253
|
writeReadyError?: BridgeErrorWire;
|
|
254
254
|
bootSettledError?: BridgeErrorWire;
|
|
255
|
+
/**
|
|
256
|
+
* The started-state snapshot at ack time (ADR-0059): `isSynced` per registry key, computed on the
|
|
257
|
+
* worker's OWN client. It rides the ack because `attachSyncClient` RESOLVES here — the worker's first
|
|
258
|
+
* `status` event is posted after the ack, so `const c = await attachSyncClient(…); c.isSynced(k)` runs
|
|
259
|
+
* before any broadcast is delivered, and only an ack field makes that first synchronous read faithful.
|
|
260
|
+
* A late attach folds the current snapshot the same way it folds the milestones above. Absent on an
|
|
261
|
+
* error ack (there is no engine to ask).
|
|
262
|
+
*/
|
|
263
|
+
synced?: Record<string, boolean>;
|
|
255
264
|
/**
|
|
256
265
|
* Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this
|
|
257
266
|
* message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot. This
|
|
@@ -274,7 +283,13 @@ export interface TokenResponsePayload {
|
|
|
274
283
|
|
|
275
284
|
/**
|
|
276
285
|
* The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors
|
|
277
|
-
* `client.mutate`/flush), mutation-state reads, and the
|
|
286
|
+
* `client.mutate`/flush), mutation-state reads, and the raw inspection surface (the one-shot `rawQuery`/
|
|
287
|
+
* `rawExec`, plus the atomic `rawTransaction`).
|
|
288
|
+
*
|
|
289
|
+
* Most dispatches are pure structured clone. The exception is a raw statement's COPY body (ADR-0061): the
|
|
290
|
+
* tab lists each `blob`'s `ArrayBuffer` on the dispatch's transfer list, so the bytes cross ZERO-COPY and
|
|
291
|
+
* the tab's buffers are detached. No wire type changes for it — a `Uint8Array` survives structured clone
|
|
292
|
+
* as a `Uint8Array` over the transferred buffer, so the worker reads `RawStatement.blob` unchanged.
|
|
278
293
|
*/
|
|
279
294
|
export type RpcOp =
|
|
280
295
|
| "create"
|
|
@@ -304,13 +319,21 @@ export type RpcOp =
|
|
|
304
319
|
| "ensureSynced"
|
|
305
320
|
| "readMutationDetails"
|
|
306
321
|
| "diagnostics"
|
|
322
|
+
// Carries `[sql, params?, options?]`. `options.blob` (ADR-0061) is the single-statement COPY bulk load:
|
|
323
|
+
// the COPY TEXT body of a `COPY … FROM '/dev/blob'`, TRANSFERRED (not cloned) with the dispatch.
|
|
307
324
|
| "rawQuery"
|
|
308
325
|
| "rawExec"
|
|
326
|
+
// The ATOMIC raw seam: carries `[statements, options?]` — the whole `RawStatement[]` in ONE round trip, so
|
|
327
|
+
// the transaction opens and closes inside the worker. It cannot be composed tab-side out of `rawQuery`
|
|
328
|
+
// calls (each would be its own implicit transaction, and a relocation between two of them would tear the
|
|
329
|
+
// write), which is exactly why it is its own op. Any statement may carry a COPY `blob` (ADR-0061); every
|
|
330
|
+
// such buffer rides this ONE dispatch's transfer list, so a chunked bulk load crosses zero-copy.
|
|
331
|
+
| "rawTransaction"
|
|
309
332
|
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the attach client's Drizzle-over-bridge compiles a
|
|
310
333
|
// read to SQL on the tab and routes it here as the {@link GuardedQueryWireArgs} tuple
|
|
311
334
|
// `[sql, params?, { rowMode? }, use?]`. Unlike `rawQuery` (raw inspection, no guard), the worker runs the
|
|
312
335
|
// engine's `guardedRawQuery` — the ADR-0041 read gate + the ADR-0021 lazy-group guard (activating any lazy
|
|
313
|
-
// relation the SQL/`use` reference) — then returns the full
|
|
336
|
+
// relation the SQL/`use` reference) — then returns the full pgwasm `Results` over `rpc-result`, so Drizzle's
|
|
314
337
|
// own result mapping runs on the tab. Only `rowMode` crosses in the options: drizzle's `parsers` map is
|
|
315
338
|
// FUNCTIONS (non-serializable) and is stripped tab-side, then re-applied worker-side so the identity-parsed
|
|
316
339
|
// OIDs (drizzle's identity parsers — temporal OIDs + numeric[]) round-trip as raw strings exactly as in-process.
|
|
@@ -472,6 +495,13 @@ export type BridgeEvent =
|
|
|
472
495
|
// the tab's matching `writeReady` / `bootSettled` promise so an awaiter fails loudly rather than hanging;
|
|
473
496
|
// `localReadReady` (and the resolved attach) are unaffected — the engine reached local-read readiness.
|
|
474
497
|
| { kind: "milestone-error"; stage: BootMilestone; error: BridgeErrorWire }
|
|
498
|
+
// The started-state snapshot (ADR-0059): what the WORKER's own client answers for `isSynced(key)`, one
|
|
499
|
+
// entry per registry key. `isSynced` is a SYNCHRONOUS peek, so it can never be an RPC; the worker pushes
|
|
500
|
+
// the answer instead and the tab reads it out of a cache. Computed by asking the in-process client, never
|
|
501
|
+
// re-derived tab-side — per-group catch-up readiness (`status`/`groupReady`) is the strictly weaker
|
|
502
|
+
// question and reads a promoted-but-still-catching-up group as not started. Broadcast whenever the answer
|
|
503
|
+
// changes (deduped against the last one sent); a tab attaching later folds {@link AttachAckPayload.synced}.
|
|
504
|
+
| { kind: "synced"; tables: Record<string, boolean> }
|
|
475
505
|
| { kind: "conflict"; details: unknown }
|
|
476
506
|
| { kind: "quarantine"; details: unknown }
|
|
477
507
|
| { kind: "reject"; details: unknown }
|
|
@@ -556,9 +586,10 @@ export function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {
|
|
|
556
586
|
|
|
557
587
|
/**
|
|
558
588
|
* Send a typed message over a port: encode → post (with any transferables). The one write choke point.
|
|
559
|
-
* `transfer` lets a caller declare payload-specific transferables (
|
|
560
|
-
* ADR-0035) WITHOUT teaching the shared codec about that op — they
|
|
561
|
-
* produces, so both the codec's future zero-copy path and
|
|
589
|
+
* `transfer` lets a caller declare payload-specific transferables (a store-backup's `ArrayBuffer`,
|
|
590
|
+
* ADR-0035; a raw statement's COPY body, ADR-0061) WITHOUT teaching the shared codec about that op — they
|
|
591
|
+
* are merged after any the codec itself produces, so both the codec's future zero-copy path and
|
|
592
|
+
* per-message transfers coexist. Every listed buffer is DETACHED in the sending realm once this returns.
|
|
562
593
|
*/
|
|
563
594
|
export function postBridgeMessage(
|
|
564
595
|
port: BridgePort,
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { type BackoffOptions } from "@electric-sql/client";
|
|
2
|
-
/**
|
|
3
|
-
* The read path's OUTAGE seam (board ADR-0010 "offline return").
|
|
4
|
-
*
|
|
5
|
-
* Every shape fetch runs inside Electric's `createFetchWithBackoff`, which retries a failed attempt
|
|
6
|
-
* **forever** (`maxRetries: Infinity` — "clients may go offline and come back") and only re-throws a
|
|
7
|
-
* non-retryable 4xx. A network-level failure therefore never escapes that wrapper: `ShapeStream.onError`
|
|
8
|
-
* is never called, so neither is `onReadStreamError`, and a runtime keying off those alone reports
|
|
9
|
-
* `syncing` for as long as the machine stays offline. `backoffOptions.onFailedAttempt` is the ONLY signal
|
|
10
|
-
* Electric surfaces from inside the loop, and it is what this probe turns into a runtime status change.
|
|
11
|
-
*
|
|
12
|
-
* The two seams PARTITION the failures, they do not overlap:
|
|
13
|
-
*
|
|
14
|
-
* - **Retried inside the wrapper** (a rejected request — the offline case, with no HTTP status at all — a
|
|
15
|
-
* 5xx, or a 429) → nobody else will ever hear about it. This probe's `onStalled`.
|
|
16
|
-
* - **Escapes the wrapper** (any other 4xx: 401/403 auth, 404/409/… structural) → `ShapeStream.onError`,
|
|
17
|
-
* i.e. `createShapeErrorHandler` → `onAuthError` / `onReadStreamError`, which own it and carry a real
|
|
18
|
-
* error message. Deliberately NOT reported here, so a rejected token still surfaces as the more
|
|
19
|
-
* actionable `auth-needed` and an expired handle's 409 stays the recovery it is.
|
|
20
|
-
* - **A deliberate abort** — a stream teardown, a hidden tab (`PAUSE_STREAM`), a live-request timeout, a
|
|
21
|
-
* system wake, and the live-tail nudge's `forceDisconnectAndRefresh` all abort the in-flight request,
|
|
22
|
-
* and Electric calls `onFailedAttempt` for the resulting `AbortError` like any other. None is an
|
|
23
|
-
* outage; counting them would report "connection needed" for backgrounding a tab.
|
|
24
|
-
*
|
|
25
|
-
* `onFailedAttempt` carries no arguments, so the classification is made one layer down, in the
|
|
26
|
-
* `fetchClient` this probe supplies: it records how the attempt that just settled would be treated by the
|
|
27
|
-
* very next lines of Electric's own catch block. Recovery needs nothing here — the runtime clears a
|
|
28
|
-
* stream-degraded status on the next delivered batch (`onSyncActivity`), which a resumed stream produces
|
|
29
|
-
* on its first successful poll.
|
|
30
|
-
*/
|
|
31
|
-
export interface ReadStreamStallProbe {
|
|
32
|
-
/** Pass as `ShapeStreamOptions.backoffOptions` — Electric's defaults plus the failed-attempt hook. */
|
|
33
|
-
backoffOptions: BackoffOptions;
|
|
34
|
-
/** Pass as `ShapeStreamOptions.fetchClient` — the innermost transport, wrapped to classify each attempt. */
|
|
35
|
-
fetchClient: typeof fetch;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* The CALL signature of `fetch`, without the runtime-specific statics (Bun's global carries `preconnect`).
|
|
39
|
-
* A ShapeStream only ever invokes its `fetchClient` as a plain call, so this is the honest contract for a
|
|
40
|
-
* transport being wrapped — and it is what lets a test inject a failing one.
|
|
41
|
-
*/
|
|
42
|
-
type FetchLike = (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
|
|
43
|
-
export declare function createReadStreamStallProbe(input: {
|
|
44
|
-
/**
|
|
45
|
-
* Notified per failed attempt that Electric will retry internally, never for an escaping 4xx and never
|
|
46
|
-
* for a deliberate abort. Fires repeatedly while an outage lasts — Electric retries forever — so the
|
|
47
|
-
* consumer owns the transition/dedup, not this probe.
|
|
48
|
-
*/
|
|
49
|
-
onStalled: () => void;
|
|
50
|
-
/** The transport to wrap. Defaults to the global `fetch`; a test injects the failure here. */
|
|
51
|
-
fetchClient?: FetchLike;
|
|
52
|
-
}): ReadStreamStallProbe;
|
|
53
|
-
export {};
|
|
54
|
-
//# sourceMappingURL=read-stream-stall.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"read-stream-stall.d.ts","sourceRoot":"","sources":["../src/read-stream-stall.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,WAAW,oBAAoB;IACnC,sGAAsG;IACtG,cAAc,EAAE,cAAc,CAAC;IAC/B,4GAA4G;IAC5G,WAAW,EAAE,OAAO,KAAK,CAAC;CAC3B;AAED;;;;GAIG;AACH,KAAK,SAAS,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAWjH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE;IAChD;;;;OAIG;IACH,SAAS,EAAE,MAAM,IAAI,CAAC;IACtB,8FAA8F;IAC9F,WAAW,CAAC,EAAE,SAAS,CAAC;CACzB,GAAG,oBAAoB,CAsCvB"}
|
package/dist/shape-sync.d.ts
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import type { ExternalHeadersRecord } from "@electric-sql/client";
|
|
2
|
-
import type { PGliteInterface } from "@electric-sql/pglite";
|
|
3
|
-
import { type Retention, type SubscriptionTiming, type SyncConfigInput, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
4
|
-
import type { BootStampCollector, GroupBootStamp } from "./boot-report";
|
|
5
|
-
import type { SyncNamespaceObj } from "./sync";
|
|
6
|
-
export interface ShapeSyncSpec {
|
|
7
|
-
electricUrl: string;
|
|
8
|
-
tableName: string;
|
|
9
|
-
schema?: string;
|
|
10
|
-
shapeKey: string;
|
|
11
|
-
primaryKey: string[];
|
|
12
|
-
electricTable?: string;
|
|
13
|
-
/**
|
|
14
|
-
* Consistency group (ADR-0009 decision 2). Specs sharing a group sync on one `MultiShapeStream`
|
|
15
|
-
* and commit atomically. Absent → the table is its own singleton group keyed by its `shapeKey`.
|
|
16
|
-
*/
|
|
17
|
-
consistencyGroup?: string;
|
|
18
|
-
/**
|
|
19
|
-
* Subscription timing (ADR-0021). Absent → `eager`. A `lazy` spec's group is held out of the eager
|
|
20
|
-
* boot set and started on demand via {@link StartConfiguredSyncResult.ensureGroupStarted}. A group's
|
|
21
|
-
* members all agree (registry-validated), so the group's timing is any member's.
|
|
22
|
-
*/
|
|
23
|
-
subscription?: SubscriptionTiming;
|
|
24
|
-
/**
|
|
25
|
-
* Retention (ADR-0021). Absent → `persistent`. Only a `persistent` `lazy` group is promoted to the
|
|
26
|
-
* eager set on activation (its activation is permanent across boots); an `ephemeral` group's activation
|
|
27
|
-
* is session-scoped by construction, so it is never promoted/persisted.
|
|
28
|
-
*/
|
|
29
|
-
retention?: Retention;
|
|
30
|
-
}
|
|
31
|
-
export interface ConfiguredShapeSyncSpec extends ShapeSyncSpec {
|
|
32
|
-
key: string;
|
|
33
|
-
}
|
|
34
|
-
export interface StartConfiguredSyncOptions {
|
|
35
|
-
syncConfig: SyncConfigInput;
|
|
36
|
-
/**
|
|
37
|
-
* The sync registry (ADR-0029 D1): the engine's sole per-table spec source. Each shape's `tableKey`
|
|
38
|
-
* (its `syncConfig` table key) resolves against it for the local table, PKs, apply strategy, and
|
|
39
|
-
* column types — no table-scoped fact is threaded from `syncConfig` into the engine.
|
|
40
|
-
*/
|
|
41
|
-
registry: SyncTableRegistry;
|
|
42
|
-
/**
|
|
43
|
-
* Shape request headers shared by every member shape. Values may be async functions resolved per
|
|
44
|
-
* request (ADR-0013) — the read-path `Authorization` token is one such function.
|
|
45
|
-
*/
|
|
46
|
-
shapeHeaders?: ExternalHeadersRecord;
|
|
47
|
-
onInitialSync?: () => void;
|
|
48
|
-
onTableInitialSync?: (tableKey: string) => void;
|
|
49
|
-
/**
|
|
50
|
-
* Fresh-store prefetch overlap (ADR-0032 S4). When present, every EAGER group starts its shape streams
|
|
51
|
-
* and buffers their catch-up into the memory inbox immediately, gating all commits until this promise
|
|
52
|
-
* resolves — so the network catch-up overlaps the local boot phases (schema/journal/reconcile) instead
|
|
53
|
-
* of running after them. Set ONLY by `createSyncClient` on a provably-fresh store (its `freshStore`
|
|
54
|
-
* hint); absent → the sequential path. Passed straight through to the engine's `syncShapesToTables`.
|
|
55
|
-
*/
|
|
56
|
-
dbReady?: Promise<void>;
|
|
57
|
-
/** Commit-level error surfacing (ADR-0009 decision 5): a sync commit exhausted its retries. */
|
|
58
|
-
onSyncError?: (error: Error) => void;
|
|
59
|
-
/**
|
|
60
|
-
* Notified when a shape hits an auth error (401/403) and the read path is retrying for a fresh
|
|
61
|
-
* token (ADR-0013 Phase 3). The runtime surfaces a distinct `auth-needed` status from this.
|
|
62
|
-
*/
|
|
63
|
-
onAuthError?: () => void;
|
|
64
|
-
/**
|
|
65
|
-
* Notified when a shape hits a NON-auth stream error (#4): a transient 5xx/429/network (retried) or
|
|
66
|
-
* a structural 4xx (stops the stream). The runtime surfaces a `degraded` status from this so it
|
|
67
|
-
* never silently believes the read path is live while it has actually stalled.
|
|
68
|
-
*/
|
|
69
|
-
onReadStreamError?: (error: Error) => void;
|
|
70
|
-
/**
|
|
71
|
-
* Notified when a shape's fetch ATTEMPT failed and Electric is retrying it inside its own backoff
|
|
72
|
-
* wrapper (board ADR-0010): a rejected request (the offline case — no HTTP status at all), a 5xx, or a
|
|
73
|
-
* 429. The complement of {@link onReadStreamError}, which only ever fires for an error that ESCAPED that
|
|
74
|
-
* wrapper (any other 4xx) — which a network outage never does, since Electric retries it forever. Fires
|
|
75
|
-
* per attempt for as long as the outage lasts, so the runtime owns the transition; a deliberate abort
|
|
76
|
-
* (teardown, hidden tab, nudge refresh) is not a failure and is filtered out. See `read-stream-stall.ts`.
|
|
77
|
-
*/
|
|
78
|
-
onReadStreamStalled?: () => void;
|
|
79
|
-
/**
|
|
80
|
-
* Notified when a shape successfully delivers a batch — i.e. a fetch just succeeded (ADR-0013
|
|
81
|
-
* Phase 3). The runtime uses this to clear an `auth-needed`/`degraded` status once sync resumes.
|
|
82
|
-
*/
|
|
83
|
-
onSyncActivity?: () => void;
|
|
84
|
-
/**
|
|
85
|
-
* Consistency-group keys of `lazy` groups that were activated on a previous boot and persisted their
|
|
86
|
-
* activation flag (ADR-0021 §2 — `lazy + persistent` promotion). These join the eager boot set as if
|
|
87
|
-
* they were declared `eager`, so a once-activated durable lazy group resumes without re-evaluation.
|
|
88
|
-
* Computed by the caller from the local meta table (the sync engine does no DB read of its own).
|
|
89
|
-
*/
|
|
90
|
-
promotedGroups?: ReadonlySet<string>;
|
|
91
|
-
/**
|
|
92
|
-
* Invoked when a `persistent` `lazy` group is activated on demand (not promoted at boot), so the
|
|
93
|
-
* caller can persist its activation flag for the next boot (ADR-0021 §2). Never fired for an
|
|
94
|
-
* `ephemeral` group (its activation is session-scoped and leaves no durable trace).
|
|
95
|
-
*/
|
|
96
|
-
onLazyActivated?: (groupKey: string) => void;
|
|
97
|
-
/**
|
|
98
|
-
* Invoked exactly once per consistency group the moment it becomes up-to-date (ADR-0032 decision 6 —
|
|
99
|
-
* per-group readiness). Fires for eager, promoted, and on-demand `lazy` groups alike, so a client can
|
|
100
|
-
* surface progressive per-group paint (and the worker bridge can fan a `groupReady` event to tabs)
|
|
101
|
-
* without the all-eager-groups `onInitialSync` gate. The matching promise is {@link StartConfiguredSyncResult.groupReady}.
|
|
102
|
-
*/
|
|
103
|
-
onGroupReady?: (groupKey: string) => void;
|
|
104
|
-
/**
|
|
105
|
-
* Boot observability (ADR-0034): opens a per-group accumulator (rows/requests/fetch/apply wall) for each
|
|
106
|
-
* EAGER + PROMOTED boot group, stamped by the engine as the group's stream chain delivers and applies. A
|
|
107
|
-
* lazy on-demand start gets none — so a lazily-activated-later group never enters (or mutates) the report.
|
|
108
|
-
* Absent → no boot instrumentation.
|
|
109
|
-
*/
|
|
110
|
-
bootCollector?: BootStampCollector;
|
|
111
|
-
}
|
|
112
|
-
type SyncEnginePGlite = PGliteInterface & {
|
|
113
|
-
electric: SyncNamespaceObj;
|
|
114
|
-
};
|
|
115
|
-
export interface ShapeSyncResult {
|
|
116
|
-
unsubscribe: () => void;
|
|
117
|
-
readonly isUpToDate: boolean;
|
|
118
|
-
}
|
|
119
|
-
export interface StartConfiguredSyncResult {
|
|
120
|
-
unsubscribe: () => void;
|
|
121
|
-
tables: Record<string, ShapeSyncResult>;
|
|
122
|
-
/**
|
|
123
|
-
* Start a `lazy` consistency group (ADR-0021) held out of the eager boot set. Idempotent and
|
|
124
|
-
* single-flight: concurrent calls share one start; a started, unknown, or eager group resolves
|
|
125
|
-
* immediately. Resolves once the group's initial sync completes — the seam the live-query layer
|
|
126
|
-
* calls on first reference to a lazy table. After it resolves, the group's member `tables` entries
|
|
127
|
-
* report `isUpToDate` live.
|
|
128
|
-
*/
|
|
129
|
-
ensureGroupStarted: (groupKey: string) => Promise<void>;
|
|
130
|
-
/**
|
|
131
|
-
* Stop a group's stream and return it to dormant (ADR-0021 §2): tear down its live subscription and
|
|
132
|
-
* clear the runtime so {@link isTableStarted} reports false again and a later {@link ensureGroupStarted}
|
|
133
|
-
* re-subscribes from scratch — the inverse of an on-demand activation. Used by the client's `desync`
|
|
134
|
-
* to halt a lazy group before truncating its read cache. A no-op for an unknown or never-started group.
|
|
135
|
-
* The temp cluster of an `ephemeral` group is NOT dropped here (that is the deferred idle-eviction); the
|
|
136
|
-
* cluster simply stops being fed.
|
|
137
|
-
*/
|
|
138
|
-
stopGroup: (groupKey: string) => void;
|
|
139
|
-
/** The consistency-group key a table belongs to — maps a queried table to its {@link ensureGroupStarted}. */
|
|
140
|
-
groupKeyForTable: (tableKey: string) => string | undefined;
|
|
141
|
-
/**
|
|
142
|
-
* Whether a table's consistency group has started and completed its initial sync, so its reads are
|
|
143
|
-
* hydrated (ADR-0021). False for a `lazy` group still held out of the boot set. Drives the read-path
|
|
144
|
-
* tripwire — a lazy relation read while this is false would return empty/stale rows.
|
|
145
|
-
*/
|
|
146
|
-
isTableStarted: (tableKey: string) => boolean;
|
|
147
|
-
/**
|
|
148
|
-
* A promise that resolves the moment the given consistency group is up-to-date (ADR-0032 decision 6).
|
|
149
|
-
* Resolves immediately for an already-ready group; stays pending for a `lazy` group until it is
|
|
150
|
-
* activated (via {@link ensureGroupStarted}) and catches up. An unknown group resolves immediately
|
|
151
|
-
* (nothing to await). Per-group readiness the client re-exposes as `client.groupReady(table)`.
|
|
152
|
-
*/
|
|
153
|
-
groupReady: (groupKey: string) => Promise<void>;
|
|
154
|
-
/** Whether the given consistency group has completed its initial sync (synchronous peek at {@link groupReady}). */
|
|
155
|
-
isGroupReady: (groupKey: string) => boolean;
|
|
156
|
-
/** Every consistency-group key this config declares — the domain of {@link groupReady}/{@link isGroupReady}. */
|
|
157
|
-
groupKeys: () => string[];
|
|
158
|
-
}
|
|
159
|
-
export declare function buildShapeUrl(electricUrl: string, table: string): string;
|
|
160
|
-
export declare function buildShapeConfig(input: ShapeSyncSpec): {
|
|
161
|
-
shape: {
|
|
162
|
-
url: string;
|
|
163
|
-
};
|
|
164
|
-
table: string;
|
|
165
|
-
schema?: string;
|
|
166
|
-
primaryKey: string[];
|
|
167
|
-
shapeKey: string;
|
|
168
|
-
};
|
|
169
|
-
export declare function buildConfiguredShapeSpecs(input: SyncConfigInput): ConfiguredShapeSyncSpec[];
|
|
170
|
-
export declare function startConfiguredSync(pg: SyncEnginePGlite, input: StartConfiguredSyncOptions): Promise<StartConfiguredSyncResult>;
|
|
171
|
-
interface StartGroupSyncOptions {
|
|
172
|
-
groupKey: string;
|
|
173
|
-
specs: ConfiguredShapeSyncSpec[];
|
|
174
|
-
registry: SyncTableRegistry;
|
|
175
|
-
/**
|
|
176
|
-
* ADR-0042: the group's retention is `ephemeral`, so its sync bookkeeping (cursor + tags) is session-
|
|
177
|
-
* scoped — the engine stores it in `pg_temp` relations that die with the engine. Forwarded straight to
|
|
178
|
-
* the engine's `syncShapesToTables`; absent/`false` for a persistent group (byte-identical storage).
|
|
179
|
-
*/
|
|
180
|
-
sessionScoped?: boolean;
|
|
181
|
-
headers?: ExternalHeadersRecord;
|
|
182
|
-
/** Fresh-store prefetch overlap gate (ADR-0032 S4) — forwarded to the engine's `syncShapesToTables`. */
|
|
183
|
-
dbReady?: Promise<void>;
|
|
184
|
-
/** Boot observability (ADR-0034): the group's accumulator, stamped by the engine on delivery/apply. */
|
|
185
|
-
bootStamp?: GroupBootStamp;
|
|
186
|
-
onGroupInitialSync?: () => void;
|
|
187
|
-
onSyncError?: (error: Error) => void;
|
|
188
|
-
onAuthError?: () => void;
|
|
189
|
-
onReadStreamError?: (error: Error) => void;
|
|
190
|
-
/** A failed fetch ATTEMPT inside Electric's backoff loop; see {@link StartConfiguredSyncOptions.onReadStreamStalled}. */
|
|
191
|
-
onReadStreamStalled?: () => void;
|
|
192
|
-
onSyncActivity?: () => void;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Sync one consistency group on a single `MultiShapeStream` (ADR-0009 decision 2). All member
|
|
196
|
-
* shapes share the group's subscription key and commit atomically at a shared LSN frontier; each
|
|
197
|
-
* shape keeps its own apply strategy and column types (resolved per-shape inside the engine).
|
|
198
|
-
*/
|
|
199
|
-
export declare function startGroupSync(pg: SyncEnginePGlite, input: StartGroupSyncOptions): Promise<import("./sync").SyncShapesToTablesResult>;
|
|
200
|
-
/**
|
|
201
|
-
* The subscription key for a spec's consistency group (ADR-0009 decision 2): the explicit
|
|
202
|
-
* `consistencyGroup` when set, else the table's own `shapeKey` (a singleton group). One persisted
|
|
203
|
-
* subscription-state row exists per group key, so subscription reset enumerates these.
|
|
204
|
-
*/
|
|
205
|
-
export declare function groupSubscriptionKey(spec: Pick<ConfiguredShapeSyncSpec, "consistencyGroup" | "shapeKey">): string;
|
|
206
|
-
export {};
|
|
207
|
-
//# sourceMappingURL=shape-sync.d.ts.map
|