@pgxsinkit/client 0.1.41 → 0.1.48
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 +60 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +195 -38
- package/dist/index.js.map +8 -8
- 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.map +1 -1
- package/dist/worker/protocol.d.ts +25 -1
- 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 +6 -2
- package/src/index.ts +211 -23
- package/src/lazy-guard.ts +67 -25
- package/src/mutation.ts +30 -0
- package/src/worker/attach-sync-client.ts +33 -1
- package/src/worker/define-sync-worker.ts +39 -2
- package/src/worker/protocol.ts +26 -0
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 {
|
|
@@ -169,6 +174,7 @@ export {
|
|
|
169
174
|
assertLazyRefsActivated,
|
|
170
175
|
buildLazyGuardIndex,
|
|
171
176
|
findReferencedLazyKeysInSql,
|
|
177
|
+
findReferencedSyncedKeysInSql,
|
|
172
178
|
type LazyGuardIndex,
|
|
173
179
|
LazyRelationNotActivatedError,
|
|
174
180
|
} from "./lazy-guard";
|
|
@@ -615,6 +621,38 @@ export interface SubscribeLiveRowsInput {
|
|
|
615
621
|
export interface LiveRowsSubscription<TRow> {
|
|
616
622
|
initialRows: TRow[];
|
|
617
623
|
unsubscribe: () => void;
|
|
624
|
+
/**
|
|
625
|
+
* The `lazy` relations the query reads (the guard's scan) — the relations held out of the eager boot
|
|
626
|
+
* set. Activation (stream start) completed before the subscription registered. Informational only:
|
|
627
|
+
* {@link hydrated} — not this — reflects catch-up completion, and it now spans eager groups too.
|
|
628
|
+
*/
|
|
629
|
+
lazyTables?: readonly string[];
|
|
630
|
+
/**
|
|
631
|
+
* Present when the query reads ANY consistency group (eager OR lazy) that was NOT YET caught up at
|
|
632
|
+
* subscribe time: resolves once every such group has completed its initial catch-up AND this
|
|
633
|
+
* subscription has already delivered rows reflecting it (the seam refreshes the live query after
|
|
634
|
+
* catch-up, then resolves — rows-before-signal is guaranteed, so flipping a UI out of its loading state
|
|
635
|
+
* on this promise can never flash a false "empty"). Absent when every referenced group is already ready
|
|
636
|
+
* at subscribe time (the steady-state fast path — no extra refresh) or sync is disabled. Offline note:
|
|
637
|
+
* stays pending until the catch-up truly completes — gate empty-state COPY on it, not data access (rows
|
|
638
|
+
* flow regardless).
|
|
639
|
+
*/
|
|
640
|
+
hydrated?: Promise<void>;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Result of {@link SyncClient.prepareQuery}: the `lazy` relations the guard scanned out of the SQL
|
|
645
|
+
* (∪ the explicit `use`) and activated. Activation means the group's STREAM IS STARTED — reads are
|
|
646
|
+
* safe from the tripwire — not that its initial catch-up has completed; await
|
|
647
|
+
* {@link SyncClient.groupReady} per key for that (see ADR-0021 / ADR-0032 decision 6).
|
|
648
|
+
*
|
|
649
|
+
* Parameterized by the TABLE-NAME UNION, not the registry: `keyof TRegistry` in an output position
|
|
650
|
+
* would make the registry parameter contravariant, and `SyncClient<ConcreteRegistry>` would stop
|
|
651
|
+
* being assignable to bare-`SyncTableRegistry` supertypes — the erasure pattern consumer seams rely
|
|
652
|
+
* on. A name union in output position keeps the whole client covariant in its registry.
|
|
653
|
+
*/
|
|
654
|
+
export interface PreparedQueryResult<TTable extends string = string> {
|
|
655
|
+
lazyTables: readonly TTable[];
|
|
618
656
|
}
|
|
619
657
|
|
|
620
658
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
@@ -723,9 +761,12 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
723
761
|
) => Promise<TRows[number] | null>;
|
|
724
762
|
/**
|
|
725
763
|
* Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held
|
|
726
|
-
* out of the eager boot, resolving once
|
|
727
|
-
*
|
|
728
|
-
*
|
|
764
|
+
* out of the eager boot, resolving once each group's STREAM IS STARTED — reads are then tripwire-safe,
|
|
765
|
+
* but the initial catch-up may still be in flight (local rows can be legitimately empty/stale until it
|
|
766
|
+
* lands; await {@link groupReady} per relation for catch-up completion — deliberately separate so an
|
|
767
|
+
* offline client still reads its persisted local rows instead of hanging on the network). Idempotent —
|
|
768
|
+
* eager or already-started relations resolve immediately. Use to pre-activate before a
|
|
769
|
+
* raw/`client.drizzle` read, or as the manual escape hatch the tripwire points to.
|
|
729
770
|
*/
|
|
730
771
|
ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
|
|
731
772
|
/**
|
|
@@ -763,14 +804,16 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
763
804
|
discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;
|
|
764
805
|
/**
|
|
765
806
|
* The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
|
|
766
|
-
* (∪ the optional `use`)
|
|
767
|
-
*
|
|
768
|
-
*
|
|
769
|
-
*
|
|
770
|
-
*
|
|
771
|
-
*
|
|
807
|
+
* (∪ the optional `use`) and activate them — so a lazy relation auto-activates on *any* reference
|
|
808
|
+
* (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the query (streams started, tripwire
|
|
809
|
+
* satisfied) and returns the activated keys ({@link PreparedQueryResult}) so a consumer can further
|
|
810
|
+
* await {@link groupReady} per key for catch-up completion — the React hooks drive `hydrating` off
|
|
811
|
+
* exactly that. A backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation
|
|
812
|
+
* could not be activated. Exposed for the React live hooks (which own their query build);
|
|
813
|
+
* `query`/`queryRow` are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope —
|
|
814
|
+
* pass `use`, or `ensureSynced` first.
|
|
772
815
|
*/
|
|
773
|
-
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<
|
|
816
|
+
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<PreparedQueryResult<SyncTableName<TRegistry>>>;
|
|
774
817
|
/**
|
|
775
818
|
* Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
|
|
776
819
|
* mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
|
|
@@ -795,6 +838,16 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
795
838
|
* same readiness as a synchronous snapshot.
|
|
796
839
|
*/
|
|
797
840
|
groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
|
|
841
|
+
/**
|
|
842
|
+
* The referenced consistency groups' member tables that are NOT YET caught up at call time (ADR-0021 /
|
|
843
|
+
* ADR-0032 decision 6): scan the compiled SQL for every synced relation the query reads (∪ `use`), map
|
|
844
|
+
* each to its consistency group, and return those whose group has not completed its initial catch-up.
|
|
845
|
+
* Empty when sync is disabled OR every referenced group is already ready — the steady-state fast path in
|
|
846
|
+
* which the live-rows seam builds no `hydrated` promise. The seam (and the worker bridge) use this to gate
|
|
847
|
+
* `hydrating` uniformly across eager AND lazy groups; ACTIVATION is separate and stays lazy-only. Returns
|
|
848
|
+
* plain table-name strings (not `keyof TRegistry`) to keep the client covariant in its registry.
|
|
849
|
+
*/
|
|
850
|
+
hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];
|
|
798
851
|
/**
|
|
799
852
|
* The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
|
|
800
853
|
* snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
|
|
@@ -1224,10 +1277,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1224
1277
|
? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }
|
|
1225
1278
|
: undefined;
|
|
1226
1279
|
|
|
1280
|
+
// ADR-0039: an ordinary optimistic write activates its target's lazy consistency group (a write is a
|
|
1281
|
+
// reference, and a reference activates — the read path already does this). The runtime reports the
|
|
1282
|
+
// non-blind table keys per enqueue; this indirection is assigned once `ensureSynced`/`lazyGuardIndex`
|
|
1283
|
+
// exist below (a write never fires during boot, so it is a harmless no-op until then).
|
|
1284
|
+
let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;
|
|
1227
1285
|
const mutationRuntime = createMutationRuntime({
|
|
1228
1286
|
db: pglite,
|
|
1229
1287
|
registry: options.registry,
|
|
1230
1288
|
writeUrl: options.writeUrl,
|
|
1289
|
+
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
1231
1290
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
1232
1291
|
...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
|
|
1233
1292
|
...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
|
|
@@ -1374,6 +1433,58 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1374
1433
|
},
|
|
1375
1434
|
};
|
|
1376
1435
|
|
|
1436
|
+
// ─── Anonymous-activation diagnostic (ADR-0039) ────────────────────────────────────────────────
|
|
1437
|
+
// Per group key, whether ANY member's row filter denies (or cannot serve) an unauthenticated caller,
|
|
1438
|
+
// plus its member registry keys (for the warning). The registry is static and the group→member map is
|
|
1439
|
+
// fixed once sync is running, so it is computed once and cached.
|
|
1440
|
+
type GroupClaimsInfo = { claimsDependent: boolean; memberKeys: string[] };
|
|
1441
|
+
let groupClaimsInfoCache: Map<string, GroupClaimsInfo> | null = null;
|
|
1442
|
+
const groupClaimsInfoFor = (activeSync: NonNullable<typeof sync>): Map<string, GroupClaimsInfo> => {
|
|
1443
|
+
if (groupClaimsInfoCache != null) return groupClaimsInfoCache;
|
|
1444
|
+
const map = new Map<string, GroupClaimsInfo>();
|
|
1445
|
+
for (const key of Object.keys(options.registry) as SyncTableName<TRegistry>[]) {
|
|
1446
|
+
const groupKey = activeSync.groupKeyForTable(key as string);
|
|
1447
|
+
if (groupKey == null) continue;
|
|
1448
|
+
const entry = options.registry[key] as SyncTableEntry;
|
|
1449
|
+
const info = map.get(groupKey) ?? { claimsDependent: false, memberKeys: [] };
|
|
1450
|
+
info.memberKeys.push(key as string);
|
|
1451
|
+
if (isClaimsDependentRowFilter(entry.shape?.rowFilter)) info.claimsDependent = true;
|
|
1452
|
+
map.set(groupKey, info);
|
|
1453
|
+
}
|
|
1454
|
+
groupClaimsInfoCache = map;
|
|
1455
|
+
return map;
|
|
1456
|
+
};
|
|
1457
|
+
// One warning per group key, ever (a claims-denied group activated with no token opens an empty
|
|
1458
|
+
// subscription by construction, so repeated activations must not spam).
|
|
1459
|
+
const anonymousActivationWarned = new Set<string>();
|
|
1460
|
+
const warnIfAnonymousClaimsDependentActivation = (activeSync: NonNullable<typeof sync>, groupKey: string) => {
|
|
1461
|
+
if (anonymousActivationWarned.has(groupKey)) return;
|
|
1462
|
+
const info = groupClaimsInfoFor(activeSync).get(groupKey);
|
|
1463
|
+
if (info == null || !info.claimsDependent) return;
|
|
1464
|
+
// Fire-and-forget: activation never blocks or fails on the token probe (a rejected `getAuthToken`
|
|
1465
|
+
// is swallowed into a syncDebug line). The dedupe Set is checked+set synchronously around the warn,
|
|
1466
|
+
// so concurrent activations still emit at most one console.warn.
|
|
1467
|
+
void (async () => {
|
|
1468
|
+
try {
|
|
1469
|
+
const token = options.getAuthToken ? await options.getAuthToken() : undefined;
|
|
1470
|
+
if (token != null && token !== "") return;
|
|
1471
|
+
if (anonymousActivationWarned.has(groupKey)) return;
|
|
1472
|
+
anonymousActivationWarned.add(groupKey);
|
|
1473
|
+
console.warn(
|
|
1474
|
+
`pgxsinkit: activating the lazy group [${info.memberKeys.join(", ")}] with no auth token — its ` +
|
|
1475
|
+
`row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` +
|
|
1476
|
+
`query on auth (e.g. the React hooks' \`ready\` option) so the group activates with real claims.`,
|
|
1477
|
+
);
|
|
1478
|
+
syncDebug("anonymous activation of a claims-dependent lazy group", {
|
|
1479
|
+
groupKey,
|
|
1480
|
+
tables: info.memberKeys,
|
|
1481
|
+
});
|
|
1482
|
+
} catch (error) {
|
|
1483
|
+
syncDebug("anonymous-activation auth probe failed", { groupKey, error });
|
|
1484
|
+
}
|
|
1485
|
+
})();
|
|
1486
|
+
};
|
|
1487
|
+
|
|
1377
1488
|
// ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
|
|
1378
1489
|
const ensureSynced: SyncClient<TRegistry>["ensureSynced"] = async (keys) => {
|
|
1379
1490
|
const activeSync = sync;
|
|
@@ -1381,11 +1492,66 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1381
1492
|
const groupKeys = new Set<string>();
|
|
1382
1493
|
for (const key of keys) {
|
|
1383
1494
|
const groupKey = activeSync.groupKeyForTable(key);
|
|
1384
|
-
if (groupKey
|
|
1495
|
+
if (groupKey == null) continue;
|
|
1496
|
+
// Diagnostic at the activation choke point (ADR-0039): only for a group not yet started — an
|
|
1497
|
+
// already-active group has already paid (or dodged) this check. Write-triggered activation flows
|
|
1498
|
+
// through here too, so the warning fires for writes as well as reads.
|
|
1499
|
+
if (!activeSync.isTableStarted(key)) {
|
|
1500
|
+
warnIfAnonymousClaimsDependentActivation(activeSync, groupKey);
|
|
1501
|
+
}
|
|
1502
|
+
groupKeys.add(groupKey);
|
|
1385
1503
|
}
|
|
1386
1504
|
await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
|
|
1387
1505
|
};
|
|
1388
1506
|
|
|
1507
|
+
// ADR-0039: now `ensureSynced` + `lazyGuardIndex` exist, wire the ordinary-write activation. Filter the
|
|
1508
|
+
// reported tables to the lazy ones, then fire-and-forget `ensureSynced` — enqueue never blocks on the
|
|
1509
|
+
// network, and a failed start self-heals on the group's next activation (a `.catch` keeps the rejection
|
|
1510
|
+
// off the unhandled-rejection path).
|
|
1511
|
+
activateOrdinaryWriteTables = (tables) => {
|
|
1512
|
+
const lazyTables = tables.filter((table) => lazyGuardIndex.lazyKeys.has(table)) as SyncTableName<TRegistry>[];
|
|
1513
|
+
if (lazyTables.length === 0) return;
|
|
1514
|
+
void ensureSynced(lazyTables).catch((error) => {
|
|
1515
|
+
syncDebug("write-triggered lazy activation failed", { tables: lazyTables, error });
|
|
1516
|
+
});
|
|
1517
|
+
};
|
|
1518
|
+
|
|
1519
|
+
// Per-table catch-up completion (ADR-0032 decision 6) — the body of `client.groupReady`, hoisted so the
|
|
1520
|
+
// live-rows seam can also await it when building a subscription's `hydrated` promise.
|
|
1521
|
+
const groupReadyForTable = async (table: SyncTableName<TRegistry>): Promise<void> => {
|
|
1522
|
+
const activeSync = sync;
|
|
1523
|
+
// Sync disabled → local-only: every relation is trivially "ready" (nothing to await).
|
|
1524
|
+
if (activeSync == null) return;
|
|
1525
|
+
const groupKey = activeSync.groupKeyForTable(table as string);
|
|
1526
|
+
if (groupKey == null) return;
|
|
1527
|
+
await activeSync.groupReady(groupKey);
|
|
1528
|
+
};
|
|
1529
|
+
|
|
1530
|
+
// Synchronous peek at a table's consistency-group catch-up (ADR-0032 decision 6) — the counterpart of
|
|
1531
|
+
// `groupReadyForTable`, hoisted so the live-rows seam can compute the STEADY-STATE fast path: when every
|
|
1532
|
+
// referenced group is already ready at subscribe time, no `hydrated` promise is built (no extra refresh).
|
|
1533
|
+
const isGroupReadyForTable = (table: string): boolean => {
|
|
1534
|
+
const activeSync = sync;
|
|
1535
|
+
// Sync disabled → local-only: reads hit whatever is local, so a group is trivially "ready".
|
|
1536
|
+
if (activeSync == null) return true;
|
|
1537
|
+
const groupKey = activeSync.groupKeyForTable(table);
|
|
1538
|
+
// No consistency group (unknown/writeonly) → nothing to await; treat as ready.
|
|
1539
|
+
if (groupKey == null) return true;
|
|
1540
|
+
return activeSync.isGroupReady(groupKey);
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
// The referenced synced tables whose consistency group is NOT YET caught up (ADR-0021/0032): scan the
|
|
1544
|
+
// compiled SQL for every synced relation the query reads (∪ the explicit `use`), then keep only those
|
|
1545
|
+
// whose group is still catching up. Empty when sync is disabled OR every referenced group is already
|
|
1546
|
+
// ready — the steady-state fast path, where the live-rows seam builds no `hydrated` promise. Eager and
|
|
1547
|
+
// lazy groups are treated identically here; only ACTIVATION (elsewhere) stays lazy-only.
|
|
1548
|
+
const hydratingTablesFor = (query: { sql: string; use?: readonly string[] }): string[] => {
|
|
1549
|
+
if (sync == null) return [];
|
|
1550
|
+
const referenced = new Set<string>(query.use ?? []);
|
|
1551
|
+
for (const key of findReferencedSyncedKeysInSql(query.sql, lazyGuardIndex)) referenced.add(key);
|
|
1552
|
+
return [...referenced].filter((table) => !isGroupReadyForTable(table));
|
|
1553
|
+
};
|
|
1554
|
+
|
|
1389
1555
|
const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
|
|
1390
1556
|
const activeSync = sync;
|
|
1391
1557
|
// Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
|
|
@@ -1551,7 +1717,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1551
1717
|
// subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).
|
|
1552
1718
|
const toActivate = new Set<string>(use ?? []);
|
|
1553
1719
|
for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);
|
|
1554
|
-
|
|
1720
|
+
const lazyTables = [...toActivate] as SyncTableName<TRegistry>[];
|
|
1721
|
+
await ensureSynced(lazyTables);
|
|
1555
1722
|
// Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),
|
|
1556
1723
|
// throw rather than let the query read empty/stale. In the normal path everything scanned was just
|
|
1557
1724
|
// activated, so this passes.
|
|
@@ -1560,6 +1727,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1560
1727
|
index: lazyGuardIndex,
|
|
1561
1728
|
isActive: (key) => isSynced(key as SyncTableName<TRegistry>),
|
|
1562
1729
|
});
|
|
1730
|
+
// Activated = streams started, NOT caught up. Hand back the keys so consumers (the React hooks'
|
|
1731
|
+
// `hydrating`) can await `groupReady` per key without blocking the read on the network.
|
|
1732
|
+
return { lazyTables };
|
|
1563
1733
|
};
|
|
1564
1734
|
|
|
1565
1735
|
const runGuardedQuery = async <TRows extends readonly unknown[]>(
|
|
@@ -1684,19 +1854,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1684
1854
|
discardEphemeral,
|
|
1685
1855
|
prepareQuery,
|
|
1686
1856
|
transaction,
|
|
1687
|
-
groupReady:
|
|
1688
|
-
|
|
1689
|
-
// Sync disabled → local-only: every relation is trivially "ready" (nothing to await).
|
|
1690
|
-
if (activeSync == null) return;
|
|
1691
|
-
const groupKey = activeSync.groupKeyForTable(table as string);
|
|
1692
|
-
if (groupKey == null) return;
|
|
1693
|
-
await activeSync.groupReady(groupKey);
|
|
1694
|
-
},
|
|
1857
|
+
groupReady: groupReadyForTable,
|
|
1858
|
+
hydratingTablesFor,
|
|
1695
1859
|
// The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React
|
|
1696
1860
|
// hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
|
|
1697
1861
|
// so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
|
|
1698
1862
|
// incrementally against its own materialized state; the column set only matters for the worker bridge.
|
|
1699
|
-
subscribeLiveRows: async ({ sql, params, fields }, onRows) => {
|
|
1863
|
+
subscribeLiveRows: async ({ sql, params, fields, use }, onRows) => {
|
|
1700
1864
|
// Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
|
|
1701
1865
|
// temp-view creation (`column "title" specified more than once`) unless every output column has a
|
|
1702
1866
|
// unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
|
|
@@ -1706,11 +1870,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1706
1870
|
onRows(results.rows as never);
|
|
1707
1871
|
};
|
|
1708
1872
|
registered.subscribe(listener);
|
|
1873
|
+
let unsubscribed = false;
|
|
1874
|
+
// The query's lazy relations (guard scan ∪ `use`; the caller's `prepareQuery` already activated them)
|
|
1875
|
+
// are surfaced as `lazyTables` for observability — the relations held out of the eager boot set.
|
|
1876
|
+
const lazySet = new Set<string>(use ?? []);
|
|
1877
|
+
for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) lazySet.add(key);
|
|
1878
|
+
const lazyTables = [...lazySet];
|
|
1879
|
+
// Hydration spans EVERY referenced consistency group (eager AND lazy): the tables whose group is not
|
|
1880
|
+
// yet caught up at subscribe time. Empty (steady state / sync disabled) → NO `hydrated` promise, so a
|
|
1881
|
+
// post-boot subscription pays no extra refresh (exactly today's eager-only behaviour). Otherwise build
|
|
1882
|
+
// `hydrated` with rows-before-signal ordering: await the pending groups' catch-up, refresh the live
|
|
1883
|
+
// query against the caught-up store (its listener delivers the rows synchronously inside the refresh),
|
|
1884
|
+
// THEN resolve — so a UI flipping out of its loading state on this promise can never flash a false empty.
|
|
1885
|
+
const hydratingTables = hydratingTablesFor({ sql, ...(use ? { use } : {}) });
|
|
1886
|
+
const hydrated =
|
|
1887
|
+
hydratingTables.length > 0
|
|
1888
|
+
? Promise.all(hydratingTables.map((table) => groupReadyForTable(table as SyncTableName<TRegistry>)))
|
|
1889
|
+
.then(async () => {
|
|
1890
|
+
if (!unsubscribed) await registered.refresh();
|
|
1891
|
+
})
|
|
1892
|
+
.catch(() => undefined)
|
|
1893
|
+
: undefined;
|
|
1709
1894
|
return {
|
|
1710
1895
|
initialRows: registered.initialResults.rows as never,
|
|
1711
1896
|
unsubscribe: () => {
|
|
1897
|
+
unsubscribed = true;
|
|
1712
1898
|
void registered.unsubscribe(listener);
|
|
1713
1899
|
},
|
|
1900
|
+
...(lazyTables.length > 0 ? { lazyTables } : {}),
|
|
1901
|
+
...(hydrated ? { hydrated } : {}),
|
|
1714
1902
|
};
|
|
1715
1903
|
},
|
|
1716
1904
|
// Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
|
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) {
|
|
@@ -48,6 +48,7 @@ import {
|
|
|
48
48
|
identityCodec,
|
|
49
49
|
isBridgeEnvelope,
|
|
50
50
|
type LiveDiffPayload,
|
|
51
|
+
type LiveHydratedPayload,
|
|
51
52
|
type LiveInitialPayload,
|
|
52
53
|
postBridgeMessage,
|
|
53
54
|
type ProvisionAckPayload,
|
|
@@ -151,6 +152,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
151
152
|
{ resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }
|
|
152
153
|
>();
|
|
153
154
|
const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, "queryId">) => void>();
|
|
155
|
+
// Resolvers for per-subscription `hydrated` promises, keyed by queryId. The worker posts
|
|
156
|
+
// `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
|
|
157
|
+
// resolution here guarantees the rows have already been applied by the materializer.
|
|
158
|
+
const hydratedPending = new Map<string, () => void>();
|
|
154
159
|
|
|
155
160
|
// ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
|
|
156
161
|
const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
|
|
@@ -305,6 +310,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
305
310
|
diffHandlers.get(diff.queryId)?.(diff);
|
|
306
311
|
break;
|
|
307
312
|
}
|
|
313
|
+
case "live-hydrated": {
|
|
314
|
+
const { queryId } = payload as LiveHydratedPayload;
|
|
315
|
+
hydratedPending.get(queryId)?.();
|
|
316
|
+
hydratedPending.delete(queryId);
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
308
319
|
case "event":
|
|
309
320
|
onEvent(payload as BridgeEvent);
|
|
310
321
|
break;
|
|
@@ -409,12 +420,29 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
409
420
|
throw error;
|
|
410
421
|
}
|
|
411
422
|
const initialRows = materializer.seed(initial.rows as TRow[]);
|
|
423
|
+
// Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted
|
|
424
|
+
// after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`
|
|
425
|
+
// means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:
|
|
426
|
+
// no hydration is pending, so no promise. Resolved on unsubscribe too, so an abandoned subscription
|
|
427
|
+
// never leaves a forever-pending promise behind.
|
|
428
|
+
let hydrated: Promise<void> | undefined;
|
|
429
|
+
if (initial.hydratingTables && initial.hydratingTables.length > 0) {
|
|
430
|
+
hydrated = new Promise<void>((resolve) => {
|
|
431
|
+
hydratedPending.set(queryId, resolve);
|
|
432
|
+
});
|
|
433
|
+
}
|
|
412
434
|
return {
|
|
413
435
|
initialRows,
|
|
414
436
|
unsubscribe: () => {
|
|
415
437
|
diffHandlers.delete(queryId);
|
|
438
|
+
hydratedPending.get(queryId)?.();
|
|
439
|
+
hydratedPending.delete(queryId);
|
|
416
440
|
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
417
441
|
},
|
|
442
|
+
// The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven
|
|
443
|
+
// by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.
|
|
444
|
+
...(initial.lazyTables ? { lazyTables: initial.lazyTables } : {}),
|
|
445
|
+
...(hydrated ? { hydrated } : {}),
|
|
418
446
|
};
|
|
419
447
|
};
|
|
420
448
|
|
|
@@ -504,7 +532,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
504
532
|
discardEphemeral: (key) => rpc<void>("discardEphemeral", [key]),
|
|
505
533
|
// The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's
|
|
506
534
|
// `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
|
|
507
|
-
|
|
535
|
+
// Empty `lazyTables`: the real scan's keys travel back on the subscription itself (`live-initial`).
|
|
536
|
+
prepareQuery: async () => ({ lazyTables: [] }),
|
|
537
|
+
// The worker computes the pending hydrating tables inside its `subscribe` handler (on its owned client)
|
|
538
|
+
// and reports them back on `live-initial` (`hydratingTables`), so the tab-side seam is a no-op here.
|
|
539
|
+
hydratingTablesFor: () => [],
|
|
508
540
|
transaction: async ({ mode }: { mode: WriteMode }, run) => {
|
|
509
541
|
// Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the
|
|
510
542
|
// serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).
|