@pgxsinkit/client 0.1.46 → 0.1.49
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/dist/index.d.ts +61 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +647 -72
- package/dist/index.js.map +11 -9
- package/dist/lazy-guard.d.ts +20 -1
- package/dist/lazy-guard.d.ts.map +1 -1
- package/dist/mutation.d.ts +10 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-fingerprint.d.ts +14 -0
- package/dist/worker/live-query-fingerprint.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts +130 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +21 -5
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +25 -4
- package/skills/operating/SKILL.md +29 -1
- package/src/index.ts +243 -35
- package/src/lazy-guard.ts +67 -25
- package/src/mutation.ts +30 -0
- package/src/worker/attach-sync-client.ts +90 -16
- package/src/worker/define-sync-worker.ts +214 -52
- package/src/worker/live-query-fingerprint.ts +128 -0
- package/src/worker/live-query-manager.ts +591 -0
- package/src/worker/protocol.ts +23 -4
package/src/index.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type {
|
|
|
19
19
|
SyncTableUpdateInput,
|
|
20
20
|
WriteMode,
|
|
21
21
|
} from "@pgxsinkit/contracts";
|
|
22
|
-
import { fingerprintRegistry, getSyncRegistrySchema } from "@pgxsinkit/contracts";
|
|
22
|
+
import { fingerprintRegistry, getSyncRegistrySchema, isClaimsDependentRowFilter } from "@pgxsinkit/contracts";
|
|
23
23
|
|
|
24
24
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
25
25
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
@@ -27,7 +27,12 @@ import { syncDebug, timeAsync } from "./debug";
|
|
|
27
27
|
import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
|
|
28
28
|
import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
|
|
29
29
|
import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
|
|
30
|
-
import {
|
|
30
|
+
import {
|
|
31
|
+
assertLazyRefsActivated,
|
|
32
|
+
buildLazyGuardIndex,
|
|
33
|
+
findReferencedLazyKeysInSql,
|
|
34
|
+
findReferencedSyncedKeysInSql,
|
|
35
|
+
} from "./lazy-guard";
|
|
31
36
|
import { createLifecycleSlot } from "./lifecycle-slot";
|
|
32
37
|
import { wrapLiveQueryForMaterialization } from "./live-rows-sql";
|
|
33
38
|
import {
|
|
@@ -66,6 +71,13 @@ import {
|
|
|
66
71
|
} from "./store-path";
|
|
67
72
|
import { createSyncEngine, type SyncEngine } from "./sync";
|
|
68
73
|
import { buildShapeHeaders } from "./sync-auth";
|
|
74
|
+
import { LiveRowsMaterializer } from "./worker/live-diff";
|
|
75
|
+
import {
|
|
76
|
+
createLiveQueryManager,
|
|
77
|
+
type LiveQueryDiagnostics,
|
|
78
|
+
type LiveQueryManager,
|
|
79
|
+
validateLiveQueryPolicy,
|
|
80
|
+
} from "./worker/live-query-manager";
|
|
69
81
|
|
|
70
82
|
export { generateLocalSchemaSql };
|
|
71
83
|
export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
|
|
@@ -135,6 +147,7 @@ export {
|
|
|
135
147
|
rowKey,
|
|
136
148
|
seedLiveDiffState,
|
|
137
149
|
} from "./worker/live-diff";
|
|
150
|
+
export type { LiveQueryDiagnostics };
|
|
138
151
|
export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
|
|
139
152
|
export {
|
|
140
153
|
type AttachAckPayload,
|
|
@@ -169,6 +182,7 @@ export {
|
|
|
169
182
|
assertLazyRefsActivated,
|
|
170
183
|
buildLazyGuardIndex,
|
|
171
184
|
findReferencedLazyKeysInSql,
|
|
185
|
+
findReferencedSyncedKeysInSql,
|
|
172
186
|
type LazyGuardIndex,
|
|
173
187
|
LazyRelationNotActivatedError,
|
|
174
188
|
} from "./lazy-guard";
|
|
@@ -484,6 +498,18 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
484
498
|
* adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
|
|
485
499
|
*/
|
|
486
500
|
provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
|
|
501
|
+
/**
|
|
502
|
+
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4) — same block as
|
|
503
|
+
* {@link DefineSyncWorkerOptions.liveQueries}. Takes effect in BOTH client forms: the in-process client
|
|
504
|
+
* now owns its own manager (decision 6), so this policy governs its live-query dedup and retention just as
|
|
505
|
+
* it does the worker's. Defaults: `defaultKeepAliveMs` 0 (tear a query down the instant its last consumer
|
|
506
|
+
* leaves), `maxRetainedQueries` 16, `maxRetainedRows` 50_000.
|
|
507
|
+
*/
|
|
508
|
+
liveQueries?: {
|
|
509
|
+
defaultKeepAliveMs?: number;
|
|
510
|
+
maxRetainedQueries?: number;
|
|
511
|
+
maxRetainedRows?: number;
|
|
512
|
+
};
|
|
487
513
|
}
|
|
488
514
|
|
|
489
515
|
export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
|
|
@@ -609,6 +635,13 @@ export interface SubscribeLiveRowsInput {
|
|
|
609
635
|
* worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
|
|
610
636
|
*/
|
|
611
637
|
use?: readonly string[];
|
|
638
|
+
/**
|
|
639
|
+
* Per-subscription keep-alive hint (ms) for the live-query manager (ADR-0040 decision 4): retain this
|
|
640
|
+
* query's shared registration for the grace period after its last consumer leaves, so a re-mount reuses it
|
|
641
|
+
* verbatim (no re-materialization). Honoured in BOTH modes — the worker manager and the in-process manager
|
|
642
|
+
* (decision 6). Bounded by the `liveQueries` policy budgets. Absent → no hint.
|
|
643
|
+
*/
|
|
644
|
+
keepAliveMs?: number;
|
|
612
645
|
}
|
|
613
646
|
|
|
614
647
|
/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
|
|
@@ -616,18 +649,20 @@ export interface LiveRowsSubscription<TRow> {
|
|
|
616
649
|
initialRows: TRow[];
|
|
617
650
|
unsubscribe: () => void;
|
|
618
651
|
/**
|
|
619
|
-
* The `lazy` relations the query reads (the guard's scan)
|
|
620
|
-
*
|
|
621
|
-
*
|
|
652
|
+
* The `lazy` relations the query reads (the guard's scan) — the relations held out of the eager boot
|
|
653
|
+
* set. Activation (stream start) completed before the subscription registered. Informational only:
|
|
654
|
+
* {@link hydrated} — not this — reflects catch-up completion, and it now spans eager groups too.
|
|
622
655
|
*/
|
|
623
656
|
lazyTables?: readonly string[];
|
|
624
657
|
/**
|
|
625
|
-
* Present
|
|
626
|
-
*
|
|
627
|
-
*
|
|
628
|
-
*
|
|
629
|
-
*
|
|
630
|
-
*
|
|
658
|
+
* Present when the query reads ANY consistency group (eager OR lazy) that was NOT YET caught up at
|
|
659
|
+
* subscribe time: resolves once every such group has completed its initial catch-up AND this
|
|
660
|
+
* subscription has already delivered rows reflecting it (the seam refreshes the live query after
|
|
661
|
+
* catch-up, then resolves — rows-before-signal is guaranteed, so flipping a UI out of its loading state
|
|
662
|
+
* on this promise can never flash a false "empty"). Absent when every referenced group is already ready
|
|
663
|
+
* at subscribe time (the steady-state fast path — no extra refresh) or sync is disabled. Offline note:
|
|
664
|
+
* stays pending until the catch-up truly completes — gate empty-state COPY on it, not data access (rows
|
|
665
|
+
* flow regardless).
|
|
631
666
|
*/
|
|
632
667
|
hydrated?: Promise<void>;
|
|
633
668
|
}
|
|
@@ -637,9 +672,14 @@ export interface LiveRowsSubscription<TRow> {
|
|
|
637
672
|
* (∪ the explicit `use`) and activated. Activation means the group's STREAM IS STARTED — reads are
|
|
638
673
|
* safe from the tripwire — not that its initial catch-up has completed; await
|
|
639
674
|
* {@link SyncClient.groupReady} per key for that (see ADR-0021 / ADR-0032 decision 6).
|
|
675
|
+
*
|
|
676
|
+
* Parameterized by the TABLE-NAME UNION, not the registry: `keyof TRegistry` in an output position
|
|
677
|
+
* would make the registry parameter contravariant, and `SyncClient<ConcreteRegistry>` would stop
|
|
678
|
+
* being assignable to bare-`SyncTableRegistry` supertypes — the erasure pattern consumer seams rely
|
|
679
|
+
* on. A name union in output position keeps the whole client covariant in its registry.
|
|
640
680
|
*/
|
|
641
|
-
export interface PreparedQueryResult<
|
|
642
|
-
lazyTables: readonly
|
|
681
|
+
export interface PreparedQueryResult<TTable extends string = string> {
|
|
682
|
+
lazyTables: readonly TTable[];
|
|
643
683
|
}
|
|
644
684
|
|
|
645
685
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
@@ -800,7 +840,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
800
840
|
* `query`/`queryRow` are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope —
|
|
801
841
|
* pass `use`, or `ensureSynced` first.
|
|
802
842
|
*/
|
|
803
|
-
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<PreparedQueryResult<TRegistry
|
|
843
|
+
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<PreparedQueryResult<SyncTableName<TRegistry>>>;
|
|
804
844
|
/**
|
|
805
845
|
* Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
|
|
806
846
|
* mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
|
|
@@ -825,6 +865,16 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
825
865
|
* same readiness as a synchronous snapshot.
|
|
826
866
|
*/
|
|
827
867
|
groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
|
|
868
|
+
/**
|
|
869
|
+
* The referenced consistency groups' member tables that are NOT YET caught up at call time (ADR-0021 /
|
|
870
|
+
* ADR-0032 decision 6): scan the compiled SQL for every synced relation the query reads (∪ `use`), map
|
|
871
|
+
* each to its consistency group, and return those whose group has not completed its initial catch-up.
|
|
872
|
+
* Empty when sync is disabled OR every referenced group is already ready — the steady-state fast path in
|
|
873
|
+
* which the live-rows seam builds no `hydrated` promise. The seam (and the worker bridge) use this to gate
|
|
874
|
+
* `hydrating` uniformly across eager AND lazy groups; ACTIVATION is separate and stays lazy-only. Returns
|
|
875
|
+
* plain table-name strings (not `keyof TRegistry`) to keep the client covariant in its registry.
|
|
876
|
+
*/
|
|
877
|
+
hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];
|
|
828
878
|
/**
|
|
829
879
|
* The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
|
|
830
880
|
* snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
|
|
@@ -843,6 +893,13 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
843
893
|
* stored report. The push counterpart is the `onBootReport` client option.
|
|
844
894
|
*/
|
|
845
895
|
bootReport: () => Promise<BootReport | null>;
|
|
896
|
+
/**
|
|
897
|
+
* Live-query diagnostics (ADR-0040 decision 5): a point-in-time snapshot of the live-query manager's
|
|
898
|
+
* entries — opaque fingerprint digests plus counts/timings only, NEVER SQL, params, or row values. Both
|
|
899
|
+
* client forms return the real snapshot: in WORKER mode this pulls the worker manager's snapshot over the
|
|
900
|
+
* bridge; the IN-PROCESS client returns its own manager's snapshot directly.
|
|
901
|
+
*/
|
|
902
|
+
liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
|
|
846
903
|
/**
|
|
847
904
|
* Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
|
|
848
905
|
* store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
|
|
@@ -930,6 +987,8 @@ export function replAdapter(
|
|
|
930
987
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
931
988
|
options: CreateSyncClientOptions<TRegistry>,
|
|
932
989
|
): Promise<SyncClient<TRegistry>> {
|
|
990
|
+
// Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
|
|
991
|
+
validateLiveQueryPolicy(options.liveQueries);
|
|
933
992
|
const status: SyncRuntimeStatus = {
|
|
934
993
|
phase: "booting",
|
|
935
994
|
isRunning: false,
|
|
@@ -1254,10 +1313,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1254
1313
|
? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }
|
|
1255
1314
|
: undefined;
|
|
1256
1315
|
|
|
1316
|
+
// ADR-0039: an ordinary optimistic write activates its target's lazy consistency group (a write is a
|
|
1317
|
+
// reference, and a reference activates — the read path already does this). The runtime reports the
|
|
1318
|
+
// non-blind table keys per enqueue; this indirection is assigned once `ensureSynced`/`lazyGuardIndex`
|
|
1319
|
+
// exist below (a write never fires during boot, so it is a harmless no-op until then).
|
|
1320
|
+
let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;
|
|
1257
1321
|
const mutationRuntime = createMutationRuntime({
|
|
1258
1322
|
db: pglite,
|
|
1259
1323
|
registry: options.registry,
|
|
1260
1324
|
writeUrl: options.writeUrl,
|
|
1325
|
+
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
1261
1326
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
1262
1327
|
...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
|
|
1263
1328
|
...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
|
|
@@ -1404,6 +1469,58 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1404
1469
|
},
|
|
1405
1470
|
};
|
|
1406
1471
|
|
|
1472
|
+
// ─── Anonymous-activation diagnostic (ADR-0039) ────────────────────────────────────────────────
|
|
1473
|
+
// Per group key, whether ANY member's row filter denies (or cannot serve) an unauthenticated caller,
|
|
1474
|
+
// plus its member registry keys (for the warning). The registry is static and the group→member map is
|
|
1475
|
+
// fixed once sync is running, so it is computed once and cached.
|
|
1476
|
+
type GroupClaimsInfo = { claimsDependent: boolean; memberKeys: string[] };
|
|
1477
|
+
let groupClaimsInfoCache: Map<string, GroupClaimsInfo> | null = null;
|
|
1478
|
+
const groupClaimsInfoFor = (activeSync: NonNullable<typeof sync>): Map<string, GroupClaimsInfo> => {
|
|
1479
|
+
if (groupClaimsInfoCache != null) return groupClaimsInfoCache;
|
|
1480
|
+
const map = new Map<string, GroupClaimsInfo>();
|
|
1481
|
+
for (const key of Object.keys(options.registry) as SyncTableName<TRegistry>[]) {
|
|
1482
|
+
const groupKey = activeSync.groupKeyForTable(key as string);
|
|
1483
|
+
if (groupKey == null) continue;
|
|
1484
|
+
const entry = options.registry[key] as SyncTableEntry;
|
|
1485
|
+
const info = map.get(groupKey) ?? { claimsDependent: false, memberKeys: [] };
|
|
1486
|
+
info.memberKeys.push(key as string);
|
|
1487
|
+
if (isClaimsDependentRowFilter(entry.shape?.rowFilter)) info.claimsDependent = true;
|
|
1488
|
+
map.set(groupKey, info);
|
|
1489
|
+
}
|
|
1490
|
+
groupClaimsInfoCache = map;
|
|
1491
|
+
return map;
|
|
1492
|
+
};
|
|
1493
|
+
// One warning per group key, ever (a claims-denied group activated with no token opens an empty
|
|
1494
|
+
// subscription by construction, so repeated activations must not spam).
|
|
1495
|
+
const anonymousActivationWarned = new Set<string>();
|
|
1496
|
+
const warnIfAnonymousClaimsDependentActivation = (activeSync: NonNullable<typeof sync>, groupKey: string) => {
|
|
1497
|
+
if (anonymousActivationWarned.has(groupKey)) return;
|
|
1498
|
+
const info = groupClaimsInfoFor(activeSync).get(groupKey);
|
|
1499
|
+
if (info == null || !info.claimsDependent) return;
|
|
1500
|
+
// Fire-and-forget: activation never blocks or fails on the token probe (a rejected `getAuthToken`
|
|
1501
|
+
// is swallowed into a syncDebug line). The dedupe Set is checked+set synchronously around the warn,
|
|
1502
|
+
// so concurrent activations still emit at most one console.warn.
|
|
1503
|
+
void (async () => {
|
|
1504
|
+
try {
|
|
1505
|
+
const token = options.getAuthToken ? await options.getAuthToken() : undefined;
|
|
1506
|
+
if (token != null && token !== "") return;
|
|
1507
|
+
if (anonymousActivationWarned.has(groupKey)) return;
|
|
1508
|
+
anonymousActivationWarned.add(groupKey);
|
|
1509
|
+
console.warn(
|
|
1510
|
+
`pgxsinkit: activating the lazy group [${info.memberKeys.join(", ")}] with no auth token — its ` +
|
|
1511
|
+
`row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` +
|
|
1512
|
+
`query on auth (e.g. the React hooks' \`ready\` option) so the group activates with real claims.`,
|
|
1513
|
+
);
|
|
1514
|
+
syncDebug("anonymous activation of a claims-dependent lazy group", {
|
|
1515
|
+
groupKey,
|
|
1516
|
+
tables: info.memberKeys,
|
|
1517
|
+
});
|
|
1518
|
+
} catch (error) {
|
|
1519
|
+
syncDebug("anonymous-activation auth probe failed", { groupKey, error });
|
|
1520
|
+
}
|
|
1521
|
+
})();
|
|
1522
|
+
};
|
|
1523
|
+
|
|
1407
1524
|
// ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
|
|
1408
1525
|
const ensureSynced: SyncClient<TRegistry>["ensureSynced"] = async (keys) => {
|
|
1409
1526
|
const activeSync = sync;
|
|
@@ -1411,11 +1528,30 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1411
1528
|
const groupKeys = new Set<string>();
|
|
1412
1529
|
for (const key of keys) {
|
|
1413
1530
|
const groupKey = activeSync.groupKeyForTable(key);
|
|
1414
|
-
if (groupKey
|
|
1531
|
+
if (groupKey == null) continue;
|
|
1532
|
+
// Diagnostic at the activation choke point (ADR-0039): only for a group not yet started — an
|
|
1533
|
+
// already-active group has already paid (or dodged) this check. Write-triggered activation flows
|
|
1534
|
+
// through here too, so the warning fires for writes as well as reads.
|
|
1535
|
+
if (!activeSync.isTableStarted(key)) {
|
|
1536
|
+
warnIfAnonymousClaimsDependentActivation(activeSync, groupKey);
|
|
1537
|
+
}
|
|
1538
|
+
groupKeys.add(groupKey);
|
|
1415
1539
|
}
|
|
1416
1540
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
1417
1541
|
};
|
|
1418
1542
|
|
|
1543
|
+
// ADR-0039: now `ensureSynced` + `lazyGuardIndex` exist, wire the ordinary-write activation. Filter the
|
|
1544
|
+
// reported tables to the lazy ones, then fire-and-forget `ensureSynced` — enqueue never blocks on the
|
|
1545
|
+
// network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection
|
|
1546
|
+
// off the unhandled-rejection path).
|
|
1547
|
+
activateOrdinaryWriteTables = (tables) => {
|
|
1548
|
+
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];
|
|
1549
|
+
if (lazyTables.length === 0) return;
|
|
1550
|
+
void ensureSynced(lazyTables).catch((error) => {
|
|
1551
|
+
syncDebug("write-triggered lazy activation failed", { tables: lazyTables, error });
|
|
1552
|
+
});
|
|
1553
|
+
};
|
|
1554
|
+
|
|
1419
1555
|
// Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the
|
|
1420
1556
|
// live-rows seam can also await it when building a subscription's `hydrated` promise.
|
|
1421
1557
|
const groupReadyForTable = async (table: SyncTableName<TRegistry>): Promise<void> => {
|
|
@@ -1427,6 +1563,31 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1427
1563
|
await activeSync.groupReady(groupKey);
|
|
1428
1564
|
};
|
|
1429
1565
|
|
|
1566
|
+
// Synchronous peek at a table's consistency-group catch-up (ADR-0032 decision 6) — the counterpart of
|
|
1567
|
+
// `groupReadyForTable`, hoisted so the live-rows seam can compute the STEADY-STATE fast path: when every
|
|
1568
|
+
// referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).
|
|
1569
|
+
const isGroupReadyForTable = (table: string): boolean => {
|
|
1570
|
+
const activeSync = sync;
|
|
1571
|
+
// Sync disabled → local-only: reads hit whatever is local, so a group is trivially "ready".
|
|
1572
|
+
if (activeSync == null) return true;
|
|
1573
|
+
const groupKey = activeSync.groupKeyForTable(table);
|
|
1574
|
+
// No consistency group (unknown/writeonly) → nothing to await; treat as ready.
|
|
1575
|
+
if (groupKey == null) return true;
|
|
1576
|
+
return activeSync.isGroupReady(groupKey);
|
|
1577
|
+
};
|
|
1578
|
+
|
|
1579
|
+
// The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the
|
|
1580
|
+
// compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those
|
|
1581
|
+
// whose group is still catching up. Empty when sync is disabled OR every referenced group is already
|
|
1582
|
+
// ready — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. Eager and
|
|
1583
|
+
// lazy groups are treated identically here; only ACTIVATION (elsewhere) stays lazy-only.
|
|
1584
|
+
const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {
|
|
1585
|
+
if (sync == null) return [];
|
|
1586
|
+
const referenced = new Set<string>(query.use ?? []);
|
|
1587
|
+
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);
|
|
1588
|
+
return [...referenced].filter((table) => !isGroupReadyForTable(table));
|
|
1589
|
+
};
|
|
1590
|
+
|
|
1430
1591
|
const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
|
|
1431
1592
|
const activeSync = sync;
|
|
1432
1593
|
// Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
|
|
@@ -1616,6 +1777,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1616
1777
|
return builder;
|
|
1617
1778
|
};
|
|
1618
1779
|
|
|
1780
|
+
// The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
|
|
1781
|
+
// client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
|
|
1782
|
+
// bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
|
|
1783
|
+
// settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).
|
|
1784
|
+
// It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.
|
|
1785
|
+
const liveManager: LiveQueryManager = createLiveQueryManager({
|
|
1786
|
+
live: pglite.live,
|
|
1787
|
+
...(options.liveQueries ? { policy: options.liveQueries } : {}),
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1619
1790
|
const client: SyncClient<TRegistry> = {
|
|
1620
1791
|
drizzle: drizzleDb,
|
|
1621
1792
|
pglite,
|
|
@@ -1650,6 +1821,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1650
1821
|
// point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
|
|
1651
1822
|
// preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
|
|
1652
1823
|
await engine.close();
|
|
1824
|
+
// Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any
|
|
1825
|
+
// keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
|
|
1826
|
+
await liveManager.dispose();
|
|
1653
1827
|
await pglite.close();
|
|
1654
1828
|
},
|
|
1655
1829
|
destroy: (destroyOptions) =>
|
|
@@ -1684,6 +1858,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1684
1858
|
// Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
|
|
1685
1859
|
// the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
|
|
1686
1860
|
await engine.close();
|
|
1861
|
+
// Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as
|
|
1862
|
+
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
1863
|
+
await liveManager.dispose();
|
|
1687
1864
|
await pglite.close();
|
|
1688
1865
|
}),
|
|
1689
1866
|
dropReadCache: () =>
|
|
@@ -1730,41 +1907,69 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1730
1907
|
prepareQuery,
|
|
1731
1908
|
transaction,
|
|
1732
1909
|
groupReady: groupReadyForTable,
|
|
1733
|
-
|
|
1734
|
-
//
|
|
1735
|
-
//
|
|
1736
|
-
//
|
|
1737
|
-
|
|
1910
|
+
hydratingTablesFor,
|
|
1911
|
+
// The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical
|
|
1912
|
+
// contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent
|
|
1913
|
+
// subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff
|
|
1914
|
+
// stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a
|
|
1915
|
+
// per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
|
|
1916
|
+
// public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
|
|
1917
|
+
// identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
|
|
1918
|
+
// exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.
|
|
1919
|
+
subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
|
|
1738
1920
|
// Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
|
|
1739
1921
|
// temp-view creation (`column "title" specified more than once`) unless every output column has a
|
|
1740
|
-
// unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
|
|
1922
|
+
// unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows). The wrap stays
|
|
1923
|
+
// caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL.
|
|
1741
1924
|
const materialSql = wrapLiveQueryForMaterialization(sql, fields);
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1925
|
+
// Keyless materializer (matches the inline seam, which never passed pkColumns): initial rows seed it;
|
|
1926
|
+
// each diff folds into a fresh ordered array whose unchanged rows keep their object identity.
|
|
1927
|
+
const materializer = new LiveRowsMaterializer<Record<string, unknown>>(undefined);
|
|
1928
|
+
const subscription = await liveManager.subscribe(
|
|
1929
|
+
{ materialSql, params: params as unknown[] },
|
|
1930
|
+
{
|
|
1931
|
+
// The initial snapshot is returned via `initialRows`, NOT `onRows` (which fires on CHANGES only) —
|
|
1932
|
+
// so `deliverInitial` just seeds the materializer; `initialRows` is read from it below.
|
|
1933
|
+
deliverInitial: (rows) => {
|
|
1934
|
+
materializer.seed(rows);
|
|
1935
|
+
},
|
|
1936
|
+
deliverDiff: (diff) => {
|
|
1937
|
+
onRows(materializer.apply(diff) as never);
|
|
1938
|
+
},
|
|
1939
|
+
},
|
|
1940
|
+
keepAliveMs != null ? { keepAliveMs } : undefined,
|
|
1941
|
+
);
|
|
1942
|
+
// Seeded synchronously by `deliverInitial` during `subscribe` above.
|
|
1943
|
+
const initialRows = materializer.current();
|
|
1747
1944
|
let unsubscribed = false;
|
|
1748
|
-
// The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated
|
|
1749
|
-
//
|
|
1750
|
-
// groups' catch-up, refresh the live query against the caught-up store (its listener delivers the
|
|
1751
|
-
// rows synchronously inside the refresh), THEN resolve — matching the worker bridge's contract.
|
|
1945
|
+
// The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)
|
|
1946
|
+
// are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.
|
|
1752
1947
|
const lazySet = new Set<string>(use ?? []);
|
|
1753
1948
|
for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) lazySet.add(key);
|
|
1754
1949
|
const lazyTables = [...lazySet];
|
|
1950
|
+
// Hydration spans EVERY referenced consistency group (eager AND lazy): the tables whose group is not
|
|
1951
|
+
// yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a
|
|
1952
|
+
// post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build
|
|
1953
|
+
// `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live
|
|
1954
|
+
// query (the manager's coalesced refresh; its listener delivers the caught-up rows as a diff → onRows,
|
|
1955
|
+
// synchronously inside the refresh), THEN resolve — so a UI flipping out of its loading state on this
|
|
1956
|
+
// promise can never flash a false empty.
|
|
1957
|
+
const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });
|
|
1755
1958
|
const hydrated =
|
|
1756
|
-
|
|
1757
|
-
? Promise.all(
|
|
1959
|
+
hydratingTables.length > 0
|
|
1960
|
+
? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))
|
|
1758
1961
|
.then(async () => {
|
|
1759
|
-
if (!unsubscribed) await
|
|
1962
|
+
if (!unsubscribed) await subscription.refresh();
|
|
1760
1963
|
})
|
|
1761
1964
|
.catch(() => undefined)
|
|
1762
1965
|
: undefined;
|
|
1763
1966
|
return {
|
|
1764
|
-
initialRows:
|
|
1967
|
+
initialRows: initialRows as never,
|
|
1765
1968
|
unsubscribe: () => {
|
|
1766
1969
|
unsubscribed = true;
|
|
1767
|
-
|
|
1970
|
+
// Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
|
|
1971
|
+
// `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).
|
|
1972
|
+
void subscription.unsubscribe();
|
|
1768
1973
|
},
|
|
1769
1974
|
...(lazyTables.length > 0 ? { lazyTables } : {}),
|
|
1770
1975
|
...(hydrated ? { hydrated } : {}),
|
|
@@ -1773,6 +1978,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1773
1978
|
// Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
|
|
1774
1979
|
// early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.
|
|
1775
1980
|
bootReport: async () => finalizedBootReport,
|
|
1981
|
+
// Live-query diagnostics (ADR-0040 decisions 5 & 6): the in-process client now owns a real manager, so
|
|
1982
|
+
// this returns its live snapshot (digests + counts/timings only — never SQL/params/rows).
|
|
1983
|
+
liveQueryDiagnostics: async () => liveManager.snapshot(),
|
|
1776
1984
|
exportStore: async (exportOptions) => {
|
|
1777
1985
|
// Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
|
|
1778
1986
|
// take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
|
package/src/lazy-guard.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type { SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
|
19
19
|
* construction — schema and all. See "Known limitations" in ADR-0021 for the residual edges.
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
/** Static index of a registry's
|
|
22
|
+
/** Static index of a registry's synced relations and the exact quoted tokens their reads compile to. */
|
|
23
23
|
export interface LazyGuardIndex {
|
|
24
24
|
/** Registry keys whose subscription timing is `lazy`. */
|
|
25
25
|
readonly lazyKeys: ReadonlySet<string>;
|
|
@@ -31,41 +31,69 @@ export interface LazyGuardIndex {
|
|
|
31
31
|
* token collision-proof against bare aliases/CTEs.
|
|
32
32
|
*/
|
|
33
33
|
readonly lazyTokens: ReadonlyMap<string, readonly string[]>;
|
|
34
|
+
/**
|
|
35
|
+
* EVERY synced relation key (eager AND lazy). {@link lazyKeys} is a subset. Drives the hydration
|
|
36
|
+
* guarantee (ADR-0021/0032): a live subscription must gate `hydrating` on every consistency group it
|
|
37
|
+
* reads, not only the lazy ones — an eager group can still be catching up on a cold boot.
|
|
38
|
+
*/
|
|
39
|
+
readonly allKeys: ReadonlySet<string>;
|
|
40
|
+
/**
|
|
41
|
+
* Per synced key (eager AND lazy), the exact quoted reference token(s) its reads compile to — the same
|
|
42
|
+
* token rules as {@link lazyTokens}, just spanning every subscription timing. {@link lazyTokens} is a
|
|
43
|
+
* subset restricted to the lazy keys (activation stays lazy-only; hydration spans all).
|
|
44
|
+
*/
|
|
45
|
+
readonly allTokens: ReadonlyMap<string, readonly string[]>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The exact quoted reference token(s) a compiled read of `entry` emits — the synced base table (and, for
|
|
50
|
+
* readwrite, its read-model view), or a read PROJECTION's (ADR-0025) DISTINCT local identity. Shared by
|
|
51
|
+
* the lazy-only and all-relations index builds so a token matches emission by construction.
|
|
52
|
+
*/
|
|
53
|
+
function tokensForEntry(entry: SyncTableRegistry[string]): string[] {
|
|
54
|
+
const tokens: string[] = [];
|
|
55
|
+
if (entry.readProjection) {
|
|
56
|
+
// A read PROJECTION (defineReadProjection, ADR-0025) owns no physical table: its `entry.table` is the
|
|
57
|
+
// OWNER's physical table, but a consumer reads it ONLY through its DISTINCT local identity
|
|
58
|
+
// `entry.localTable` (the `as` name — where Electric syncs the projection's rows). Token that, NOT the
|
|
59
|
+
// owner's physical name: a read of the projection's own local table then resolves to it, while a read of
|
|
60
|
+
// the owner's table resolves the OWNER entry (which carries the owner token) without falsely resolving
|
|
61
|
+
// this projection. (A projection is always readonly and has no read-model view.)
|
|
62
|
+
const localTable = getTableConfig(entry.localTable);
|
|
63
|
+
tokens.push(quotedRef(localTable.name, localTable.schema));
|
|
64
|
+
} else {
|
|
65
|
+
// A regular entry is read through the synced base table (and, for readwrite, its read-model view);
|
|
66
|
+
// `entry.localTable` shares the base table's name here, so no extra token is needed.
|
|
67
|
+
const table = getTableConfig(entry.table);
|
|
68
|
+
tokens.push(quotedRef(table.name, table.schema));
|
|
69
|
+
if (entry.view != null) {
|
|
70
|
+
const view = getViewConfig(entry.view);
|
|
71
|
+
tokens.push(quotedRef(view.name, view.schema));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return tokens;
|
|
34
75
|
}
|
|
35
76
|
|
|
36
77
|
/** Build the {@link LazyGuardIndex} for a registry. Cheap and pure — cache it per client. */
|
|
37
78
|
export function buildLazyGuardIndex(registry: SyncTableRegistry): LazyGuardIndex {
|
|
38
79
|
const lazyKeys = new Set<string>();
|
|
39
80
|
const lazyTokens = new Map<string, readonly string[]>();
|
|
81
|
+
const allKeys = new Set<string>();
|
|
82
|
+
const allTokens = new Map<string, readonly string[]>();
|
|
40
83
|
|
|
41
84
|
for (const [key, entry] of Object.entries(registry)) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
// owner's physical name: a read of the projection's own local table then activates it, while a read of
|
|
51
|
-
// the owner's table activates the OWNER entry (which carries the owner token) without falsely
|
|
52
|
-
// activating this projection. (A projection is always readonly and has no read-model view.)
|
|
53
|
-
const localTable = getTableConfig(entry.localTable);
|
|
54
|
-
tokens.push(quotedRef(localTable.name, localTable.schema));
|
|
55
|
-
} else {
|
|
56
|
-
// A regular entry is read through the synced base table (and, for readwrite, its read-model view);
|
|
57
|
-
// `entry.localTable` shares the base table's name here, so no extra token is needed.
|
|
58
|
-
const table = getTableConfig(entry.table);
|
|
59
|
-
tokens.push(quotedRef(table.name, table.schema));
|
|
60
|
-
if (entry.view != null) {
|
|
61
|
-
const view = getViewConfig(entry.view);
|
|
62
|
-
tokens.push(quotedRef(view.name, view.schema));
|
|
63
|
-
}
|
|
85
|
+
const tokens = tokensForEntry(entry);
|
|
86
|
+
allKeys.add(key);
|
|
87
|
+
allTokens.set(key, tokens);
|
|
88
|
+
// ACTIVATION stays lazy-only (ADR-0021): eager groups start at boot, so only lazy keys enter the lazy
|
|
89
|
+
// maps the `prepareQuery`/`ensureSynced` guard scans. Hydration (all keys) is a superset.
|
|
90
|
+
if (entry.subscription === "lazy") {
|
|
91
|
+
lazyKeys.add(key);
|
|
92
|
+
lazyTokens.set(key, tokens);
|
|
64
93
|
}
|
|
65
|
-
lazyTokens.set(key, tokens);
|
|
66
94
|
}
|
|
67
95
|
|
|
68
|
-
return { lazyKeys, lazyTokens };
|
|
96
|
+
return { lazyKeys, lazyTokens, allKeys, allTokens };
|
|
69
97
|
}
|
|
70
98
|
|
|
71
99
|
/** The quoted identifier Drizzle emits for a relation: `"schema"."name"` when schema-qualified, else `"name"`. */
|
|
@@ -88,6 +116,20 @@ export function findReferencedLazyKeysInSql(sql: string, index: LazyGuardIndex):
|
|
|
88
116
|
return found;
|
|
89
117
|
}
|
|
90
118
|
|
|
119
|
+
/**
|
|
120
|
+
* The compiled-SQL scan across EVERY synced relation (eager AND lazy): the registry keys whose quoted
|
|
121
|
+
* reference token appears in `sql`. Same exact-token matching as {@link findReferencedLazyKeysInSql}, just
|
|
122
|
+
* over {@link LazyGuardIndex.allTokens}. Drives the hydration guarantee — the caller maps each key to its
|
|
123
|
+
* consistency group and gates a live subscription's `hydrating` on every group still catching up.
|
|
124
|
+
*/
|
|
125
|
+
export function findReferencedSyncedKeysInSql(sql: string, index: LazyGuardIndex): Set<string> {
|
|
126
|
+
const found = new Set<string>();
|
|
127
|
+
for (const [key, tokens] of index.allTokens) {
|
|
128
|
+
if (tokens.some((token) => sqlReferencesToken(sql, token))) found.add(key);
|
|
129
|
+
}
|
|
130
|
+
return found;
|
|
131
|
+
}
|
|
132
|
+
|
|
91
133
|
function sqlReferencesToken(sql: string, token: string): boolean {
|
|
92
134
|
for (let from = 0; ;) {
|
|
93
135
|
const at = sql.indexOf(token, from);
|
package/src/mutation.ts
CHANGED
|
@@ -218,6 +218,16 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
|
|
|
218
218
|
* surfaces the typed reason (e.g. "full") rather than a resolve/diff UI. Never silent.
|
|
219
219
|
*/
|
|
220
220
|
onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
|
|
221
|
+
/**
|
|
222
|
+
* Invoked once per enqueue with the DISTINCT non-blind table keys of the planned batch (ADR-0039).
|
|
223
|
+
* An ordinary optimistic `create`/`update`/`delete` is a reference to its target, and a reference
|
|
224
|
+
* activates the target's lazy consistency group — the read path does this implicitly, the write path
|
|
225
|
+
* did not. The client wires this to a fire-and-forget `ensureSynced`, so the group is open by the time
|
|
226
|
+
* the echo returns. Purely-blind batches (only `updateBlind`) report nothing: a blind write is the
|
|
227
|
+
* deliberate no-echo, no-activation write-only exception. Fire-and-forget from the runtime's view —
|
|
228
|
+
* never awaited, and a throw here must never fail the enqueue (the runtime guards the call).
|
|
229
|
+
*/
|
|
230
|
+
onOrdinaryEnqueue?: (tables: readonly string[]) => void;
|
|
221
231
|
}
|
|
222
232
|
|
|
223
233
|
interface TableContext {
|
|
@@ -566,6 +576,26 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
566
576
|
const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;
|
|
567
577
|
|
|
568
578
|
const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));
|
|
579
|
+
|
|
580
|
+
// ADR-0039: report the DISTINCT non-blind table keys so the client can fire-and-forget activate
|
|
581
|
+
// each target's lazy consistency group. A blind update plans a journal row only (no echo, no
|
|
582
|
+
// activation — the write-only pattern), so it is never reported; create/delete are never blind.
|
|
583
|
+
const ordinaryTables = new Set<string>();
|
|
584
|
+
for (const item of normalizedItems) {
|
|
585
|
+
if (item.kind === "update" && item.blind) {
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
ordinaryTables.add(item.context.key);
|
|
589
|
+
}
|
|
590
|
+
if (ordinaryTables.size > 0 && options.onOrdinaryEnqueue) {
|
|
591
|
+
try {
|
|
592
|
+
options.onOrdinaryEnqueue([...ordinaryTables]);
|
|
593
|
+
} catch {
|
|
594
|
+
// A hook throw must never fail the enqueue (ADR-0039): the activation is a fire-and-forget
|
|
595
|
+
// best-effort; the group self-heals on its next activation regardless.
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
569
599
|
const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();
|
|
570
600
|
|
|
571
601
|
for (const item of normalizedItems) {
|