@pgxsinkit/client 0.1.46 → 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 +33 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +134 -25
- 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 +12 -4
- 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 +1 -1
- package/src/index.ts +152 -21
- package/src/lazy-guard.ts +67 -25
- package/src/mutation.ts +30 -0
- package/src/worker/attach-sync-client.ts +11 -6
- package/src/worker/define-sync-worker.ts +15 -6
- package/src/worker/protocol.ts +12 -4
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) {
|
|
@@ -420,11 +420,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
420
420
|
throw error;
|
|
421
421
|
}
|
|
422
422
|
const initialRows = materializer.seed(initial.rows as TRow[]);
|
|
423
|
-
//
|
|
424
|
-
//
|
|
425
|
-
//
|
|
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.
|
|
426
428
|
let hydrated: Promise<void> | undefined;
|
|
427
|
-
if (initial.
|
|
429
|
+
if (initial.hydratingTables && initial.hydratingTables.length > 0) {
|
|
428
430
|
hydrated = new Promise<void>((resolve) => {
|
|
429
431
|
hydratedPending.set(queryId, resolve);
|
|
430
432
|
});
|
|
@@ -437,8 +439,8 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
437
439
|
hydratedPending.delete(queryId);
|
|
438
440
|
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
439
441
|
},
|
|
440
|
-
// The lazy relations the worker's guard activated for this query
|
|
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.
|
|
442
444
|
...(initial.lazyTables ? { lazyTables: initial.lazyTables } : {}),
|
|
443
445
|
...(hydrated ? { hydrated } : {}),
|
|
444
446
|
};
|
|
@@ -532,6 +534,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
532
534
|
// `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
|
|
533
535
|
// Empty `lazyTables`: the real scan's keys travel back on the subscription itself (`live-initial`).
|
|
534
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: () => [],
|
|
535
540
|
transaction: async ({ mode }: { mode: WriteMode }, run) => {
|
|
536
541
|
// Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the
|
|
537
542
|
// serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).
|
|
@@ -454,6 +454,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
454
454
|
// The activated keys travel back on the initial snapshot: activation is stream-start, not catch-up,
|
|
455
455
|
// so the tab needs them to await `groupReady` (its `hydrating` signal) without blocking this register.
|
|
456
456
|
const prepared = await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });
|
|
457
|
+
// Hydration spans EVERY referenced consistency group (eager AND lazy), computed on the real client the
|
|
458
|
+
// worker owns: the referenced tables whose group is not yet caught up at subscribe time. Empty (steady
|
|
459
|
+
// state / sync disabled) → no `hydrated` gating at all; otherwise it drives both the `live-initial`
|
|
460
|
+
// `hydratingTables` field (the tab's `hydrating` source) and the `live-hydrated` block below.
|
|
461
|
+
const hydratingTables = active.hydratingTablesFor({ sql, ...(use ? { use: use as string[] } : {}) });
|
|
457
462
|
|
|
458
463
|
const live = active.pglite.live;
|
|
459
464
|
// Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
|
|
@@ -478,7 +483,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
478
483
|
{
|
|
479
484
|
queryId,
|
|
480
485
|
rows: registered.initialResults.rows,
|
|
486
|
+
// `lazyTables` = the activated lazy relations (observability); `hydratingTables` = the referenced
|
|
487
|
+
// groups (eager OR lazy) still catching up, which the tab turns into its `hydrated` promise.
|
|
481
488
|
...(prepared.lazyTables.length > 0 ? { lazyTables: prepared.lazyTables.map(String) } : {}),
|
|
489
|
+
...(hydratingTables.length > 0 ? { hydratingTables: [...hydratingTables] } : {}),
|
|
482
490
|
},
|
|
483
491
|
id,
|
|
484
492
|
);
|
|
@@ -495,12 +503,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
495
503
|
});
|
|
496
504
|
|
|
497
505
|
// Hydration completion travels the SAME port as the diff stream, so ordering is guaranteed: await the
|
|
498
|
-
//
|
|
499
|
-
// posts the rows as a live-diff, synchronously inside the refresh), THEN post
|
|
500
|
-
// therefore always has the caught-up rows before its `hydrated` resolves — a
|
|
501
|
-
// channel (e.g. the `groupReady` broadcast) can beat the rows and flash a
|
|
502
|
-
|
|
503
|
-
|
|
506
|
+
// pending groups' catch-up (eager AND lazy), force one refresh of the live query against the caught-up
|
|
507
|
+
// store (its listener posts the rows as a live-diff, synchronously inside the refresh), THEN post
|
|
508
|
+
// `live-hydrated`. The tab therefore always has the caught-up rows before its `hydrated` resolves — a
|
|
509
|
+
// readiness signal on a side channel (e.g. the `groupReady` broadcast) can beat the rows and flash a
|
|
510
|
+
// false "empty" state. Skipped entirely when nothing is pending (steady state / sync disabled).
|
|
511
|
+
if (hydratingTables.length > 0) {
|
|
512
|
+
void Promise.all(hydratingTables.map((key) => active.groupReady(key as SyncTableName<TRegistry>)))
|
|
504
513
|
.then(async () => {
|
|
505
514
|
if (!liveSubs.has(queryId)) return; // unsubscribed while catching up
|
|
506
515
|
await registered.refresh();
|
package/src/worker/protocol.ts
CHANGED
|
@@ -306,11 +306,18 @@ export interface LiveInitialPayload {
|
|
|
306
306
|
queryId: string;
|
|
307
307
|
rows: Record<string, unknown>[];
|
|
308
308
|
/**
|
|
309
|
-
* The `lazy` relations the worker's guard activated for this query (ADR-0021)
|
|
310
|
-
* the
|
|
311
|
-
* `
|
|
309
|
+
* The `lazy` relations the worker's guard activated for this query (ADR-0021) — the relations held out
|
|
310
|
+
* of the eager boot set. Observability only: {@link hydratingTables}, not this, drives the tab's
|
|
311
|
+
* `hydrated` promise.
|
|
312
312
|
*/
|
|
313
313
|
lazyTables?: string[];
|
|
314
|
+
/**
|
|
315
|
+
* The referenced consistency groups' member tables (eager OR lazy) that were NOT YET caught up when this
|
|
316
|
+
* snapshot was taken (ADR-0021 / ADR-0032). Non-empty → the tab builds a `hydrated` promise the worker
|
|
317
|
+
* settles via `live-hydrated` (posted after the catch-up rows on this same port). Absent → every
|
|
318
|
+
* referenced group was already ready (steady state) or sync is disabled: nothing to hydrate.
|
|
319
|
+
*/
|
|
320
|
+
hydratingTables?: string[];
|
|
314
321
|
}
|
|
315
322
|
|
|
316
323
|
/**
|
|
@@ -318,7 +325,8 @@ export interface LiveInitialPayload {
|
|
|
318
325
|
* query has been refreshed against the caught-up store (ADR-0021). Posted on the SAME port as the
|
|
319
326
|
* live-diff stream, strictly after the refresh-triggered diff — so when the tab sees this, the rows
|
|
320
327
|
* reflecting the catch-up have already been delivered. Resolves the tab subscription's `hydrated`
|
|
321
|
-
* promise (the React hooks' `hydrating` gate); never sent for a query with no
|
|
328
|
+
* promise (the React hooks' `hydrating` gate); never sent for a query with no pending groups (steady
|
|
329
|
+
* state / sync disabled), i.e. an empty `live-initial` {@link LiveInitialPayload.hydratingTables}.
|
|
322
330
|
*/
|
|
323
331
|
export interface LiveHydratedPayload {
|
|
324
332
|
queryId: string;
|