@pgxsinkit/client 0.1.51 → 0.1.53
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/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +66 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +213 -55
- package/dist/index.js.map +15 -13
- package/dist/local-tables.d.ts +6 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +4 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +41 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +17 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +6 -2
- package/skills/operating/SKILL.md +28 -5
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/index.ts +175 -41
- package/src/local-tables.ts +7 -0
- package/src/sync/apply.ts +164 -26
- package/src/sync/index.ts +31 -7
- package/src/worker/attach-sync-client.ts +119 -20
- package/src/worker/define-sync-worker.ts +112 -2
- package/src/worker/live-query-manager.ts +6 -0
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +28 -0
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PGlite, type Results } from "@electric-sql/pglite";
|
|
1
|
+
import { PGlite, type QueryOptions, type Results } from "@electric-sql/pglite";
|
|
2
2
|
import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
|
|
3
3
|
import type { PgliteDatabase } from "drizzle-orm/pglite";
|
|
4
4
|
import { drizzle } from "drizzle-orm/pglite";
|
|
@@ -25,6 +25,7 @@ import { fingerprintRegistry, getSyncRegistrySchema, isClaimsDependentRowFilter
|
|
|
25
25
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
26
26
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
27
27
|
import { syncDebug, timeAsync } from "./debug";
|
|
28
|
+
import { describeErrorChain } from "./error-chain";
|
|
28
29
|
import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
|
|
29
30
|
import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
|
|
30
31
|
import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
|
|
@@ -276,6 +277,21 @@ export interface CreateClientPGliteOptions {
|
|
|
276
277
|
* asset load), so it never fails the create.
|
|
277
278
|
*/
|
|
278
279
|
bootAssets?: Promise<PgliteBootAssets>;
|
|
280
|
+
/**
|
|
281
|
+
* Relax PGlite's per-query durability (default `true`; ADR-0047) — the SINGLE resolution point for the
|
|
282
|
+
* default, which lives HERE and only here. On PGlite's idb backend every query otherwise ends with a
|
|
283
|
+
* SYNCHRONOUS flush of the whole datadir to IndexedDB, and that flush — not the query — dominates local
|
|
284
|
+
* write latency (a measured ~50ms+ floor per statement in a consumer). With relaxed durability a query
|
|
285
|
+
* returns BEFORE the flush and the flush is scheduled asynchronously, so latency reflects the query
|
|
286
|
+
* itself. Passed straight into `PGlite.create` and stamped onto the `boot pglite.create` rail.
|
|
287
|
+
*
|
|
288
|
+
* Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) are ever at risk, and only on a crash before
|
|
289
|
+
* BOTH (a) their journal rows reach the write API — which happens within ~hundreds of ms of enqueue — and
|
|
290
|
+
* (b) the scheduled idb flush lands. Synced tables are recoverable from the server by construction
|
|
291
|
+
* (ADR-0036), so relaxing their flush TIMING — not their persistence — costs nothing durable; consumer
|
|
292
|
+
* local-only tables carry whatever risk the consumer accepts. Opt out with `relaxedDurability: false`.
|
|
293
|
+
*/
|
|
294
|
+
relaxedDurability?: boolean;
|
|
279
295
|
/**
|
|
280
296
|
* @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
|
|
281
297
|
* scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
|
|
@@ -329,6 +345,11 @@ export async function createClientPGlite(
|
|
|
329
345
|
// result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
|
|
330
346
|
// pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
|
|
331
347
|
const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
|
|
348
|
+
// Relaxed durability (ADR-0047) — resolved HERE, the single default point: every store minting path
|
|
349
|
+
// (createSyncClient's own create, the worker's default createPglite factory, spare/prewarm mints) funnels
|
|
350
|
+
// through this function, so the `?? true` here is the whole toolkit's default. On idb the per-query
|
|
351
|
+
// synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
|
|
352
|
+
const relaxedDurability = options?.relaxedDurability ?? true;
|
|
332
353
|
return (await timeAsync(
|
|
333
354
|
"boot pglite.create",
|
|
334
355
|
() =>
|
|
@@ -340,6 +361,7 @@ export async function createClientPGlite(
|
|
|
340
361
|
// `electric` namespace is provisioned later, exactly as the registry-derived schema is.
|
|
341
362
|
PGlite.create(dataDir, {
|
|
342
363
|
...(bootAssets ?? {}),
|
|
364
|
+
relaxedDurability,
|
|
343
365
|
// Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
|
|
344
366
|
// `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
|
|
345
367
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
@@ -349,7 +371,9 @@ export async function createClientPGlite(
|
|
|
349
371
|
live,
|
|
350
372
|
},
|
|
351
373
|
}),
|
|
352
|
-
|
|
374
|
+
// Stamp the resolved durability mode alongside the storage scheme so every boot-rail capture shows the
|
|
375
|
+
// mode the store was created under (ADR-0047 diagnosability).
|
|
376
|
+
{ dataDir: dataDirScheme, relaxedDurability },
|
|
353
377
|
// `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
|
|
354
378
|
// extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
|
|
355
379
|
)) as unknown as ClientPGlite;
|
|
@@ -399,6 +423,20 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
399
423
|
* falls back to loading its own assets, so this is a pure best-effort accelerator.
|
|
400
424
|
*/
|
|
401
425
|
pgliteBootAssets?: Promise<PgliteBootAssets>;
|
|
426
|
+
/**
|
|
427
|
+
* Relax PGlite's per-query durability for the client-owned store create (default `true`; ADR-0047).
|
|
428
|
+
* Forwarded verbatim to {@link createClientPGlite}, where the default is resolved — on the idb backend the
|
|
429
|
+
* per-query synchronous flush to IndexedDB dominates local write latency, so the toolkit defaults to
|
|
430
|
+
* relaxed (the query returns before the flush; the flush is scheduled asynchronously).
|
|
431
|
+
*
|
|
432
|
+
* Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a crash before
|
|
433
|
+
* BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the scheduled idb
|
|
434
|
+
* flush lands. Synced tables are recoverable from the server by construction, so this relaxes flush
|
|
435
|
+
* TIMING, not persistence (ADR-0036); consumer local-only tables carry whatever risk the consumer
|
|
436
|
+
* accepts. Ignored on the {@link pgliteInstance} path (the caller owns that store's create). Opt out with
|
|
437
|
+
* `relaxedDurability: false`.
|
|
438
|
+
*/
|
|
439
|
+
relaxedDurability?: boolean;
|
|
402
440
|
resetSubscriptionKeys?: string[];
|
|
403
441
|
prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
404
442
|
prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
|
|
@@ -450,15 +488,17 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
450
488
|
* - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
|
|
451
489
|
* resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
|
|
452
490
|
* remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
|
|
453
|
-
* - **
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
491
|
+
* - **Comes online iff the recovered journal is clean (ADR-0046).** If journal recovery found NOTHING to
|
|
492
|
+
* quarantine — an empty recovered journal, the guaranteed-clean server-built bootstrap-artifact case — the
|
|
493
|
+
* restore boots ONLINE, honouring {@link syncEnabled}/{@link autoSync} exactly as a normal boot (streams,
|
|
494
|
+
* flush, convergence). If recovered mutations were quarantined, the boot stays OFFLINE (no shape streams,
|
|
495
|
+
* no read fetch, no flush): the app inspects {@link SyncClient.diagnostics}, releases/discards the
|
|
496
|
+
* quarantined rows, then a subsequent NORMAL boot of the (now-persisted) store brings sync online.
|
|
497
|
+
* `loadDataDir` happens exactly once, on this restore boot. An explicit `syncEnabled: false` keeps it offline.
|
|
458
498
|
* - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
|
|
459
499
|
* `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
|
|
460
500
|
* ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
|
|
461
|
-
* (`discardQuarantined`) them explicitly.
|
|
501
|
+
* (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
|
|
462
502
|
*
|
|
463
503
|
* Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
|
|
464
504
|
* creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
|
|
@@ -843,6 +883,23 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
843
883
|
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
844
884
|
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
|
|
845
885
|
rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
886
|
+
/**
|
|
887
|
+
* @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
|
|
888
|
+
* ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
|
|
889
|
+
* `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
|
|
890
|
+
* `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
|
|
891
|
+
* client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
|
|
892
|
+
* worker-side. Accepts the full PGlite {@link QueryOptions} (the worker re-applies drizzle's identity
|
|
893
|
+
* parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
|
|
894
|
+
* read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
|
|
895
|
+
* from the generated API docs (typedoc excludeInternal).
|
|
896
|
+
*/
|
|
897
|
+
guardedRawQuery: (
|
|
898
|
+
sql: string,
|
|
899
|
+
params?: unknown[],
|
|
900
|
+
options?: QueryOptions,
|
|
901
|
+
use?: readonly SyncTableName<TRegistry>[],
|
|
902
|
+
) => Promise<Results>;
|
|
846
903
|
/**
|
|
847
904
|
* Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
|
|
848
905
|
* Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
|
|
@@ -1126,18 +1183,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1126
1183
|
);
|
|
1127
1184
|
}
|
|
1128
1185
|
|
|
1129
|
-
// Restore
|
|
1130
|
-
//
|
|
1131
|
-
//
|
|
1132
|
-
//
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1140
|
-
// ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
|
|
1186
|
+
// Restore boots start offline and DEFER the sync-enable decision until AFTER journal recovery (ADR-0046,
|
|
1187
|
+
// refining ADR-0035 decision 6): a restore comes online iff recovery found NOTHING to quarantine — an empty
|
|
1188
|
+
// recovered journal, the guaranteed-clean server-built bootstrap-artifact case — and stays offline (today's
|
|
1189
|
+
// behaviour) when recovered mutations were quarantined, because a replayed write is unsafe without a dedupe
|
|
1190
|
+
// ledger. The decision is taken in the restore recovery block below (it needs the quarantine count) and
|
|
1191
|
+
// honours an explicit `syncEnabled: false`. A normal boot resolves its final value here, up front.
|
|
1192
|
+
let syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1193
|
+
// ADR-0032 S4 overlap flag. A restore starts `syncEnabled: false` here, so it never takes the overlap
|
|
1194
|
+
// prefetch path (a restore also never presents a fresh spare store); the flag stays `false` for the whole
|
|
1195
|
+
// boot even when the restore later comes online (which uses the sequential sync-start path, not overlap).
|
|
1141
1196
|
const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
|
|
1142
1197
|
// How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
|
|
1143
1198
|
// backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
|
|
@@ -1178,6 +1233,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1178
1233
|
const createClientOptions: CreateClientPGliteOptions = {
|
|
1179
1234
|
...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
|
|
1180
1235
|
...(backendOverride ? { backendOverride } : {}),
|
|
1236
|
+
// Relaxed durability (ADR-0047): forward the caller's explicit choice; `createClientPGlite` resolves the
|
|
1237
|
+
// `?? true` default. Passed only when set, so the default lives at exactly one point.
|
|
1238
|
+
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
1181
1239
|
// Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
|
|
1182
1240
|
// mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
|
|
1183
1241
|
// create — never the adopt paths, which leave `restoreFrom` unread.
|
|
@@ -1345,7 +1403,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1345
1403
|
// letting the read cache silently diverge from the server. Sticky (see below).
|
|
1346
1404
|
status.phase = "degraded";
|
|
1347
1405
|
degradedReason = "commit";
|
|
1348
|
-
|
|
1406
|
+
// The cause chain, not just the wrapper: a drizzle "Failed query" message hides the actual
|
|
1407
|
+
// database error (SQLSTATE, detail) on `.cause`.
|
|
1408
|
+
status.lastError = describeErrorChain(error);
|
|
1349
1409
|
options.onStatusChange?.(status);
|
|
1350
1410
|
options.onSyncError?.(error);
|
|
1351
1411
|
},
|
|
@@ -1362,7 +1422,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1362
1422
|
// way then another reports the current cause (observability).
|
|
1363
1423
|
status.phase = "degraded";
|
|
1364
1424
|
degradedReason = "stream";
|
|
1365
|
-
status.lastError = error
|
|
1425
|
+
status.lastError = describeErrorChain(error);
|
|
1366
1426
|
options.onStatusChange?.(status);
|
|
1367
1427
|
},
|
|
1368
1428
|
// Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
|
|
@@ -1521,6 +1581,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1521
1581
|
// dropping the quarantined writes — unchanged from the pre-ADR-0041 recover→quarantine→reconcile order.
|
|
1522
1582
|
// `localReadReady` and `writeReady` therefore coincide on a restore boot (both resolved after this point).
|
|
1523
1583
|
await runBootRecoveryStage();
|
|
1584
|
+
|
|
1585
|
+
// ADR-0046: with recovery + quarantine complete, decide whether this restore comes online. The restore
|
|
1586
|
+
// quarantine pass parked every recovered non-terminal write (pending/sending/failed) as `quarantined`, so a
|
|
1587
|
+
// zero quarantined count means the backup's journal was CLEAN — the server-built bootstrap-artifact case —
|
|
1588
|
+
// and sync may start exactly as a normal boot would. A non-zero count keeps the boot offline (the protective
|
|
1589
|
+
// ADR-0035 rule, now applied only where it protects) until the app releases the rows; a subsequent normal
|
|
1590
|
+
// boot then brings sync online. An explicit `syncEnabled: false` is always honoured (stays offline).
|
|
1591
|
+
const recoveredQuarantined = (await mutationRuntime.readMutationStats()).quarantinedCount;
|
|
1592
|
+
if (recoveredQuarantined === 0 && options.syncEnabled !== false) {
|
|
1593
|
+
syncEnabled = options.syncEnabled ?? true;
|
|
1594
|
+
syncDebug("boot restore comes online — recovered journal was clean (nothing to quarantine)");
|
|
1595
|
+
} else if (recoveredQuarantined > 0) {
|
|
1596
|
+
syncDebug(
|
|
1597
|
+
"boot restore stays offline — recovered journal mutations were quarantined; release/discard them and a subsequent normal boot brings sync online",
|
|
1598
|
+
{ quarantinedCount: recoveredQuarantined, syncEnabledOption: options.syncEnabled ?? null },
|
|
1599
|
+
);
|
|
1600
|
+
}
|
|
1524
1601
|
await runReconcileStage();
|
|
1525
1602
|
} else {
|
|
1526
1603
|
// Normal boot (ADR-0041): reconcile is part of the local-read core and runs BEFORE recovery (which moves
|
|
@@ -1675,11 +1752,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1675
1752
|
resolveSyncWired();
|
|
1676
1753
|
};
|
|
1677
1754
|
|
|
1678
|
-
//
|
|
1679
|
-
//
|
|
1680
|
-
//
|
|
1681
|
-
// online
|
|
1682
|
-
|
|
1755
|
+
// Convergence driver (ADR-0035 decision 6 / ADR-0046): a restore boot that STAYS offline (recovered journal
|
|
1756
|
+
// quarantined) never stands up the driver, so an `autoSync` trigger drives NO flush/reconcile passes — the
|
|
1757
|
+
// quarantined rows must stay put until the app releases them and a normal boot goes online. A restore that
|
|
1758
|
+
// came online (clean recovered journal) is treated exactly like a normal online boot and DOES get the driver.
|
|
1759
|
+
// On every non-restore boot the gate is unchanged (`!restoreBoot` is true regardless of `syncEnabled`).
|
|
1760
|
+
if (options.autoSync && (!restoreBoot || syncEnabled)) {
|
|
1683
1761
|
convergenceDriver = createConvergenceDriver({
|
|
1684
1762
|
client: {
|
|
1685
1763
|
flush: () => mutationRuntime.flush(),
|
|
@@ -2069,19 +2147,41 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2069
2147
|
return { lazyTables };
|
|
2070
2148
|
};
|
|
2071
2149
|
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
): Promise<
|
|
2150
|
+
// The single gate+guard core shared by BOTH one-shot read entry points (the in-process drizzle-builder path
|
|
2151
|
+
// below and the worker-reachable `guardedRawQuery`), so the read gate and lazy-group guard can never drift
|
|
2152
|
+
// between modes. Given the query's compiled SQL (∪ `use`): read gate first, then the lazy-group guard.
|
|
2153
|
+
const gateAndGuardRead = async (sql: string, use?: readonly SyncTableName<TRegistry>[]): Promise<void> => {
|
|
2076
2154
|
// Read gate (ADR-0041): a query must not run against a store whose local-read core has not finished. On
|
|
2077
2155
|
// the in-process client this is a settled-promise await (the client is handed out at `localReadReady`),
|
|
2078
2156
|
// but it is cheap and keeps the read path safe if a caller retained a query builder across the boundary.
|
|
2079
2157
|
await localReadReady;
|
|
2158
|
+
// Lazy-group guard (ADR-0021): scan the compiled SQL (∪ `use`) for lazy relations it reads and activate +
|
|
2159
|
+
// await them before the query runs, so a lazy relation is never read empty/stale.
|
|
2160
|
+
await prepareQuery({ sql, ...(use ? { use } : {}) });
|
|
2161
|
+
};
|
|
2162
|
+
|
|
2163
|
+
const runGuardedQuery = async <TRows extends readonly unknown[]>(
|
|
2164
|
+
build: GuardedQueryFn<TRegistry, TRows>,
|
|
2165
|
+
use?: readonly SyncTableName<TRegistry>[],
|
|
2166
|
+
): Promise<TRows> => {
|
|
2167
|
+
// Building the drizzle query is pure construction (no DB I/O — it only compiles to SQL), so compile first,
|
|
2168
|
+
// then run the shared gate+guard on that SQL, then hand back the still-unexecuted builder (its `await`
|
|
2169
|
+
// executes via the local drizzle exactly as before — return shape unchanged).
|
|
2080
2170
|
const builder = build(client);
|
|
2081
|
-
await
|
|
2171
|
+
await gateAndGuardRead(builder.toSQL().sql, use);
|
|
2082
2172
|
return builder;
|
|
2083
2173
|
};
|
|
2084
2174
|
|
|
2175
|
+
// The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
|
|
2176
|
+
// `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
|
|
2177
|
+
// drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
|
|
2178
|
+
// the attach client's Drizzle-over-bridge routes reads here. Returns the full PGlite `Results` so drizzle's
|
|
2179
|
+
// own result mapping runs on the tab.
|
|
2180
|
+
const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
|
|
2181
|
+
await gateAndGuardRead(sql, use);
|
|
2182
|
+
return pglite.query(sql, params as unknown[] | undefined, options);
|
|
2183
|
+
};
|
|
2184
|
+
|
|
2085
2185
|
// The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
|
|
2086
2186
|
// client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
|
|
2087
2187
|
// bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
|
|
@@ -2246,6 +2346,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2246
2346
|
// overlay involvement. The worker facade runs the identical call inside the worker's own client.
|
|
2247
2347
|
rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
|
|
2248
2348
|
rawExec: (sql, options) => pglite.exec(sql, options),
|
|
2349
|
+
// @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
|
|
2350
|
+
guardedRawQuery,
|
|
2249
2351
|
query: (build) => runGuardedQuery(build),
|
|
2250
2352
|
queryRow: async (build) => {
|
|
2251
2353
|
const rows = await runGuardedQuery(build);
|
|
@@ -2451,7 +2553,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2451
2553
|
// NIT 8: surface a signal beyond the stage rejections — move the runtime to `degraded` so a consumer
|
|
2452
2554
|
// watching `status`/`onStatusChange` sees the boot failed, not just an awaiter of a stage promise.
|
|
2453
2555
|
status.phase = "degraded";
|
|
2454
|
-
status.lastError =
|
|
2556
|
+
status.lastError = describeErrorChain(error);
|
|
2455
2557
|
options.onStatusChange?.(status);
|
|
2456
2558
|
rejectWriteReady(error);
|
|
2457
2559
|
rejectReady(error);
|
|
@@ -2519,22 +2621,54 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
|
2519
2621
|
}
|
|
2520
2622
|
|
|
2521
2623
|
/**
|
|
2522
|
-
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a
|
|
2523
|
-
* plus the registry views.
|
|
2524
|
-
*
|
|
2525
|
-
*
|
|
2526
|
-
*
|
|
2624
|
+
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2/decision 4): a Drizzle instance
|
|
2625
|
+
* plus the registry views. `createSyncClient`'s SAME builders, so a query built on either client compiles
|
|
2626
|
+
* identically. The `client` argument is the executor Drizzle runs against:
|
|
2627
|
+
* - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
|
|
2628
|
+
* and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
|
|
2629
|
+
* - Pass a `ClientPGlite`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
|
|
2630
|
+
* that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
|
|
2631
|
+
* queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
|
|
2527
2632
|
*/
|
|
2528
2633
|
export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
2529
2634
|
registry: TRegistry,
|
|
2530
|
-
|
|
2531
|
-
|
|
2635
|
+
client: ClientPGlite = {} as ClientPGlite,
|
|
2636
|
+
): {
|
|
2637
|
+
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
2638
|
+
views: RegistryViews<TRegistry>;
|
|
2639
|
+
/**
|
|
2640
|
+
* A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
|
|
2641
|
+
* the schema + relations computed ONCE here so a caller can cheaply build additional per-executor databases
|
|
2642
|
+
* without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
|
|
2643
|
+
* bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
|
|
2644
|
+
*/
|
|
2645
|
+
drizzleFor: (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
2646
|
+
} {
|
|
2647
|
+
const drizzleFor = buildRegistryDrizzleFactory(registry);
|
|
2532
2648
|
return {
|
|
2533
|
-
drizzle:
|
|
2649
|
+
drizzle: drizzleFor(client),
|
|
2534
2650
|
views: buildViews(registry),
|
|
2651
|
+
drizzleFor,
|
|
2535
2652
|
};
|
|
2536
2653
|
}
|
|
2537
2654
|
|
|
2655
|
+
/**
|
|
2656
|
+
* Compute a registry's Drizzle schema + relations ONCE and return a `(client) => db` factory over them
|
|
2657
|
+
* (ADR-0032 decision 4). Splitting this out of {@link buildRegistryReadHandles} lets `attachSyncClient` build
|
|
2658
|
+
* one base bridge database plus a fresh per-read database (each over its own executor) without paying the
|
|
2659
|
+
* schema/relations construction on every read — only the `client` binding differs between them.
|
|
2660
|
+
*/
|
|
2661
|
+
function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
|
|
2662
|
+
registry: TRegistry,
|
|
2663
|
+
): (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>> {
|
|
2664
|
+
const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
|
|
2665
|
+
const createDatabase = drizzle as unknown as (config: {
|
|
2666
|
+
client: ClientPGlite;
|
|
2667
|
+
relations: RegistryRelations<TRegistry>;
|
|
2668
|
+
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
2669
|
+
return (client) => createDatabase({ client, relations });
|
|
2670
|
+
}
|
|
2671
|
+
|
|
2538
2672
|
function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
|
|
2539
2673
|
registry: TRegistry,
|
|
2540
2674
|
electricUrl: string,
|
package/src/local-tables.ts
CHANGED
|
@@ -492,6 +492,12 @@ export interface ApplyTarget {
|
|
|
492
492
|
propertyKeyByName: Record<string, string>;
|
|
493
493
|
/** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
|
|
494
494
|
primaryKey: string[];
|
|
495
|
+
/**
|
|
496
|
+
* CDC insert-apply policy (ADR-0045), from the entry. `"insert"` (default) applies a CDC insert as a
|
|
497
|
+
* plain INSERT so a genuine PK collision surfaces; `"upsert"` applies it idempotently (ON CONFLICT DO
|
|
498
|
+
* UPDATE) because this table legitimately receives locally-derived provisional rows.
|
|
499
|
+
*/
|
|
500
|
+
applyMode: "insert" | "upsert";
|
|
495
501
|
/** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
|
|
496
502
|
columnTypes: SyncColumnType[];
|
|
497
503
|
/**
|
|
@@ -525,6 +531,7 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
|
|
|
525
531
|
columnByName,
|
|
526
532
|
propertyKeyByName,
|
|
527
533
|
primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
|
|
534
|
+
applyMode: entry.applyMode,
|
|
528
535
|
columnTypes: deriveSyncColumnTypes(entry),
|
|
529
536
|
insertRenderCache: new Map(),
|
|
530
537
|
};
|