@pgxsinkit/client 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +10 -3
- package/dist/boot-report.d.ts +6 -6
- package/dist/circuits/envelope-to-change.d.ts +9 -5
- package/dist/circuits/envelope-to-change.d.ts.map +1 -1
- package/dist/circuits/group-sync.d.ts +2 -2
- package/dist/circuits/group-sync.d.ts.map +1 -1
- package/dist/circuits/stream-source.d.ts +6 -0
- package/dist/circuits/stream-source.d.ts.map +1 -1
- package/dist/circuits/sync-engine.d.ts +2 -2
- package/dist/circuits/sync-engine.d.ts.map +1 -1
- package/dist/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +191 -95
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +989 -432
- package/dist/index.js.map +39 -36
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +58 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +5 -5
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +82 -6
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +5 -5
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +24 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +35 -18
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -8
- package/skills/core/SKILL.md +80 -15
- package/skills/operating/SKILL.md +129 -129
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +9 -9
- package/src/circuits/envelope-to-change.ts +121 -12
- package/src/circuits/group-sync.ts +2 -2
- package/src/circuits/stream-source.ts +35 -9
- package/src/circuits/sync-engine.ts +6 -4
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +21 -26
- package/src/export-store.ts +17 -17
- package/src/index.ts +520 -284
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +70 -6
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +124 -18
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +56 -40
- package/src/sync/apply.ts +32 -46
- package/src/sync/copy.ts +108 -13
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/metadata-tables.ts +1 -1
- package/src/sync/subscription-state.ts +7 -7
- package/src/testing.ts +3 -3
- package/src/worker/attach-sync-client.ts +142 -56
- package/src/worker/define-sync-worker.ts +204 -75
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +10 -10
- package/src/worker/protocol.ts +38 -7
package/src/index.ts
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import { PGlite, type PGliteOptions, type QueryOptions, type Results } from "@electric-sql/pglite";
|
|
2
|
-
import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
|
|
3
|
-
import type { PgliteDatabase } from "drizzle-orm/pglite";
|
|
4
|
-
import { drizzle } from "drizzle-orm/pglite";
|
|
5
1
|
import { defineRelations } from "drizzle-orm/relations";
|
|
6
2
|
|
|
7
3
|
import type {
|
|
@@ -18,7 +14,9 @@ import type {
|
|
|
18
14
|
SyncTableName,
|
|
19
15
|
SyncTableRegistry,
|
|
20
16
|
SyncTableUpdateInput,
|
|
17
|
+
StorageBuild,
|
|
21
18
|
StorageDurability,
|
|
19
|
+
StoreBuildCheckSite,
|
|
22
20
|
WriteMode,
|
|
23
21
|
} from "@pgxsinkit/contracts";
|
|
24
22
|
import {
|
|
@@ -27,10 +25,21 @@ import {
|
|
|
27
25
|
isClaimsDependentRowFilter,
|
|
28
26
|
resolveStorageDeclaration,
|
|
29
27
|
} from "@pgxsinkit/contracts";
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
28
|
+
import {
|
|
29
|
+
createPgwasm,
|
|
30
|
+
type PgwasmOptions,
|
|
31
|
+
type PostgresBuild,
|
|
32
|
+
type QueryOptions,
|
|
33
|
+
type Results,
|
|
34
|
+
} from "@pgxsinkit/pgwasm";
|
|
35
|
+
import { cBuild } from "@pgxsinkit/pgwasm-c";
|
|
36
|
+
import type { PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
|
|
37
|
+
import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
38
|
+
import { live, type PgwasmWithLive } from "@pgxsinkit/pgwasm/live";
|
|
39
|
+
// Type-only import (erased at runtime): the OPFS store factory's option/return types for the `opfs://`
|
|
40
|
+
// branch. The `/opfs` VALUES (`createOpfsPgwasm`, `strictSync`) are loaded lazily via dynamic `import()`, so the
|
|
41
|
+
// store's code stays off every bundle and boot that never opens an OPFS store.
|
|
42
|
+
import type { CreateOpfsPgwasmOptions, OpfsPgwasm } from "@pgxsinkit/pgwasm/opfs";
|
|
34
43
|
|
|
35
44
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
36
45
|
import { startCircuitsSync, type CircuitsGroupSyncResult } from "./circuits/group-sync";
|
|
@@ -97,6 +106,7 @@ import {
|
|
|
97
106
|
type ResolvedStorageBackend,
|
|
98
107
|
type StoreBootResolution,
|
|
99
108
|
} from "./store-boot";
|
|
109
|
+
import { assertStoreBuild, isStoreBuildRefusal } from "./store-build";
|
|
100
110
|
import { runCommitmentBarrier } from "./store-lifecycle";
|
|
101
111
|
import {
|
|
102
112
|
META_STORE_UNAVAILABLE,
|
|
@@ -105,8 +115,9 @@ import {
|
|
|
105
115
|
type StoreMetaDeps,
|
|
106
116
|
writeStoreMetaRecord,
|
|
107
117
|
} from "./store-meta";
|
|
118
|
+
import { acquireStoreOwnership } from "./store-ownership-lock";
|
|
108
119
|
import {
|
|
109
|
-
|
|
120
|
+
classifyNonPersistentStorage,
|
|
110
121
|
NonPersistentStoreError,
|
|
111
122
|
normaliseStorePathInput,
|
|
112
123
|
readTestStoreMarker,
|
|
@@ -220,6 +231,7 @@ export {
|
|
|
220
231
|
type ProvisionStalledWire,
|
|
221
232
|
} from "./worker/engine-control";
|
|
222
233
|
export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
234
|
+
export { STORE_OWNERSHIP_WAIT_MS, StoreOwnershipWaitError } from "./store-ownership-lock";
|
|
223
235
|
export {
|
|
224
236
|
COMMITTED_STORE_UNREACHABLE_CODE,
|
|
225
237
|
CommittedStoreUnreachableError,
|
|
@@ -230,6 +242,15 @@ export {
|
|
|
230
242
|
type ResolveStoreBootOptions,
|
|
231
243
|
type StoreBootResolution,
|
|
232
244
|
} from "./store-boot";
|
|
245
|
+
export {
|
|
246
|
+
// The DECLARED store engine (ADR-0050 addendum): loading a `storage.engine.module` and taking its
|
|
247
|
+
// `createStore`. The worker uses it for every declared mint; an app whose in-process fallback must
|
|
248
|
+
// honour the same declaration uses it there.
|
|
249
|
+
createStoreEngineResolver,
|
|
250
|
+
loadStoreEngineFactory,
|
|
251
|
+
type StoreEngineFactory,
|
|
252
|
+
type StoreEngineModuleLoader,
|
|
253
|
+
} from "./store-engine";
|
|
233
254
|
export {
|
|
234
255
|
InvalidStorePathError,
|
|
235
256
|
NonPersistentStoreError,
|
|
@@ -306,6 +327,19 @@ export {
|
|
|
306
327
|
// surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
|
|
307
328
|
export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
|
|
308
329
|
|
|
330
|
+
// The COPY TEXT bulk-load seam (ADR-0061). PUBLIC because a consumer's LOCAL-ONLY table — one pgxsinkit
|
|
331
|
+
// does not manage, so `mutate`/`tables.*` do not apply to it — has no other way to load 10k rows without
|
|
332
|
+
// paying an INSERT per row: `buildCopyFromBlobStatement` renders the tier-③ `COPY … FROM '/dev/blob'`
|
|
333
|
+
// statement from the REAL Drizzle table object and serializes the rows with the SAME serializer the sync
|
|
334
|
+
// applier uses, and the resulting {@link RawStatement} goes straight to `rawTransaction`/`rawQuery`.
|
|
335
|
+
// `generateCopyData`/`serializeCopyValue` are exported under it for a caller that renders its own COPY.
|
|
336
|
+
export {
|
|
337
|
+
buildCopyFromBlobStatement,
|
|
338
|
+
type CopyFromBlobStatementOptions,
|
|
339
|
+
generateCopyData,
|
|
340
|
+
serializeCopyValue,
|
|
341
|
+
} from "./sync/copy";
|
|
342
|
+
|
|
309
343
|
// The Circuits-native read transport (ADR-0055 decision 10). Reads terminate on durable-streams
|
|
310
344
|
// through the edge; everything above the transport stays ours.
|
|
311
345
|
export { createTokenRecovery, readShapeStream, STREAM_START } from "./circuits/stream-source";
|
|
@@ -391,40 +425,39 @@ export class ClientDisposedError extends Error {
|
|
|
391
425
|
}
|
|
392
426
|
}
|
|
393
427
|
|
|
394
|
-
// The store carries
|
|
428
|
+
// The store carries pgwasm's own `live` extension and nothing else. The pgxsinkit sync runtime is not an
|
|
395
429
|
// extension at all (ADR-0032 S1): `createSyncClient` starts it BESIDE the store (`startCircuitsSync`)
|
|
396
|
-
// rather than attaching a namespace to the instance, so a store's type is exactly
|
|
430
|
+
// rather than attaching a namespace to the instance, so a store's type is exactly pgwasm + `live`
|
|
397
431
|
// whether or not sync ever runs on it.
|
|
398
|
-
export type
|
|
432
|
+
export type PgwasmClient = PgwasmWithLive;
|
|
399
433
|
|
|
400
|
-
/**
|
|
401
|
-
|
|
402
|
-
* {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
|
|
403
|
-
* compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
|
|
404
|
-
* asset load — see the field's JSDoc for the accelerator geometry.
|
|
405
|
-
*/
|
|
406
|
-
export interface PgliteBootAssets {
|
|
407
|
-
pgliteWasmModule?: WebAssembly.Module;
|
|
408
|
-
initdbWasmModule?: WebAssembly.Module;
|
|
409
|
-
fsBundle?: Blob;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
/** Options for {@link createClientPGlite}. */
|
|
413
|
-
export interface CreateClientPGliteOptions {
|
|
434
|
+
/** Options for {@link createPgwasmClient}. */
|
|
435
|
+
export interface CreatePgwasmClientOptions {
|
|
414
436
|
/**
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
* asset load
|
|
437
|
+
* The Postgres build the store runs on (see {@link CreateSyncClientOptions.build}); defaults to `cBuild`.
|
|
438
|
+
* Pass `createCBuild({ assets })` to hand in pre-warmed WASM modules and filesystem bundle: a rejected warm
|
|
439
|
+
* falls back to the build's own asset load, so it never fails the create.
|
|
418
440
|
*/
|
|
419
|
-
|
|
441
|
+
build?: PostgresBuild;
|
|
442
|
+
/**
|
|
443
|
+
* @internal Toolkit-internal declared-build carrier (ADR-0063), NOT a public per-open knob: the registry's
|
|
444
|
+
* resolved `storage.build`, threaded by the sites that resolve a declaration (`createSyncClient`'s mints,
|
|
445
|
+
* the worker's provision and spare mints). When present, the supplied {@link build} must be that build
|
|
446
|
+
* ({@link StorageBuildMismatchError}, thrown before the store is touched); absent, no declaration is checked.
|
|
447
|
+
*/
|
|
448
|
+
declaredBuild?: StorageBuild;
|
|
449
|
+
/**
|
|
450
|
+
* @internal The site the {@link declaredBuild} check reports; defaults to `"createPgwasmClient"`.
|
|
451
|
+
*/
|
|
452
|
+
buildCheckSite?: StoreBuildCheckSite;
|
|
420
453
|
/**
|
|
421
454
|
* @internal Toolkit-internal durability carrier (ADR-0047), NOT a public per-open knob. Durability is
|
|
422
455
|
* registry-declared: {@link createSyncClient} resolves `storage.durability ?? "relaxed"` off its registry
|
|
423
456
|
* and threads the resolved mode in here — the ONE resolution point — for every mint it funnels through this
|
|
424
457
|
* factory (its own boot, the worker provision/spare mint, the pre-expose idb drain read). Defaults to
|
|
425
|
-
* `"relaxed"` when absent and is stamped onto the `boot
|
|
458
|
+
* `"relaxed"` when absent and is stamped onto the `boot pgwasm.create` rail (ADR-0047 D3). On idb, relaxed
|
|
426
459
|
* returns before the whole-datadir snapshot flush and schedules it asynchronously; strict keeps that
|
|
427
|
-
* synchronous snapshot (~100–200ms per statement). On OPFS-repacked the package factory keeps
|
|
460
|
+
* synchronous snapshot (~100–200ms per statement). On OPFS-repacked the package factory keeps pgwasm on its
|
|
428
461
|
* awaited host path: relaxed routine sync asserts health without an ordinary physical flush, while strict
|
|
429
462
|
* flushes arena data before metadata. Initialization, activation, and open-state close retain strict
|
|
430
463
|
* ordering in both OPFS modes.
|
|
@@ -438,10 +471,10 @@ export interface CreateClientPGliteOptions {
|
|
|
438
471
|
backendOverride?: "memory";
|
|
439
472
|
/**
|
|
440
473
|
* A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
|
|
441
|
-
* produced by {@link SyncClient.exportStore}. Passed straight to
|
|
474
|
+
* produced by {@link SyncClient.exportStore}. Passed straight to pgwasm's `loadDataDir`, so the created
|
|
442
475
|
* store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
|
|
443
476
|
* has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
|
|
444
|
-
* freshness check of its own. A corrupt/foreign tarball surfaces as a
|
|
477
|
+
* freshness check of its own. A corrupt/foreign tarball surfaces as a pgwasm boot failure here.
|
|
445
478
|
*/
|
|
446
479
|
restoreFrom?: File | Blob;
|
|
447
480
|
/**
|
|
@@ -454,12 +487,14 @@ export interface CreateClientPGliteOptions {
|
|
|
454
487
|
/**
|
|
455
488
|
* @internal ADR-0049 step 10a: the opfs-repacked factory + store-directory seam, injectable so Bun unit
|
|
456
489
|
* tests exercise the `opfs://` branch WITHOUT loading real WASM/OPFS. In production both default to the real
|
|
457
|
-
* implementations (`
|
|
490
|
+
* implementations (`createOpfsPgwasm` via a lazy `import()`, and the OPFS effects' store directory
|
|
458
491
|
* handle). Never consumer-facing.
|
|
459
492
|
*/
|
|
460
|
-
|
|
461
|
-
/** The
|
|
462
|
-
|
|
493
|
+
opfsFactories?: {
|
|
494
|
+
/** The OPFS store factory; defaults to a lazily-imported `createOpfsPgwasm` from `@pgxsinkit/pgwasm/opfs`. */
|
|
495
|
+
createOpfsPgwasm?: (
|
|
496
|
+
options: CreateOpfsPgwasmOptions<{ live: typeof live }>,
|
|
497
|
+
) => Promise<OpfsPgwasm<{ live: typeof live }>>;
|
|
463
498
|
/** The create-if-absent store directory handle for the factory; defaults to the real OPFS effects. */
|
|
464
499
|
getStoreDirectoryHandle?: () => Promise<unknown>;
|
|
465
500
|
/** Backoff between bounded open retries (ms); defaults to a small real delay. Tests pass `0`. */
|
|
@@ -500,29 +535,45 @@ const CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is faili
|
|
|
500
535
|
*/
|
|
501
536
|
const STREAM_LOST = "read stream lost; re-subscribing";
|
|
502
537
|
/**
|
|
503
|
-
*
|
|
504
|
-
*
|
|
505
|
-
*
|
|
506
|
-
*
|
|
507
|
-
* `precreatedPglite` (the provision-then-attach path). This brand lets the guard recognise it as PROVABLY
|
|
508
|
-
* persistent. `Symbol.for` so the brand survives even if the instance is inspected via a different module copy.
|
|
538
|
+
* Is this instance on an OPFS-repacked store? The store reports itself through `pg.storage` (the filesystem's
|
|
539
|
+
* own description, `{ kind: "vfs", name: "opfs-repacked", persistent: true }`), so an ADOPTED instance is
|
|
540
|
+
* recognised without any brand: it is the one provenance that carries the OPFS commitment machinery, which a
|
|
541
|
+
* BYO idb/file/memory instance does not.
|
|
509
542
|
*/
|
|
510
|
-
|
|
543
|
+
function isOpfsRepackedStore(instance: PgwasmClient): boolean {
|
|
544
|
+
const storage = instance.storage;
|
|
545
|
+
return storage.kind === "vfs" && storage.name === OPFS_REPACKED_STORAGE_NAME;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** The name the OPFS-repacked filesystem reports in `pg.storage` (`OpfsRepackedFS`'s `description`). */
|
|
549
|
+
const OPFS_REPACKED_STORAGE_NAME = "opfs-repacked";
|
|
511
550
|
|
|
512
551
|
/**
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
552
|
+
* Keep the store's ownership lock until the database has closed (its build releases the OPFS handles in
|
|
553
|
+
* `closeFs` on every close, a failed one included), then release it. `Symbol.asyncDispose` routes through
|
|
554
|
+
* `close`, so both exits are covered; a second close is idempotent here as in pgwasm.
|
|
516
555
|
*/
|
|
517
|
-
function
|
|
518
|
-
return
|
|
556
|
+
function holdOwnershipUntilClosed(instance: PgwasmClient, release: () => void): PgwasmClient {
|
|
557
|
+
// An injected test factory may return a close-less stand-in: nothing can ever close it, so the lock stays
|
|
558
|
+
// held for the context's life (its owner never lets go), exactly the semantics of a live store.
|
|
559
|
+
if (typeof instance.close !== "function") return instance;
|
|
560
|
+
const close = instance.close.bind(instance);
|
|
561
|
+
instance.close = async () => {
|
|
562
|
+
try {
|
|
563
|
+
await close();
|
|
564
|
+
} finally {
|
|
565
|
+
release();
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
return instance;
|
|
519
569
|
}
|
|
520
570
|
|
|
521
571
|
/**
|
|
522
|
-
* Open the opfs-repacked factory with bounded retries
|
|
572
|
+
* Open the opfs-repacked factory with bounded retries and a small linear backoff for transient failures,
|
|
523
573
|
* then propagate the last error — a committed store's final failure is HARD, and an uncommitted candidate's
|
|
524
|
-
* likewise propagates (the caller never exposes an unopened store).
|
|
525
|
-
*
|
|
574
|
+
* likewise propagates (the caller never exposes an unopened store). A typed build refusal (ADR-0063: the
|
|
575
|
+
* directory or backup is another build or data format, or its marker is unreadable) is not transient, so it
|
|
576
|
+
* propagates at once, never retried.
|
|
526
577
|
*/
|
|
527
578
|
async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: number): Promise<T> {
|
|
528
579
|
let lastError: unknown;
|
|
@@ -530,6 +581,7 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
|
|
|
530
581
|
try {
|
|
531
582
|
return await open();
|
|
532
583
|
} catch (error) {
|
|
584
|
+
if (isStoreBuildRefusal(error)) throw error;
|
|
533
585
|
lastError = error;
|
|
534
586
|
if (attempt < OPFS_OPEN_ATTEMPTS && backoffMs > 0) {
|
|
535
587
|
await new Promise<void>((resolve) => setTimeout(resolve, backoffMs * attempt));
|
|
@@ -540,47 +592,53 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
|
|
|
540
592
|
}
|
|
541
593
|
|
|
542
594
|
/**
|
|
543
|
-
* Create the raw local
|
|
595
|
+
* Create the raw local pgwasm store the sync client runs on — the SAME `pgwasm.create` call
|
|
544
596
|
* {@link createSyncClient} makes internally (the `live` extension, pre-warmed boot-asset
|
|
545
|
-
* consumption, and the `boot
|
|
597
|
+
* consumption, and the `boot pgwasm.create` rail stamp), extracted so exactly one implementation exists
|
|
546
598
|
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
547
|
-
* instance to {@link CreateSyncClientOptions.
|
|
599
|
+
* instance to {@link CreateSyncClientOptions.precreatedPgwasm}: the client then owns schema exec, prepare
|
|
548
600
|
* hooks, journal recovery, and registry reconciliation, exactly as its own `storePath` path does.
|
|
549
601
|
*
|
|
550
602
|
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED from the engine home
|
|
551
603
|
* (capability-selected opfs-repacked with IndexedDB fallback in a browser, or the filesystem on Bun/Node);
|
|
552
604
|
* a scheme-bearing path throws {@link InvalidStorePathError}.
|
|
553
|
-
* Also accepts the testing helper's output (`
|
|
605
|
+
* Also accepts the testing helper's output (`createPgwasmClient(memoryStoreForTests("x"))`) so a test can
|
|
554
606
|
* mint a memory store without naming a backend.
|
|
555
607
|
*
|
|
556
608
|
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
557
609
|
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
558
610
|
* initdb (+ persistent-store open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
559
611
|
*
|
|
560
|
-
* `
|
|
561
|
-
*
|
|
612
|
+
* `build` is the Postgres build (see {@link CreateSyncClientOptions.build}); a `createCBuild({ assets })` whose
|
|
613
|
+
* warm rejects loads its own assets — never a failure.
|
|
562
614
|
*/
|
|
563
|
-
export async function
|
|
615
|
+
export async function createPgwasmClient(
|
|
564
616
|
store: StorePathInput,
|
|
565
|
-
options?:
|
|
566
|
-
): Promise<
|
|
617
|
+
options?: CreatePgwasmClientOptions,
|
|
618
|
+
): Promise<PgwasmClient> {
|
|
567
619
|
// Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),
|
|
568
|
-
// then derive the concrete
|
|
620
|
+
// then derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
|
|
569
621
|
// empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
|
|
570
622
|
const normalised = normaliseStorePathInput(store);
|
|
571
623
|
const storePath = normalised.storePath;
|
|
572
624
|
const backendOverride = options?.backendOverride ?? normalised.backendOverride;
|
|
625
|
+
// ADR-0063: with a declaration threaded in, the supplied build must be the declared one — checked before
|
|
626
|
+
// anything below touches a store (the denied-home meta gate included). Absent `build` means `cBuild`.
|
|
627
|
+
if (options?.declaredBuild !== undefined) {
|
|
628
|
+
const suppliedBuild = (options.build ?? cBuild).identity;
|
|
629
|
+
assertStoreBuild(options.declaredBuild, suppliedBuild, options.buildCheckSite ?? "createPgwasmClient");
|
|
630
|
+
}
|
|
573
631
|
// An eager precreate is itself a store mint, so it passes the SAME pre-mint meta gate the ordinary
|
|
574
632
|
// createSyncClient path does before a denied browser home opens an IDB store: settle any durable `deleting`
|
|
575
633
|
// authority, retire an unexposed `opfs-candidate`, and REFUSE an `opfs-committed` store outright ({@link
|
|
576
634
|
// CommittedStoreUnreachableError}) — an eager tab-side precreate must never be the thing that mints an empty
|
|
577
635
|
// sibling over the committed store, nor one exposed beneath a record still claiming a candidate.
|
|
578
636
|
// Keeping this at the documented precreate factory protects callers outside defineSyncWorker; the worker
|
|
579
|
-
// provision handler carries the same guard separately because it permits a caller-supplied
|
|
637
|
+
// provision handler carries the same guard separately because it permits a caller-supplied createStore factory.
|
|
580
638
|
if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
|
|
581
639
|
await resolveDeniedBootAuthority(storePath);
|
|
582
640
|
}
|
|
583
|
-
// Derive the concrete
|
|
641
|
+
// Derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
|
|
584
642
|
// Bun/Node → `file://`, the sanctioned test lane → `memory://`. A scheme-bearing/empty storePath throws here.
|
|
585
643
|
// ADR-0049 step 10a: when the caller threads the placement probe's grant (`hasOpfsSyncAccess`), the browser
|
|
586
644
|
// store resolves to `opfs://` and routes to the opfs-repacked factory below. Default (undefined/false) leaves
|
|
@@ -591,90 +649,96 @@ export async function createClientPGlite(
|
|
|
591
649
|
// Stamp the store's scheme on the boot rail (never the full path — it can carry an identity-specific store
|
|
592
650
|
// name): "idb:" / "file:" / "memory:".
|
|
593
651
|
const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
|
|
594
|
-
//
|
|
595
|
-
//
|
|
596
|
-
//
|
|
597
|
-
|
|
598
|
-
const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
|
|
652
|
+
// The build a client-owned store runs on: the caller's (e.g. `createCBuild({ assets })` over a warm started
|
|
653
|
+
// on an earlier screen, where a rejected warm falls back to the build's own lazy asset load and never fails
|
|
654
|
+
// the boot), else the shared `cBuild`.
|
|
655
|
+
const build = options?.build ?? cBuild;
|
|
599
656
|
// Durability (ADR-0047) is registry-declared and resolved by createSyncClient; the resolved mode is threaded
|
|
600
657
|
// in via the internal `durability` carrier. Every store minting path (createSyncClient's own create, the
|
|
601
|
-
// worker's default
|
|
658
|
+
// worker's default createStore factory, spare/prewarm mints) funnels through this function, so the
|
|
602
659
|
// `?? "relaxed"` here is the terminal fallback when no mode was threaded (e.g. an eager caller-owned
|
|
603
|
-
// precreate). Maps to
|
|
660
|
+
// precreate). Maps to pgwasm's `relaxedDurability` boolean (`"strict"` → false). On idb the per-query
|
|
604
661
|
// synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
|
|
605
662
|
const relaxedDurability = (options?.durability ?? "relaxed") !== "strict";
|
|
606
|
-
|
|
607
|
-
//
|
|
608
|
-
//
|
|
609
|
-
|
|
663
|
+
// Wait for everything the build's boot would wait on (a `createCBuild({ assets })` warm still in flight)
|
|
664
|
+
// BEFORE the `boot pgwasm.create` stamp starts, so the stamp measures the create alone, never an unfinished
|
|
665
|
+
// warm. `prepare` never rejects: a failed warm falls back to the build's own lazy asset load.
|
|
666
|
+
await build.prepare?.();
|
|
667
|
+
|
|
668
|
+
// ADR-0049 step 10a — the `opfs://` branch. pgwasm does NOT accept `opfs://` as a dataDir; instead the
|
|
669
|
+
// OPFS store factory owns the store on a dedicated OPFS directory. The factory is loaded LAZILY (a
|
|
670
|
+
// dynamic `import()`) and both it and the store-directory handle are injectable (`opfsFactories`) so a Bun
|
|
610
671
|
// unit test drives this branch with no real WASM/OPFS. Durability maps from the same `relaxedDurability`
|
|
611
672
|
// resolution above (ADR-0047's default logic is untouched): `relaxed` → the factory's `"relaxed"`, else
|
|
612
673
|
// `"strict"`. The open is retried a bounded number of times for transient failures, then propagates.
|
|
613
674
|
if (dataDir.startsWith("opfs://")) {
|
|
614
675
|
const opfsPglite = (await timeAsync(
|
|
615
|
-
"boot
|
|
676
|
+
"boot pgwasm.create",
|
|
616
677
|
async () => {
|
|
617
|
-
const
|
|
618
|
-
options?.
|
|
619
|
-
|
|
620
|
-
// A create that never returns used to leave the rail at `boot pglite.create start` with nothing after
|
|
678
|
+
const createOpfsStore =
|
|
679
|
+
options?.opfsFactories?.createOpfsPgwasm ?? (await import("@pgxsinkit/pgwasm/opfs")).createOpfsPgwasm;
|
|
680
|
+
// A create that never returns used to leave the rail at `boot pgwasm.create start` with nothing after
|
|
621
681
|
// it — indistinguishable from a lost worker. These four phase lines split the create into its long
|
|
622
|
-
// steps (module load, directory handle, handle acquisition,
|
|
623
|
-
syncDebug("boot
|
|
682
|
+
// steps (module load, directory handle, handle acquisition, pgwasm boot), so a stall is attributable.
|
|
683
|
+
syncDebug("boot pgwasm.create phase", { phase: "module-loaded" });
|
|
624
684
|
const getStoreDirectoryHandle =
|
|
625
|
-
options?.
|
|
685
|
+
options?.opfsFactories?.getStoreDirectoryHandle ??
|
|
626
686
|
(() => createOpfsEffects(storePath).getStoreDirectoryHandle());
|
|
627
687
|
const directory = await getStoreDirectoryHandle();
|
|
628
|
-
syncDebug("boot
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
688
|
+
syncDebug("boot pgwasm.create phase", { phase: "directory-ready" });
|
|
689
|
+
// The store's OWNERSHIP LOCK (store-ownership-lock.ts), taken before the handles are opened and held
|
|
690
|
+
// until the database has closed them: a deleter (destroy, wipe, candidate retirement) orders on it, so
|
|
691
|
+
// it can never `removeEntry` under handles this context still holds. Waiting for it also orders this
|
|
692
|
+
// open after a dying predecessor's release, ahead of the contention retries below.
|
|
693
|
+
const releaseOwnership = await acquireStoreOwnership(storePath);
|
|
694
|
+
let opened: PgwasmClient;
|
|
695
|
+
try {
|
|
696
|
+
opened = await openWithBoundedRetries(
|
|
697
|
+
() =>
|
|
698
|
+
createOpfsStore({
|
|
699
|
+
build,
|
|
700
|
+
directory: directory as CreateOpfsPgwasmOptions["directory"],
|
|
701
|
+
durability: relaxedDurability ? "relaxed" : "strict",
|
|
702
|
+
extentSize: OPFS_STORE_EXTENT_SIZE,
|
|
703
|
+
// The factory's own two phases: handles acquired (`store-opened`) and pgwasm booted
|
|
704
|
+
// (`pgwasm-ready`). Same rail line, so one grep shows the whole create.
|
|
705
|
+
onPhase: (phase) => syncDebug("boot pgwasm.create phase", { phase }),
|
|
706
|
+
// The store is engine-less by construction (only `live` is a create-time extension); the sync
|
|
707
|
+
// engine attaches post-create (ADR-0032 S1). Restore rides the same `pgwasm` sub-options the
|
|
708
|
+
// idb path uses; the pre-warmed boot assets ride the `build`.
|
|
709
|
+
pgwasm: {
|
|
710
|
+
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
711
|
+
extensions: { live },
|
|
712
|
+
},
|
|
713
|
+
}),
|
|
714
|
+
options?.opfsFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS,
|
|
715
|
+
);
|
|
716
|
+
} catch (error) {
|
|
717
|
+
releaseOwnership();
|
|
718
|
+
throw error;
|
|
719
|
+
}
|
|
720
|
+
return holdOwnershipUntilClosed(opened, releaseOwnership);
|
|
649
721
|
},
|
|
650
722
|
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
651
|
-
)) as
|
|
652
|
-
//
|
|
653
|
-
// non-persistent guard
|
|
654
|
-
try {
|
|
655
|
-
Object.defineProperty(opfsPglite, OPFS_REPACKED_PERSISTENT, {
|
|
656
|
-
value: true,
|
|
657
|
-
enumerable: false,
|
|
658
|
-
configurable: true,
|
|
659
|
-
});
|
|
660
|
-
} catch {
|
|
661
|
-
// A frozen/exotic instance — the guard still falls back to its dataDir classification (best-effort brand).
|
|
662
|
-
}
|
|
723
|
+
)) as PgwasmClient;
|
|
724
|
+
// No brand is needed: the store reports itself as persistent through `pg.storage`, so the BYO
|
|
725
|
+
// non-persistent guard accepts it when it is adopted as a `precreatedPgwasm` (provision-then-attach).
|
|
663
726
|
return opfsPglite;
|
|
664
727
|
}
|
|
665
728
|
|
|
666
729
|
const pglite = (await timeAsync(
|
|
667
|
-
"boot
|
|
730
|
+
"boot pgwasm.create",
|
|
668
731
|
() => {
|
|
669
|
-
const createOptions:
|
|
670
|
-
|
|
732
|
+
const createOptions: PgwasmOptions<{ live: typeof live }> = {
|
|
733
|
+
build,
|
|
734
|
+
dataDir,
|
|
671
735
|
relaxedDurability,
|
|
672
|
-
// Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball.
|
|
736
|
+
// Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. pgwasm's
|
|
673
737
|
// `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
|
|
674
738
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
675
739
|
// create (the store initdbs empty).
|
|
676
740
|
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
677
|
-
// Only
|
|
741
|
+
// Only pgwasm's own `live` extension is a create-time extension; the pgxsinkit sync runtime is NOT
|
|
678
742
|
// (ADR-0032 S1) — `createSyncClient` starts it beside the store, never on it. So a store minted here
|
|
679
743
|
// is deliberately SYNC-LESS by construction: a spare/pre-warmed store (e.g. the board's login-screen
|
|
680
744
|
// mint) carries no subscription session, no shape streams, and no open stream connections until it
|
|
@@ -683,15 +747,15 @@ export async function createClientPGlite(
|
|
|
683
747
|
live,
|
|
684
748
|
},
|
|
685
749
|
};
|
|
686
|
-
// idb/file/memory take the dataDir-string form;
|
|
687
|
-
return
|
|
750
|
+
// idb/file/memory take the dataDir-string form; pgwasm's own scheme parser selects the backend.
|
|
751
|
+
return createPgwasm(createOptions);
|
|
688
752
|
},
|
|
689
753
|
// Stamp the resolved durability mode + store scheme so every boot-rail capture shows the mode and lane the
|
|
690
754
|
// store was created under (ADR-0047 diagnosability).
|
|
691
755
|
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
692
|
-
//
|
|
693
|
-
//
|
|
694
|
-
)) as
|
|
756
|
+
// The raw store is deliberately sync-less here (only `live` is a create-time extension); the sync runtime
|
|
757
|
+
// never lands on the instance at all (ADR-0032 S1).
|
|
758
|
+
)) as PgwasmClient;
|
|
695
759
|
return pglite;
|
|
696
760
|
}
|
|
697
761
|
|
|
@@ -742,7 +806,7 @@ export interface FreshBootResolution {
|
|
|
742
806
|
}
|
|
743
807
|
|
|
744
808
|
/**
|
|
745
|
-
* Map a resolved
|
|
809
|
+
* Map a resolved pgwasm dataDir URL to the ADR-0049 decision 12 `storageBackend` diagnostic — the inverse of
|
|
746
810
|
* {@link resolveStoreDataDir}'s scheme selection (`opfs://` → opfs-repacked, `idb://` → idbfs, `file://` →
|
|
747
811
|
* filesystem, `memory://` → memory). Used to stamp the BootReport at the single client-owned mint seam. Returns
|
|
748
812
|
* `undefined` for an unrecognised scheme (a BYO instance whose dataDir the toolkit never minted — e.g. an
|
|
@@ -757,6 +821,26 @@ function storageBackendFromDataDir(dataDir: string | undefined): NonNullable<Boo
|
|
|
757
821
|
return undefined;
|
|
758
822
|
}
|
|
759
823
|
|
|
824
|
+
/**
|
|
825
|
+
* Map an instance's own `pg.storage` to the ADR-0049 decision 12 `storageBackend` diagnostic, for a BYO or adopted
|
|
826
|
+
* store the toolkit did not mint here. Returns `undefined` for a filesystem it does not recognise, so the field is
|
|
827
|
+
* then honestly omitted.
|
|
828
|
+
*/
|
|
829
|
+
function storageBackendFromStorage(
|
|
830
|
+
storage: PgwasmClient["storage"],
|
|
831
|
+
): NonNullable<BootReport["storageBackend"]> | undefined {
|
|
832
|
+
switch (storage.kind) {
|
|
833
|
+
case "memory":
|
|
834
|
+
return "memory";
|
|
835
|
+
case "idb":
|
|
836
|
+
return "idbfs";
|
|
837
|
+
case "file":
|
|
838
|
+
return "filesystem";
|
|
839
|
+
case "vfs":
|
|
840
|
+
return storage.name === OPFS_REPACKED_STORAGE_NAME ? "opfs-repacked" : undefined;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
760
844
|
/** Does a boot verdict stand up an UNCOMMITTED opfs candidate the commitment barrier must promote (invariant 3)? */
|
|
761
845
|
function verdictNeedsCommitmentBarrier(
|
|
762
846
|
verdict: StoreBootVerdict | undefined,
|
|
@@ -839,19 +923,18 @@ export async function resolveFreshBoot(
|
|
|
839
923
|
* for unit tests via {@link FreshCommitmentSeams}.
|
|
840
924
|
*/
|
|
841
925
|
/**
|
|
842
|
-
*
|
|
843
|
-
* requires it (data-before-authority, invariant 3); a store that
|
|
844
|
-
*
|
|
926
|
+
* Resolve the live engine's strict sync (`strictSync(pg)` from `@pgxsinkit/pgwasm/opfs`) for the commitment
|
|
927
|
+
* barrier. The barrier requires it (data-before-authority, invariant 3); a store that is not on the OPFS-repacked
|
|
928
|
+
* filesystem has none, which is a boot invariant violation. `/opfs` is imported lazily, as the factory is.
|
|
845
929
|
*/
|
|
846
|
-
function resolveEngineStrictSync(pglite:
|
|
847
|
-
|
|
848
|
-
if (typeof strictSync !== "function") {
|
|
930
|
+
function resolveEngineStrictSync(pglite: PgwasmClient): () => Promise<void> {
|
|
931
|
+
if (!isOpfsRepackedStore(pglite)) {
|
|
849
932
|
throw new Error(
|
|
850
|
-
"[pgxsinkit] fresh commitment: the
|
|
851
|
-
"requires an OPFS-repacked engine (data-before-authority, invariant 3).",
|
|
933
|
+
"[pgxsinkit] fresh commitment: the store is not on the OPFS-repacked filesystem, so it has no strict " +
|
|
934
|
+
"sync — the commitment barrier requires an OPFS-repacked engine (data-before-authority, invariant 3).",
|
|
852
935
|
);
|
|
853
936
|
}
|
|
854
|
-
return () => strictSync
|
|
937
|
+
return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pglite);
|
|
855
938
|
}
|
|
856
939
|
|
|
857
940
|
export async function runFreshCommitmentBarrier(
|
|
@@ -874,11 +957,11 @@ export async function runFreshCommitmentBarrier(
|
|
|
874
957
|
}
|
|
875
958
|
|
|
876
959
|
/**
|
|
877
|
-
* @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`
|
|
878
|
-
* `
|
|
960
|
+
* @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`pgwasmInstance` /
|
|
961
|
+
* `precreatedPgwasm` — the provision→adopt accelerator, ADR-0032 decision 5) never enters `openOwnedStore`, so
|
|
879
962
|
* {@link resolveFreshBoot} never runs and nothing flags the barrier. Left alone, an adopted OPFS store therefore
|
|
880
963
|
* stays UNCOMMITTED for its whole life: no sentinel, and a record still at `opfs-candidate` (or absent, when the
|
|
881
|
-
* adopted instance was built outside the mint seam — a BYO `
|
|
964
|
+
* adopted instance was built outside the mint seam — a BYO `pgwasmInstance`). That state is INDISTINGUISHABLE
|
|
882
965
|
* from a torn candidate, so the next client-owned boot classifies `delete-candidate-and-rebuild` and DESTROYS a
|
|
883
966
|
* populated store — offline, with nothing to rebuild from. An adopted opfs boot therefore owes the SAME barrier
|
|
884
967
|
* ({@link runFreshCommitmentBarrier}) a fresh one does, pre-expose (invariant 3).
|
|
@@ -1013,7 +1096,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1013
1096
|
*/
|
|
1014
1097
|
readSilenceMs?: number;
|
|
1015
1098
|
/**
|
|
1016
|
-
* The local store's name (ADR-0036) — a PLAIN path/name, never a
|
|
1099
|
+
* The local store's name (ADR-0036) — a PLAIN path/name, never a pgwasm storage URL. The storage backend
|
|
1017
1100
|
* is DERIVED from the engine home (capability-selected opfs-repacked with IndexedDB fallback in a browser,
|
|
1018
1101
|
* or the filesystem on Bun/Node); a
|
|
1019
1102
|
* scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
|
|
@@ -1035,68 +1118,73 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1035
1118
|
* ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
|
|
1036
1119
|
* (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
|
|
1037
1120
|
* backend. Absent/false is the honest IDBFS home — the declared `backend: "idbfs"` mode or a capability-absence
|
|
1038
|
-
* fallback (a main thread can never hold handles either). Forwarded verbatim to {@link
|
|
1121
|
+
* fallback (a main thread can never hold handles either). Forwarded verbatim to {@link createPgwasmClient}, which
|
|
1039
1122
|
* resolves the actual dataDir from it.
|
|
1040
1123
|
*/
|
|
1041
1124
|
hasOpfsSyncAccess?: boolean;
|
|
1042
1125
|
/**
|
|
1043
|
-
*
|
|
1044
|
-
*
|
|
1045
|
-
*
|
|
1046
|
-
*
|
|
1047
|
-
*
|
|
1048
|
-
*
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1126
|
+
* The Postgres build a client-owned store runs on; defaults to `cBuild`. To hide the ~2.5s cold
|
|
1127
|
+
* `boot pgwasm.create` cost — dominated by the WASM fetch+compile — behind user think-time, pass
|
|
1128
|
+
* `createCBuild({ assets })` from `@pgxsinkit/pgwasm-c`, where `assets` is a `Promise<CBuildAssets>` the host
|
|
1129
|
+
* started fetching/compiling on an earlier screen (e.g. the login/identity picker): by the time a store is
|
|
1130
|
+
* opened the assets are resolved and the build skips its own lazy asset load. Ignored when
|
|
1131
|
+
* {@link pgwasmInstance} is supplied (the caller owns that instance's boot). A rejected/failed warm never
|
|
1132
|
+
* fails the boot — the build falls back to loading its own assets, so the warm is a pure best-effort
|
|
1133
|
+
* accelerator. The boot waits for the build's `prepare()` (the warm) before its `boot pgwasm.create` stamp,
|
|
1134
|
+
* so `pgwasmCreateMs` measures the create alone.
|
|
1135
|
+
*
|
|
1136
|
+
* The build must be the registry's declared `storage.build` (default `"c"`, ADR-0063): a mismatch throws
|
|
1137
|
+
* `StorageBuildMismatchError` before any store is touched. An adopted {@link pgwasmInstance} /
|
|
1138
|
+
* {@link precreatedPgwasm} is checked the same way, against its own `pg.build`.
|
|
1051
1139
|
*/
|
|
1052
|
-
|
|
1140
|
+
build?: PostgresBuild;
|
|
1053
1141
|
resetSubscriptionKeys?: string[];
|
|
1054
|
-
prepareLocalDbBeforeSchema?: (pglite:
|
|
1055
|
-
prepareLocalDbAfterSchema?: (pglite:
|
|
1142
|
+
prepareLocalDbBeforeSchema?: (pglite: PgwasmClient) => Promise<void>;
|
|
1143
|
+
prepareLocalDbAfterSchema?: (pglite: PgwasmClient) => Promise<void>;
|
|
1056
1144
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
1057
1145
|
onTableInitialSync?: (tableKey: string) => void;
|
|
1058
1146
|
/**
|
|
1059
|
-
* A fully-provisioned
|
|
1147
|
+
* A fully-provisioned pgwasm instance the CALLER owns end-to-end. The client runs NONE of its
|
|
1060
1148
|
* post-create boot steps against it — no schema exec, prepare hooks, or registry reconciliation
|
|
1061
1149
|
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
1062
1150
|
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
1063
1151
|
* - {@link storePath} (default) — the client creates the store AND runs every post-create step.
|
|
1064
|
-
* - {@link
|
|
1152
|
+
* - {@link precreatedPgwasm} — the caller creates the raw store (via {@link createPgwasmClient}), but
|
|
1065
1153
|
* the client still runs every post-create step (schema, prepare hooks, and reconciliation), exactly as
|
|
1066
1154
|
* `storePath` does.
|
|
1067
|
-
* - `
|
|
1155
|
+
* - `pgwasmInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
1068
1156
|
*
|
|
1069
1157
|
* A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
|
|
1070
|
-
* non-persistent (a `new
|
|
1158
|
+
* non-persistent (a `new pgwasm()` default, or an in-memory store) — pgxsinkit's durability semantics
|
|
1071
1159
|
* assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
|
|
1072
1160
|
* `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
|
|
1073
1161
|
*
|
|
1074
|
-
* Mutually exclusive with {@link
|
|
1162
|
+
* Mutually exclusive with {@link precreatedPgwasm} (supplying both throws).
|
|
1075
1163
|
*/
|
|
1076
|
-
|
|
1164
|
+
pgwasmInstance?: PgwasmClient;
|
|
1077
1165
|
/**
|
|
1078
|
-
* A raw
|
|
1166
|
+
* A raw pgwasm instance the caller created EAGERLY (via {@link createPgwasmClient}) — typically on an
|
|
1079
1167
|
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
1080
1168
|
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and registry
|
|
1081
1169
|
* reconciliation all run exactly as on the {@link storePath} path. This is the difference from
|
|
1082
|
-
* {@link
|
|
1170
|
+
* {@link pgwasmInstance} (which skips schema, prepare hooks, and reconciliation because the caller owns
|
|
1083
1171
|
* them); see that
|
|
1084
1172
|
* option's JSDoc for the three-way distinction.
|
|
1085
1173
|
*
|
|
1086
1174
|
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
1087
|
-
* - Supplying both this and {@link
|
|
1175
|
+
* - Supplying both this and {@link pgwasmInstance} throws — they claim different ownership.
|
|
1088
1176
|
* - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
|
|
1089
1177
|
* create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
|
|
1090
|
-
* consuming {@link
|
|
1178
|
+
* consuming {@link build} if provided). The pattern is a pure accelerator, never a boot
|
|
1091
1179
|
* dependency.
|
|
1092
1180
|
* - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
|
|
1093
|
-
* {@link
|
|
1181
|
+
* {@link pgwasmInstance} (checked after resolution, so the refusal propagates rather than being
|
|
1094
1182
|
* swallowed by the reject-fallback).
|
|
1095
1183
|
*/
|
|
1096
|
-
|
|
1184
|
+
precreatedPgwasm?: Promise<PgwasmClient>;
|
|
1097
1185
|
/**
|
|
1098
1186
|
* Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
|
|
1099
|
-
* {@link SyncClient.exportStore}. The client creates its store with the backup handed to
|
|
1187
|
+
* {@link SyncClient.exportStore}. The client creates its store with the backup handed to pgwasm's
|
|
1100
1188
|
* `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
|
|
1101
1189
|
* bytes that travelled inside it). Three restore-only rules apply, none of them optional:
|
|
1102
1190
|
*
|
|
@@ -1115,7 +1203,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1115
1203
|
* ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
|
|
1116
1204
|
* (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
|
|
1117
1205
|
*
|
|
1118
|
-
* Mutually exclusive with {@link
|
|
1206
|
+
* Mutually exclusive with {@link pgwasmInstance} AND {@link precreatedPgwasm} — restore owns the store's
|
|
1119
1207
|
* creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
|
|
1120
1208
|
* with `restoreFrom` throws).
|
|
1121
1209
|
*/
|
|
@@ -1123,7 +1211,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1123
1211
|
/**
|
|
1124
1212
|
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
1125
1213
|
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
1126
|
-
* is enabled, and the client owns schema exec — i.e. not the {@link
|
|
1214
|
+
* is enabled, and the client owns schema exec — i.e. not the {@link pgwasmInstance} path), the shape
|
|
1127
1215
|
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery, and registry
|
|
1128
1216
|
* reconciliation) and buffered in memory, with commits gated until those phases finish — so the network
|
|
1129
1217
|
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
@@ -1184,9 +1272,10 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1184
1272
|
batchEventUrl?: string;
|
|
1185
1273
|
/**
|
|
1186
1274
|
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff
|
|
1187
|
-
* tuning, and per-Event-stream overrides. NEVER on the registry —
|
|
1188
|
-
* deployment tuning, and a batch-size tweak must not surface as a
|
|
1189
|
-
* additionally clamped by the contracts-level request-shape limits the
|
|
1275
|
+
* tuning, the acked ledger's retention (ADR-0060), and per-Event-stream overrides. NEVER on the registry —
|
|
1276
|
+
* the registry is the contract, cadence is deployment tuning, and a batch-size tweak must not surface as a
|
|
1277
|
+
* registry diff. Client batching is additionally clamped by the contracts-level request-shape limits the
|
|
1278
|
+
* server enforces independently.
|
|
1190
1279
|
*/
|
|
1191
1280
|
events?: EventLaneOptions;
|
|
1192
1281
|
/**
|
|
@@ -1226,8 +1315,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1226
1315
|
/**
|
|
1227
1316
|
* @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
|
|
1228
1317
|
* minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
|
|
1229
|
-
* time here; the boot reports them as {@link BootReport.provision} and sets `phases.
|
|
1230
|
-
* A promise because the stamp settles with the spare's `create`. Only honoured on the {@link
|
|
1318
|
+
* time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgwasmCreateMs = null`.
|
|
1319
|
+
* A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPgwasm}
|
|
1231
1320
|
* adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
|
|
1232
1321
|
*/
|
|
1233
1322
|
provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
|
|
@@ -1348,7 +1437,7 @@ export interface SubscribeLiveRowsInput {
|
|
|
1348
1437
|
/**
|
|
1349
1438
|
* The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
|
|
1350
1439
|
* compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
|
|
1351
|
-
* tables share a column name compiles to duplicate output names — which
|
|
1440
|
+
* tables share a column name compiles to duplicate output names — which pgwasm's `live` extension
|
|
1352
1441
|
* refuses to materialise (`column "title" specified more than once`) and which silently collapse
|
|
1353
1442
|
* same-named columns even in a plain query. When supplied, the seam wraps the query so every output
|
|
1354
1443
|
* column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
|
|
@@ -1416,14 +1505,14 @@ export interface PreparedQueryResult<TTable extends string = string> {
|
|
|
1416
1505
|
}
|
|
1417
1506
|
|
|
1418
1507
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
1419
|
-
drizzle:
|
|
1420
|
-
|
|
1508
|
+
drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
1509
|
+
pgwasm: PgwasmClient;
|
|
1421
1510
|
views: RegistryViews<TRegistry>;
|
|
1422
1511
|
tables: {
|
|
1423
1512
|
[TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
|
|
1424
1513
|
};
|
|
1425
1514
|
/**
|
|
1426
|
-
* Local-read readiness (ADR-0041): resolves once
|
|
1515
|
+
* Local-read readiness (ADR-0041): resolves once pgwasm is open, the durable schema is ready, registry
|
|
1427
1516
|
* reconciliation has completed, and the drizzle read
|
|
1428
1517
|
* facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
|
|
1429
1518
|
* start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
|
|
@@ -1582,7 +1671,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1582
1671
|
* The store's owed-state diagnostics: the mutation journal's per-status counts, plus — when this client has
|
|
1583
1672
|
* an Event lane — the Outbox's drain signal (ADR-0053 decision 8: the Event lane's durable state takes a
|
|
1584
1673
|
* position on every lifecycle surface). `outbox` is the boolean signal rather than a count, for the reason
|
|
1585
|
-
* {@link onOutboxStatus} carries none; it is absent on a client with no lane.
|
|
1674
|
+
* {@link onOutboxStatus} carries none; it is absent on a client with no lane. It reports what is OWED, so
|
|
1675
|
+
* acked rows held by the ledger's retention (ADR-0060) read as empty.
|
|
1586
1676
|
*/
|
|
1587
1677
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
|
|
1588
1678
|
mutation: MutationDiagnostics;
|
|
@@ -1603,17 +1693,45 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1603
1693
|
* issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
|
|
1604
1694
|
* {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
|
|
1605
1695
|
* store, not to read app state or mutate it.
|
|
1696
|
+
*
|
|
1697
|
+
* `options.blob` makes it the single-statement BULK-LOAD seam too: pass a `COPY … FROM '/dev/blob'`
|
|
1698
|
+
* statement plus its COPY TEXT bytes ({@link buildCopyFromBlobStatement}) to load a chunk of rows into a
|
|
1699
|
+
* LOCAL-ONLY table the app owns without a transaction around it. Use {@link rawTransaction} when the load
|
|
1700
|
+
* must land together with other statements.
|
|
1606
1701
|
*/
|
|
1607
1702
|
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
1608
|
-
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
|
|
1703
|
+
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. Takes no `blob`. */
|
|
1609
1704
|
rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
1705
|
+
/**
|
|
1706
|
+
* {@link rawQuery}'s ATOMIC form: run the given statements, in order, inside ONE local transaction and
|
|
1707
|
+
* resolve one {@link Results} per statement. All-or-nothing — a statement that throws rolls the whole list
|
|
1708
|
+
* back and rejects with its error; an empty list resolves `[]` without opening a transaction at all.
|
|
1709
|
+
*
|
|
1710
|
+
* The seam exists for a consumer that owns LOCAL-ONLY tables pgxsinkit does not manage (a definition cache,
|
|
1711
|
+
* a personal dictionary — anything that must delete-then-insert without a torn intermediate state). It is
|
|
1712
|
+
* the ONLY way to get that atomicity on a worker-attached client, where the tab has no pgwasm of its own,
|
|
1713
|
+
* and it behaves identically on both client forms rather than making atomicity depend on where the engine
|
|
1714
|
+
* happens to live.
|
|
1715
|
+
*
|
|
1716
|
+
* Every {@link rawQuery} caveat still holds, transaction or not: the statements run raw against the local
|
|
1717
|
+
* store, BYPASSING the mutation journal and optimistic overlay, so a write through here stays local and
|
|
1718
|
+
* will NEVER converge. Use it for the tables the consumer owns — never for a synced table, whose only
|
|
1719
|
+
* write path is `mutate` / `tables.*`.
|
|
1720
|
+
*
|
|
1721
|
+
* A statement may carry {@link RawStatement.blob}: the bytes of a `COPY … FROM '/dev/blob'` BULK load
|
|
1722
|
+
* ({@link buildCopyFromBlobStatement} renders the pair). That is how a chunk of thousands of rows lands
|
|
1723
|
+
* in one statement instead of one INSERT per row — and, in a list, atomically alongside whatever must
|
|
1724
|
+
* land with it. On a worker-attached client those bytes are TRANSFERRED, never copied, so the caller's
|
|
1725
|
+
* buffer is detached when the call dispatches.
|
|
1726
|
+
*/
|
|
1727
|
+
rawTransaction: (statements: readonly RawStatement[], options?: RawQueryOptions) => Promise<Results[]>;
|
|
1610
1728
|
/**
|
|
1611
1729
|
* @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
|
|
1612
1730
|
* ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
|
|
1613
1731
|
* `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
|
|
1614
1732
|
* `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
|
|
1615
1733
|
* client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
|
|
1616
|
-
* worker-side. Accepts the full
|
|
1734
|
+
* worker-side. Accepts the full pgwasm {@link QueryOptions} (the worker re-applies drizzle's identity
|
|
1617
1735
|
* parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
|
|
1618
1736
|
* read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
|
|
1619
1737
|
* from the generated API docs (typedoc excludeInternal).
|
|
@@ -1659,8 +1777,19 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1659
1777
|
*/
|
|
1660
1778
|
ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
|
|
1661
1779
|
/**
|
|
1662
|
-
* Whether a relation's group
|
|
1663
|
-
*
|
|
1780
|
+
* Whether a relation's consistency group is STARTED (ADR-0021) — a durable subscription for it exists,
|
|
1781
|
+
* so reads of it are meaningful. The synchronous peek, for guards and render paths that cannot await.
|
|
1782
|
+
*
|
|
1783
|
+
* For an ordinary group that coincides with caught up: it reads `false` while the group is activated but
|
|
1784
|
+
* still catching up, and `true` once its catch-up lands. A **promoted** `lazy + persistent` group (one a
|
|
1785
|
+
* previous session activated, so boot starts it) reads `true` from boot — including offline, while its
|
|
1786
|
+
* subscribe is still retrying — because its local table is durable and populated, which is what "started"
|
|
1787
|
+
* asks. A dormant `lazy` relation reads `false`, as does every relation while sync is PENDING (enabled but
|
|
1788
|
+
* not yet wired, ADR-0041); every key reads `true` when sync is DISABLED (local-only — nothing is dormant).
|
|
1789
|
+
*
|
|
1790
|
+
* Catch-up COMPLETION is the separate, strictly stronger question {@link groupReady} answers. A
|
|
1791
|
+
* worker-attached client answers this from a snapshot the worker computes with this same method on its own
|
|
1792
|
+
* client (ADR-0059), so the two modes cannot diverge.
|
|
1664
1793
|
*/
|
|
1665
1794
|
isSynced: (key: SyncTableName<TRegistry>) => boolean;
|
|
1666
1795
|
/**
|
|
@@ -1763,8 +1892,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1763
1892
|
*/
|
|
1764
1893
|
liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
|
|
1765
1894
|
/**
|
|
1766
|
-
* Take a **store backup** (ADR-0035): a full-fidelity,
|
|
1767
|
-
* store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via
|
|
1895
|
+
* Take a **store backup** (ADR-0035): a full-fidelity, pgwasm-restorable tarball of the whole local
|
|
1896
|
+
* store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via pgwasm's
|
|
1768
1897
|
* `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
|
|
1769
1898
|
* suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
|
|
1770
1899
|
* with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
|
|
@@ -1813,16 +1942,88 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1813
1942
|
export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };
|
|
1814
1943
|
|
|
1815
1944
|
/**
|
|
1816
|
-
* The structured-clone-safe subset of
|
|
1945
|
+
* The structured-clone-safe subset of pgwasm's `QueryOptions` the inspection surface carries. Kept
|
|
1817
1946
|
* narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
|
|
1818
1947
|
* `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
|
|
1819
|
-
* of this contract. `rowMode: "array"` is what `@
|
|
1948
|
+
* of this contract. `rowMode: "array"` is what `@pgxsinkit/pgwasm-repl` asks for on every exec.
|
|
1949
|
+
*
|
|
1950
|
+
* `blob` diverges from pgwasm's own type for the same reason: pgwasm takes a `Blob`, which is neither
|
|
1951
|
+
* transferable nor (usefully) clonable, so this contract carries BYTES and wraps them into the `Blob` at
|
|
1952
|
+
* the pgwasm call (ADR-0061).
|
|
1820
1953
|
*/
|
|
1821
1954
|
export interface RawQueryOptions {
|
|
1822
1955
|
rowMode?: "object" | "array";
|
|
1956
|
+
/**
|
|
1957
|
+
* The bytes pgwasm reads when the statement is a `COPY … FROM '/dev/blob'` — the single-statement form
|
|
1958
|
+
* of {@link RawStatement.blob}, for a bulk load that needs no surrounding transaction. Build the
|
|
1959
|
+
* statement AND these bytes together with {@link buildCopyFromBlobStatement}; any other statement
|
|
1960
|
+
* ignores this option.
|
|
1961
|
+
*
|
|
1962
|
+
* On a worker-attached client the buffer is **TRANSFERRED**, not copied: it is detached the moment the
|
|
1963
|
+
* call dispatches, so the caller must NOT read or reuse it afterwards (build a fresh one per chunk).
|
|
1964
|
+
*
|
|
1965
|
+
* Typed over a real `ArrayBuffer` (not the default `ArrayBufferLike`) because that IS the contract: a
|
|
1966
|
+
* `SharedArrayBuffer`-backed view can neither be transferred nor read as a `Blob` part.
|
|
1967
|
+
*/
|
|
1968
|
+
blob?: Uint8Array<ArrayBuffer>;
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
/**
|
|
1972
|
+
* One statement of a {@link SyncClient.rawTransaction} list: the SQL plus its bound params, and optionally
|
|
1973
|
+
* the `blob` bytes a `COPY` statement ingests. Structured-clone safe by construction (a string, plain
|
|
1974
|
+
* values and a `Uint8Array`), because on a worker-attached client the whole list crosses the bridge in a
|
|
1975
|
+
* single RPC.
|
|
1976
|
+
*/
|
|
1977
|
+
export interface RawStatement {
|
|
1978
|
+
readonly sql: string;
|
|
1979
|
+
readonly params?: readonly unknown[];
|
|
1980
|
+
/**
|
|
1981
|
+
* The bytes pgwasm reads for this statement's `/dev/blob` — how a LOCAL-ONLY table an app owns is
|
|
1982
|
+
* BULK-LOADED with `COPY` instead of one INSERT per row. It rides ONLY with a `COPY … FROM '/dev/blob'`
|
|
1983
|
+
* statement; any other statement ignores it. Build the pair with {@link buildCopyFromBlobStatement},
|
|
1984
|
+
* which renders the statement and serializes the rows from ONE column list (and with the same COPY TEXT
|
|
1985
|
+
* serializer the sync applier uses), so the SQL and the bytes cannot disagree.
|
|
1986
|
+
*
|
|
1987
|
+
* **On a worker-attached client the buffer is TRANSFERRED, not copied.** It is listed on the RPC's
|
|
1988
|
+
* `postMessage` transfer list, so it is DETACHED (`byteLength === 0`) the moment the call dispatches:
|
|
1989
|
+
* the caller must not read, reuse or re-send it afterwards — serialize a fresh chunk for each call.
|
|
1990
|
+
* Zero-copy is the point: a 1000-row chunk crosses the bridge without a structured-clone copy.
|
|
1991
|
+
*
|
|
1992
|
+
* Typed over a real `ArrayBuffer` (not the default `ArrayBufferLike`) because that IS the contract: a
|
|
1993
|
+
* `SharedArrayBuffer`-backed view can neither be transferred nor read as a `Blob` part.
|
|
1994
|
+
*/
|
|
1995
|
+
readonly blob?: Uint8Array<ArrayBuffer>;
|
|
1823
1996
|
}
|
|
1824
1997
|
|
|
1825
|
-
/**
|
|
1998
|
+
/**
|
|
1999
|
+
* Translate the raw seam's structured-clone-safe options into the pgwasm `QueryOptions` the store takes:
|
|
2000
|
+
* the COPY body travels as BYTES (a `Uint8Array` — transferable across the worker bridge, unlike a `Blob`)
|
|
2001
|
+
* and pgwasm reads `/dev/blob` from a `Blob`, so it is wrapped HERE, at the one place the two meet.
|
|
2002
|
+
* A statement's own `blob` ({@link RawStatement.blob}) wins over the call-level {@link RawQueryOptions.blob}.
|
|
2003
|
+
*/
|
|
2004
|
+
function toPgliteQueryOptions(
|
|
2005
|
+
options?: RawQueryOptions,
|
|
2006
|
+
statementBlob?: Uint8Array<ArrayBuffer>,
|
|
2007
|
+
): QueryOptions | undefined {
|
|
2008
|
+
const bytes = statementBlob ?? options?.blob;
|
|
2009
|
+
const rest = withoutCopyBlob(options);
|
|
2010
|
+
if (bytes === undefined) return rest;
|
|
2011
|
+
return { ...rest, blob: new Blob([bytes]) };
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* The same options WITHOUT the COPY bytes — for `rawExec`, whose pgwasm counterpart runs a multi-statement
|
|
2016
|
+
* script through the simple protocol and has no `/dev/blob` hook at all. Dropping the field keeps the raw
|
|
2017
|
+
* trio on ONE options type (a caller can pass the same object to all three) while the COPY body reaches
|
|
2018
|
+
* only the two seams that can actually ingest it.
|
|
2019
|
+
*/
|
|
2020
|
+
function withoutCopyBlob(options?: RawQueryOptions): QueryOptions | undefined {
|
|
2021
|
+
if (options === undefined) return undefined;
|
|
2022
|
+
const { blob: _blobBytes, ...rest } = options;
|
|
2023
|
+
return rest;
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
/** The `{ query, exec }` duck `@pgxsinkit/pgwasm-repl` drives, backed by a client's inspection surface. */
|
|
1826
2027
|
export interface ReplInspectionSurface {
|
|
1827
2028
|
query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
1828
2029
|
exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
@@ -1830,9 +2031,9 @@ export interface ReplInspectionSurface {
|
|
|
1830
2031
|
|
|
1831
2032
|
/**
|
|
1832
2033
|
* Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
|
|
1833
|
-
* `@
|
|
1834
|
-
* each statement routes through the worker bridge, so the REPL works even though `client.
|
|
1835
|
-
* unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `
|
|
2034
|
+
* `@pgxsinkit/pgwasm-repl` needs. Identical on the in-process and worker-attached client — on the latter
|
|
2035
|
+
* each statement routes through the worker bridge, so the REPL works even though `client.pgwasm` is
|
|
2036
|
+
* unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `pgwasm`).
|
|
1836
2037
|
* The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
|
|
1837
2038
|
*/
|
|
1838
2039
|
export function replAdapter(
|
|
@@ -1882,7 +2083,7 @@ type SyncGroupsRuntime = CircuitsGroupSyncResult;
|
|
|
1882
2083
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1883
2084
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1884
2085
|
): Promise<SyncClient<TRegistry>> {
|
|
1885
|
-
// Fail fast on a bad keep-alive policy — before any
|
|
2086
|
+
// Fail fast on a bad keep-alive policy — before any pgwasm boot work (ADR-0040 decision 4 — bounded).
|
|
1886
2087
|
validateLiveQueryPolicy(options.liveQueries);
|
|
1887
2088
|
const status: SyncRuntimeStatus = {
|
|
1888
2089
|
phase: "booting",
|
|
@@ -1924,9 +2125,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1924
2125
|
rejectBootSettled = reject;
|
|
1925
2126
|
});
|
|
1926
2127
|
|
|
1927
|
-
if (options.
|
|
2128
|
+
if (options.pgwasmInstance && options.precreatedPgwasm) {
|
|
1928
2129
|
throw new Error(
|
|
1929
|
-
"createSyncClient: pass at most one of `
|
|
2130
|
+
"createSyncClient: pass at most one of `pgwasmInstance` or `precreatedPgwasm` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, and registry reconciliation).",
|
|
1930
2131
|
);
|
|
1931
2132
|
}
|
|
1932
2133
|
|
|
@@ -1934,9 +2135,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1934
2135
|
// the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already
|
|
1935
2136
|
// exists and is provisioned). Fail loudly rather than silently ignore one.
|
|
1936
2137
|
const restoreBoot = options.restoreFrom != null;
|
|
1937
|
-
if (restoreBoot && (options.
|
|
2138
|
+
if (restoreBoot && (options.pgwasmInstance || options.precreatedPgwasm)) {
|
|
1938
2139
|
throw new Error(
|
|
1939
|
-
"createSyncClient: `restoreFrom` is mutually exclusive with `
|
|
2140
|
+
"createSyncClient: `restoreFrom` is mutually exclusive with `pgwasmInstance` / `precreatedPgwasm` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).",
|
|
1940
2141
|
);
|
|
1941
2142
|
}
|
|
1942
2143
|
|
|
@@ -1968,7 +2169,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1968
2169
|
const engineHome: BootReport["engineHome"] | undefined = bootMode === "worker" ? options.engineHome : "in-process";
|
|
1969
2170
|
|
|
1970
2171
|
// Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
|
|
1971
|
-
// sync. Created FIRST so its monotonic anchor precedes every timed phase (including the
|
|
2172
|
+
// sync. Created FIRST so its monotonic anchor precedes every timed phase (including the pgwasm create).
|
|
1972
2173
|
const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
|
|
1973
2174
|
mode: bootMode,
|
|
1974
2175
|
freshStore: options.freshStore === true,
|
|
@@ -1998,7 +2199,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1998
2199
|
const backendOverride = testStoreMarker === "memory" ? ("memory" as const) : undefined;
|
|
1999
2200
|
|
|
2000
2201
|
// Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
|
|
2001
|
-
// `
|
|
2202
|
+
// `precreatedPgwasm` reject-fallback), so both consume the same pre-warm + resolve the same backend.
|
|
2002
2203
|
// ADR-0049 step 11c: the OPFS-home grant the client-owned mint opens under. Starts at the placement probe's
|
|
2003
2204
|
// value and is ADJUSTED DOWN to `false` by the pre-mint phase machine (an existing idb store is opened in
|
|
2004
2205
|
// place — the backend is fixed at first mint). Read at mint time by `timedCreate` below, so the phase machine
|
|
@@ -2019,14 +2220,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2019
2220
|
// declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
|
|
2020
2221
|
// explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
|
|
2021
2222
|
// The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
|
|
2022
|
-
// fallback) via the internal carrier on `
|
|
2223
|
+
// fallback) via the internal carrier on `createPgwasmClient`; no open site takes a durability option, so
|
|
2023
2224
|
// no mint can contradict the data contract.
|
|
2024
|
-
const
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
).
|
|
2028
|
-
const
|
|
2029
|
-
|
|
2225
|
+
const resolvedDeclaration = resolveStorageDeclaration(getSyncRegistryStorage(options.registry), options.storage);
|
|
2226
|
+
const resolvedDurability: StorageDurability = resolvedDeclaration.durability;
|
|
2227
|
+
// ADR-0063: the declared Postgres build (default `"c"`). A client-owned mint runs on the supplied build
|
|
2228
|
+
// (`options.build`, else `cBuild`), which must be the declared one; an adopted instance's `pg.build` must too.
|
|
2229
|
+
const declaredBuild: StorageBuild = resolvedDeclaration.build;
|
|
2230
|
+
const suppliedBuild = options.build ?? cBuild;
|
|
2231
|
+
const createClientOptions: CreatePgwasmClientOptions = {
|
|
2232
|
+
...(options.build ? { build: options.build } : {}),
|
|
2233
|
+
declaredBuild,
|
|
2234
|
+
buildCheckSite: "createSyncClient",
|
|
2030
2235
|
...(backendOverride ? { backendOverride } : {}),
|
|
2031
2236
|
durability: resolvedDurability,
|
|
2032
2237
|
// Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
|
|
@@ -2037,6 +2242,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2037
2242
|
const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
2038
2243
|
let openedStorageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
|
|
2039
2244
|
|
|
2245
|
+
// A boot that will mint (no adopted instance) refuses a supplied build that is not the declared one here,
|
|
2246
|
+
// before the restore probe or any meta read touches a store. A `precreatedPgwasm` whose create rejected
|
|
2247
|
+
// mints through `openOwnedStore`, which checks again first.
|
|
2248
|
+
if (!options.pgwasmInstance && !options.precreatedPgwasm) {
|
|
2249
|
+
assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2040
2252
|
// Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
|
|
2041
2253
|
// brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
|
|
2042
2254
|
// half-write) an existing datadir. The memory test lane is fresh by construction, so the probe is a no-op.
|
|
@@ -2050,20 +2262,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2050
2262
|
throw new RestoreTargetExistsError(fallbackStorePath);
|
|
2051
2263
|
}
|
|
2052
2264
|
}
|
|
2053
|
-
// Time a client-owned `
|
|
2265
|
+
// Time a client-owned `createPgwasmClient` into `phases.pgwasmCreateMs`; an ADOPTED store (spare or
|
|
2054
2266
|
// caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
|
|
2055
|
-
const timedCreate = async (): Promise<
|
|
2267
|
+
const timedCreate = async (): Promise<PgwasmClient> => {
|
|
2268
|
+
// The build's warm (if any) settles BEFORE the clock starts: `pgwasmCreateMs` measures the create alone,
|
|
2269
|
+
// never an unfinished warm (`prepare` never rejects; a failed warm is the build's own lazy load).
|
|
2270
|
+
await suppliedBuild.prepare?.();
|
|
2056
2271
|
const startedAt = performance.now();
|
|
2057
2272
|
// ADR-0049 step 10b/11c: the OPFS-home grant is spread in at MINT time (not baked into `createClientOptions`),
|
|
2058
2273
|
// so the pre-mint phase machine that ran just above can settle `bootHasOpfsSyncAccess` first — opening the
|
|
2059
2274
|
// committed opfs store or the existing idb store. Default absent keeps today's backend.
|
|
2060
2275
|
// ADR-0049 decision 12: this is the SINGLE client-owned mint seam, so stamp `storageBackend` from the resolved
|
|
2061
|
-
// dataDir scheme here — the same resolution `
|
|
2276
|
+
// dataDir scheme here — the same resolution `createPgwasmClient` performs, so the diagnostic never diverges
|
|
2062
2277
|
// from the backend actually opened. Covers every client-owned mint (in-process, worker, precreated-fallback).
|
|
2063
2278
|
const resolvedDataDir = bootHasOpfsSyncAccess
|
|
2064
2279
|
? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
|
|
2065
2280
|
: resolveStoreDataDir(fallbackStorePath, backendOverride);
|
|
2066
|
-
const created = await
|
|
2281
|
+
const created = await createPgwasmClient(fallbackStorePath, {
|
|
2067
2282
|
...createClientOptions,
|
|
2068
2283
|
...(bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
2069
2284
|
});
|
|
@@ -2080,21 +2295,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2080
2295
|
};
|
|
2081
2296
|
|
|
2082
2297
|
// Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
|
|
2083
|
-
// acknowledgment is present. `
|
|
2084
|
-
//
|
|
2085
|
-
//
|
|
2298
|
+
// acknowledgment is present. `classifyNonPersistentStorage` inspects the instance's own `storage` — the
|
|
2299
|
+
// provably-non-persistent shapes are a memory store (pgwasm's default, or an explicit `memory://`) and a
|
|
2300
|
+
// filesystem that reports itself non-persistent. Checked AFTER a
|
|
2086
2301
|
// successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the
|
|
2087
|
-
// `
|
|
2088
|
-
const refuseIfNonPersistent = (instance:
|
|
2302
|
+
// `precreatedPgwasm` reject-fallback below (which only catches a create that never produced a store).
|
|
2303
|
+
const refuseIfNonPersistent = (instance: PgwasmClient): void => {
|
|
2089
2304
|
if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
|
|
2090
|
-
// An opfs-repacked instance
|
|
2091
|
-
// (
|
|
2092
|
-
|
|
2093
|
-
if (isOpfsRepackedPersistent(instance)) return;
|
|
2094
|
-
const observedDataDir = (instance as { dataDir?: string }).dataDir;
|
|
2095
|
-
// The two provably-non-persistent shapes: an undefined dataDir (a raw `new PGlite()` in-memory default)
|
|
2096
|
-
// and a `memory://` store. Every store the funnel mints carries a real `idb://`/`file://` dataDir string.
|
|
2097
|
-
const observed = classifyNonPersistentDataDir(observedDataDir);
|
|
2305
|
+
// An opfs-repacked instance reports `{ kind: "vfs", persistent: true }`, so adopting a provisioned opfs
|
|
2306
|
+
// store (provision-then-attach, ADR-0049) passes; every store the funnel mints is idb/file/opfs.
|
|
2307
|
+
const observed = classifyNonPersistentStorage(instance.storage);
|
|
2098
2308
|
if (observed !== null) throw new NonPersistentStoreError(observed);
|
|
2099
2309
|
};
|
|
2100
2310
|
|
|
@@ -2102,7 +2312,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2102
2312
|
// accelerator MUST enter here: recovery/classification precede every persistent mint. Keeping the flow in one
|
|
2103
2313
|
// closure prevents a rejected eager create from bypassing live `deleting` authority or the OPFS commitment
|
|
2104
2314
|
// phase machine by jumping straight to `timedCreate()`.
|
|
2105
|
-
const openOwnedStore = async (): Promise<
|
|
2315
|
+
const openOwnedStore = async (): Promise<PgwasmClient> => {
|
|
2316
|
+
// ADR-0063: the build this path mints on must be the declared one, before any meta read or mint.
|
|
2317
|
+
assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
|
|
2106
2318
|
// A capability-denied browser may inherit an interrupted destroy or an unexposed candidate from an earlier
|
|
2107
2319
|
// granted engine home, and it may be looking at a store that lives in OPFS it cannot open at all. ONE
|
|
2108
2320
|
// bounded meta read settles all three before any replacement IDB store is minted: a `deleting` handoff
|
|
@@ -2151,29 +2363,34 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2151
2363
|
return timedCreate();
|
|
2152
2364
|
};
|
|
2153
2365
|
|
|
2154
|
-
let pglite:
|
|
2155
|
-
// Whether the boot adopted the caller's `
|
|
2366
|
+
let pglite: PgwasmClient;
|
|
2367
|
+
// Whether the boot adopted the caller's `precreatedPgwasm` (vs. falling back to a fresh create) — gates
|
|
2156
2368
|
// whether the provision stamp is honoured (ADR-0034).
|
|
2157
2369
|
let adoptedPrecreated = false;
|
|
2158
|
-
if (options.
|
|
2370
|
+
if (options.pgwasmInstance) {
|
|
2159
2371
|
// The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
|
|
2160
|
-
// (schema, prepare hooks, and reconciliation) — see the `
|
|
2161
|
-
// `
|
|
2162
|
-
refuseIfNonPersistent(options.
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2372
|
+
// (schema, prepare hooks, and reconciliation) — see the `pgwasmInstance` JSDoc. No create here →
|
|
2373
|
+
// `pgwasmCreateMs` null.
|
|
2374
|
+
refuseIfNonPersistent(options.pgwasmInstance);
|
|
2375
|
+
// ADR-0063: the adopted instance's own build must be the declared one.
|
|
2376
|
+
assertStoreBuild(declaredBuild, options.pgwasmInstance.build, "pgwasmInstance");
|
|
2377
|
+
pglite = options.pgwasmInstance;
|
|
2378
|
+
} else if (options.precreatedPgwasm) {
|
|
2379
|
+
// The caller created the raw store eagerly via `createPgwasmClient`; the client still owns every
|
|
2166
2380
|
// post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
|
|
2167
2381
|
// `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN
|
|
2168
2382
|
// branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,
|
|
2169
2383
|
// outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create
|
|
2170
2384
|
// that never produced a store).
|
|
2171
|
-
const outcome = await options.
|
|
2385
|
+
const outcome = await options.precreatedPgwasm.then(
|
|
2172
2386
|
(instance) => ({ ok: true as const, instance }),
|
|
2173
2387
|
(error: unknown) => ({ ok: false as const, error }),
|
|
2174
2388
|
);
|
|
2175
2389
|
if (outcome.ok) {
|
|
2176
2390
|
refuseIfNonPersistent(outcome.instance);
|
|
2391
|
+
// ADR-0063: checked outside the reject-fallback, so the refusal propagates (never swallowed as a
|
|
2392
|
+
// rejected create that falls back to minting on the supplied build).
|
|
2393
|
+
assertStoreBuild(declaredBuild, outcome.instance.build, "precreatedPgwasm");
|
|
2177
2394
|
pglite = outcome.instance;
|
|
2178
2395
|
adoptedPrecreated = true;
|
|
2179
2396
|
} else {
|
|
@@ -2198,10 +2415,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2198
2415
|
bootReportBuilder.setStorageFallbackReason(options.storageFallbackReason);
|
|
2199
2416
|
}
|
|
2200
2417
|
// ADR-0049 decision 12: a BYO instance / adopted-precreated store was created OUTSIDE the mint seam, so derive
|
|
2201
|
-
// its `storageBackend` from the instance's own
|
|
2202
|
-
//
|
|
2203
|
-
if (options.
|
|
2204
|
-
const byoBackend =
|
|
2418
|
+
// its `storageBackend` from the instance's own `storage` where recognisable; an unknown filesystem leaves it
|
|
2419
|
+
// omitted (`setStorageBackend` is first-wins, so a fallback-create is never clobbered).
|
|
2420
|
+
if (options.pgwasmInstance != null || adoptedPrecreated) {
|
|
2421
|
+
const byoBackend = storageBackendFromStorage(pglite.storage);
|
|
2205
2422
|
if (byoBackend) {
|
|
2206
2423
|
openedStorageBackend = byoBackend;
|
|
2207
2424
|
bootReportBuilder.setStorageBackend(byoBackend);
|
|
@@ -2214,20 +2431,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2214
2431
|
// run, and the memory test lane has no meta machinery at all. The bounded meta read is kicked off HERE and folded
|
|
2215
2432
|
// into `commitmentBarrierPending` at the milestone below, so it overlaps schema exec instead of preceding it.
|
|
2216
2433
|
const adoptedCommitmentGate =
|
|
2217
|
-
(options.
|
|
2218
|
-
backendOverride !== "memory" &&
|
|
2219
|
-
isOpfsRepackedPersistent(pglite)
|
|
2434
|
+
(options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pglite)
|
|
2220
2435
|
? resolveAdoptedCommitmentBarrier(fallbackStorePath)
|
|
2221
2436
|
: null;
|
|
2222
2437
|
// The gate's rejection is observed at the milestone (fail closed, invariant 12); this only keeps an unrelated
|
|
2223
2438
|
// earlier boot failure from surfacing it as an unhandled rejection in the meantime.
|
|
2224
2439
|
if (adoptedCommitmentGate) void adoptedCommitmentGate.catch(() => undefined);
|
|
2225
2440
|
// Whether THIS client owns the store's lifecycle (so `destroy()` may run the supervised destruction machine
|
|
2226
|
-
// over it). A BYO `
|
|
2227
|
-
const ownsStoreLifecycle = !options.
|
|
2441
|
+
// over it). A BYO `pgwasmInstance` is the caller's to dispose of; every other provenance is ours.
|
|
2442
|
+
const ownsStoreLifecycle = !options.pgwasmInstance;
|
|
2228
2443
|
|
|
2229
2444
|
// Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
|
|
2230
|
-
// its create timing, report the spare's initdb cost + how long it sat ready, and leave `
|
|
2445
|
+
// its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgwasmCreateMs`
|
|
2231
2446
|
// null (the create was paid at provision time, off this boot's clock).
|
|
2232
2447
|
if (adoptedPrecreated && options.provisionStamp) {
|
|
2233
2448
|
const stamp = await options.provisionStamp.catch(() => null);
|
|
@@ -2398,7 +2613,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2398
2613
|
},
|
|
2399
2614
|
});
|
|
2400
2615
|
|
|
2401
|
-
if (!options.
|
|
2616
|
+
if (!options.pgwasmInstance) {
|
|
2402
2617
|
if (options.prepareLocalDbBeforeSchema) {
|
|
2403
2618
|
const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
|
|
2404
2619
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
@@ -2466,8 +2681,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2466
2681
|
registry: options.registry,
|
|
2467
2682
|
batchWriteUrl: options.batchWriteUrl,
|
|
2468
2683
|
// pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
|
|
2469
|
-
// supplied their own
|
|
2470
|
-
ownsMetaTable: !options.
|
|
2684
|
+
// supplied their own pgwasm — then the marker is never touched and recovery runs unconditionally.
|
|
2685
|
+
ownsMetaTable: !options.pgwasmInstance,
|
|
2471
2686
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
2472
2687
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
2473
2688
|
...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
|
|
@@ -2482,11 +2697,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2482
2697
|
// no driver is stood up), so there is no conditional to get wrong when a registry gains its first stream.
|
|
2483
2698
|
// The ingestion endpoint is the mutation endpoint's sibling — derived from `batchWriteUrl` unless the
|
|
2484
2699
|
// consumer names it — and it shares the write path's headers (same ingress, same gateway credentials).
|
|
2485
|
-
// A caller-owned
|
|
2700
|
+
// A caller-owned pgwasm (`pgwasmInstance`) never had the toolkit's schema applied, so the Outbox table may
|
|
2486
2701
|
// not exist: the lane stays unconstructed there, exactly as the meta-table marker is left alone.
|
|
2487
2702
|
const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
|
|
2488
2703
|
const eventLane: EventLaneRuntime | null =
|
|
2489
|
-
eventLaneUrl != null && !options.
|
|
2704
|
+
eventLaneUrl != null && !options.pgwasmInstance
|
|
2490
2705
|
? createEventLaneRuntime({
|
|
2491
2706
|
db: pglite,
|
|
2492
2707
|
registry: options.registry,
|
|
@@ -2502,7 +2717,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2502
2717
|
throw new Error(
|
|
2503
2718
|
"pgxsinkit: the Event lane is not available on this client — either `batchWriteUrl` is not the canonical " +
|
|
2504
2719
|
'"…/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' +
|
|
2505
|
-
"`
|
|
2720
|
+
"`pgwasmInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
|
|
2506
2721
|
);
|
|
2507
2722
|
};
|
|
2508
2723
|
|
|
@@ -2522,13 +2737,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2522
2737
|
// quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
|
|
2523
2738
|
const runBootRecoveryStage = async (): Promise<void> => {
|
|
2524
2739
|
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
|
|
2525
|
-
mutationRuntime.runBootRecovery({ ownsMetaTable: !options.
|
|
2740
|
+
mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgwasmInstance, restore: restoreBoot }),
|
|
2526
2741
|
);
|
|
2527
2742
|
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
2528
2743
|
};
|
|
2529
2744
|
|
|
2530
2745
|
const runReconcileStage = async (): Promise<void> => {
|
|
2531
|
-
if (options.
|
|
2746
|
+
if (options.pgwasmInstance) return;
|
|
2532
2747
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
|
|
2533
2748
|
reconcileLocalStoreVersion({
|
|
2534
2749
|
db: pglite,
|
|
@@ -2577,7 +2792,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2577
2792
|
// still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
|
|
2578
2793
|
// each stage boundary — before setting `isRunning`, before starting sync — so no shape stream starts after a
|
|
2579
2794
|
// stop; and `stop`/`destroy` await `bootSettled` before teardown so the tail can never exec against a
|
|
2580
|
-
// closing
|
|
2795
|
+
// closing pgwasm.
|
|
2581
2796
|
let disposed = false;
|
|
2582
2797
|
// Resolves the moment `sync` is wired (and the activation buffer replayed); rejects if the boot is disposed
|
|
2583
2798
|
// or the tail fails before wiring — so a read seam awaiting it in the pre-wire window unblocks rather than
|
|
@@ -2600,7 +2815,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2600
2815
|
// called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails
|
|
2601
2816
|
// at its next stage boundary (never starting sync after this), gracefully release any read seam parked on
|
|
2602
2817
|
// `syncWired` (it then falls through to the local-only path), then AWAIT `bootSettled` — swallowing a tail
|
|
2603
|
-
// failure — so the tail has fully SETTLED before teardown touches the engine/
|
|
2818
|
+
// failure — so the tail has fully SETTLED before teardown touches the engine/pgwasm. Any sync the tail did
|
|
2604
2819
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
2605
2820
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
2606
2821
|
disposed = true;
|
|
@@ -3177,7 +3392,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3177
3392
|
// The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
|
|
3178
3393
|
// `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
|
|
3179
3394
|
// drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
|
|
3180
|
-
// the attach client's Drizzle-over-bridge routes reads here. Returns the full
|
|
3395
|
+
// the attach client's Drizzle-over-bridge routes reads here. Returns the full pgwasm `Results` so drizzle's
|
|
3181
3396
|
// own result mapping runs on the tab.
|
|
3182
3397
|
const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
|
|
3183
3398
|
await gateAndGuardRead(sql, use);
|
|
@@ -3196,7 +3411,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3196
3411
|
|
|
3197
3412
|
const client: SyncClient<TRegistry> = {
|
|
3198
3413
|
drizzle: drizzleDb,
|
|
3199
|
-
pglite,
|
|
3414
|
+
pgwasm: pglite,
|
|
3200
3415
|
views: buildViews(options.registry),
|
|
3201
3416
|
tables: Object.fromEntries(
|
|
3202
3417
|
Object.keys(options.registry).map((tableKey) => [
|
|
@@ -3226,9 +3441,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3226
3441
|
haltActivity();
|
|
3227
3442
|
// ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
|
|
3228
3443
|
// and await its settlement — so no shape stream is left running and nothing execs against the closing
|
|
3229
|
-
//
|
|
3444
|
+
// pgwasm. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
|
|
3230
3445
|
await quiesceTailForTeardown();
|
|
3231
|
-
// Await any in-flight convergence pass before closing
|
|
3446
|
+
// Await any in-flight convergence pass before closing pgwasm, so a pass never queries a
|
|
3232
3447
|
// closed handle. The Event-lane flush pass is awaited on the same rule, for the same reason.
|
|
3233
3448
|
await convergenceDriver?.stop();
|
|
3234
3449
|
await eventFlushDriver?.stop();
|
|
@@ -3239,7 +3454,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3239
3454
|
// point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
|
|
3240
3455
|
// preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
|
|
3241
3456
|
sync?.unsubscribe();
|
|
3242
|
-
// Dispose the live-query manager before closing
|
|
3457
|
+
// Dispose the live-query manager before closing pgwasm (ADR-0040 decisions 1 & 6): it cancels any
|
|
3243
3458
|
// keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
|
|
3244
3459
|
await liveManager.dispose();
|
|
3245
3460
|
await pglite.close();
|
|
@@ -3273,7 +3488,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3273
3488
|
// ADR-0053 decision 8: the same refusal, for the Event lane's durable state. A non-empty Outbox
|
|
3274
3489
|
// holds events the SERVER has not yet ruled on, and "never discard without a server verdict" is
|
|
3275
3490
|
// exactly what at-least-once means on this edge — so a non-forced destroy refuses here too,
|
|
3276
|
-
// naming the Outbox so the two causes are never confused.
|
|
3491
|
+
// naming the Outbox so the two causes are never confused. Rows the acked ledger is retaining
|
|
3492
|
+
// (ADR-0060) have HAD their verdict, so they are not "empty: false" and never block a destroy.
|
|
3277
3493
|
if (eventLane && !(await eventLane.outboxStatus()).empty) {
|
|
3278
3494
|
throw new Error(
|
|
3279
3495
|
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
@@ -3293,7 +3509,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3293
3509
|
// Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
|
|
3294
3510
|
// the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
|
|
3295
3511
|
sync?.unsubscribe();
|
|
3296
|
-
// Dispose the live-query manager before closing
|
|
3512
|
+
// Dispose the live-query manager before closing pgwasm — same close-vs-unsubscribe hang guard as
|
|
3297
3513
|
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
3298
3514
|
await liveManager.dispose();
|
|
3299
3515
|
await pglite.close();
|
|
@@ -3301,7 +3517,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3301
3517
|
// now finish the store-meta / OPFS-namespace side. Every recorded browser store runs the full destructive
|
|
3302
3518
|
// lifecycle (set `deleting` → delete commitment
|
|
3303
3519
|
// sentinel → delete both possible backend stores → delete meta). Wiping application tables and closing
|
|
3304
|
-
//
|
|
3520
|
+
// pgwasm do NOT delete its IndexedDB database; retaining that shell would make the next granted boot
|
|
3305
3521
|
// classify it as an existing recordless idb store instead of a genuinely fresh path. A recordless lifecycle-owned
|
|
3306
3522
|
// IDB store therefore enters the same machine; memory, filesystem, non-browser, and caller-owned stores
|
|
3307
3523
|
// have no toolkit browser authority to finish.
|
|
@@ -3413,8 +3629,37 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3413
3629
|
mutations: undefined as unknown as MutationsApi<TRegistry>,
|
|
3414
3630
|
// Inspection surface (see the interface doc): straight through to the underlying store, no journal /
|
|
3415
3631
|
// overlay involvement. The worker facade runs the identical call inside the worker's own client.
|
|
3416
|
-
|
|
3417
|
-
|
|
3632
|
+
// `options.blob` is the single-statement COPY form: the bytes are wrapped into the `Blob` pgwasm reads
|
|
3633
|
+
// from `/dev/blob` (see {@link toPgliteQueryOptions}) — a bulk load that needs no transaction around it.
|
|
3634
|
+
rawQuery: (sql, params, options) =>
|
|
3635
|
+
pglite.query(sql, params as unknown[] | undefined, toPgliteQueryOptions(options)),
|
|
3636
|
+
// `rawExec` takes no blob: pgwasm's `exec` runs a multi-statement script through the simple protocol,
|
|
3637
|
+
// which has no `/dev/blob` hook — a COPY-from-blob load goes through `rawQuery`/`rawTransaction`.
|
|
3638
|
+
rawExec: (sql, options) => pglite.exec(sql, withoutCopyBlob(options)),
|
|
3639
|
+
// The atomic form of the same surface. `pglite.transaction` opens ONE transaction and rolls it back on a
|
|
3640
|
+
// throw, so the all-or-nothing guarantee is the store's, not a re-implementation here. An empty list is
|
|
3641
|
+
// answered without touching the store at all — an empty transaction would be pure overhead on the single
|
|
3642
|
+
// WASM thread (and, in worker mode, would serialise behind whatever else the engine is doing).
|
|
3643
|
+
rawTransaction: async (statements, options) => {
|
|
3644
|
+
if (statements.length === 0) {
|
|
3645
|
+
return [];
|
|
3646
|
+
}
|
|
3647
|
+
return pglite.transaction(async (tx) => {
|
|
3648
|
+
const results: Results[] = [];
|
|
3649
|
+
for (const statement of statements) {
|
|
3650
|
+
// A statement carrying `blob` is a `COPY … FROM '/dev/blob'` bulk load: its bytes become the
|
|
3651
|
+
// `Blob` pgwasm reads, for THAT statement only. Every other statement is unaffected.
|
|
3652
|
+
results.push(
|
|
3653
|
+
await tx.query(
|
|
3654
|
+
statement.sql,
|
|
3655
|
+
statement.params as unknown[] | undefined,
|
|
3656
|
+
toPgliteQueryOptions(options, statement.blob),
|
|
3657
|
+
),
|
|
3658
|
+
);
|
|
3659
|
+
}
|
|
3660
|
+
return results;
|
|
3661
|
+
});
|
|
3662
|
+
},
|
|
3418
3663
|
// @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
|
|
3419
3664
|
guardedRawQuery,
|
|
3420
3665
|
query: (build) => runGuardedQuery(build),
|
|
@@ -3442,7 +3687,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3442
3687
|
// per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
|
|
3443
3688
|
// public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
|
|
3444
3689
|
// identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
|
|
3445
|
-
// exactly as the inline seam was:
|
|
3690
|
+
// exactly as the inline seam was: pgwasm's `live.query` + the manager's value-identity diff.
|
|
3446
3691
|
subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
|
|
3447
3692
|
// Read gate (ADR-0041): do not register a live query before the local-read core has finished (a
|
|
3448
3693
|
// settled-promise await on the steady-state client — cheap, and stage-2-safe).
|
|
@@ -3498,7 +3743,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3498
3743
|
unsubscribe: () => {
|
|
3499
3744
|
unsubscribed = true;
|
|
3500
3745
|
// Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
|
|
3501
|
-
// `stop()`/`destroy()`) awaits it before closing
|
|
3746
|
+
// `stop()`/`destroy()`) awaits it before closing pgwasm (ADR-0040 decision 1 — the close race).
|
|
3502
3747
|
void subscription.unsubscribe();
|
|
3503
3748
|
},
|
|
3504
3749
|
...(lazyTables.length > 0 ? { lazyTables } : {}),
|
|
@@ -3515,7 +3760,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3515
3760
|
// Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
|
|
3516
3761
|
// take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
|
|
3517
3762
|
await ready;
|
|
3518
|
-
// Name the backup from the configured plain store PATH (ADR-0036), never the
|
|
3763
|
+
// Name the backup from the configured plain store PATH (ADR-0036), never the pgwasm instance's
|
|
3519
3764
|
// resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name
|
|
3520
3765
|
// as something to imitate. The store id is the path's last segment (see `deriveStoreId`).
|
|
3521
3766
|
return lifecycleSlot.run("exportStore", () =>
|
|
@@ -3558,7 +3803,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3558
3803
|
return lifecycleSlot.run("exportData", () =>
|
|
3559
3804
|
performDataExport(
|
|
3560
3805
|
{
|
|
3561
|
-
pglite,
|
|
3806
|
+
pgwasm: pglite,
|
|
3562
3807
|
readMutationStats: () => mutationRuntime.readMutationStats(),
|
|
3563
3808
|
flush: () => mutationRuntime.flush(),
|
|
3564
3809
|
syncedTableNames: collectDataExportSyncedTableNames(options.registry),
|
|
@@ -3666,7 +3911,7 @@ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry:
|
|
|
3666
3911
|
return [...new Set(keys)];
|
|
3667
3912
|
}
|
|
3668
3913
|
|
|
3669
|
-
async function resetSubscriptionsIfRequested(pglite:
|
|
3914
|
+
async function resetSubscriptionsIfRequested(pglite: PgwasmClient, keys: string[] | undefined) {
|
|
3670
3915
|
if (!keys || keys.length === 0) {
|
|
3671
3916
|
return;
|
|
3672
3917
|
}
|
|
@@ -3686,17 +3931,12 @@ async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[
|
|
|
3686
3931
|
}
|
|
3687
3932
|
|
|
3688
3933
|
function createDrizzleDatabase<TRegistry extends SyncTableRegistry>(
|
|
3689
|
-
client:
|
|
3934
|
+
client: PgwasmClient,
|
|
3690
3935
|
schema: RegistryTables<TRegistry>,
|
|
3691
3936
|
) {
|
|
3692
3937
|
const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
|
|
3693
3938
|
|
|
3694
|
-
|
|
3695
|
-
client: ClientPGlite;
|
|
3696
|
-
relations: RegistryRelations<TRegistry>;
|
|
3697
|
-
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3698
|
-
|
|
3699
|
-
return createDatabase({ client, relations });
|
|
3939
|
+
return drizzle(client, { relations });
|
|
3700
3940
|
}
|
|
3701
3941
|
|
|
3702
3942
|
function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
@@ -3717,15 +3957,15 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
|
3717
3957
|
* identically. The `client` argument is the executor Drizzle runs against:
|
|
3718
3958
|
* - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
|
|
3719
3959
|
* and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
|
|
3720
|
-
* - Pass a `
|
|
3960
|
+
* - Pass a `PgwasmClient`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
|
|
3721
3961
|
* that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
|
|
3722
3962
|
* queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
|
|
3723
3963
|
*/
|
|
3724
3964
|
export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
3725
3965
|
registry: TRegistry,
|
|
3726
|
-
client:
|
|
3966
|
+
client: PgwasmClient = {} as PgwasmClient,
|
|
3727
3967
|
): {
|
|
3728
|
-
drizzle:
|
|
3968
|
+
drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
3729
3969
|
views: RegistryViews<TRegistry>;
|
|
3730
3970
|
/**
|
|
3731
3971
|
* A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
|
|
@@ -3733,7 +3973,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
|
3733
3973
|
* without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
|
|
3734
3974
|
* bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
|
|
3735
3975
|
*/
|
|
3736
|
-
drizzleFor: (client:
|
|
3976
|
+
drizzleFor: (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
3737
3977
|
} {
|
|
3738
3978
|
const drizzleFor = buildRegistryDrizzleFactory(registry);
|
|
3739
3979
|
return {
|
|
@@ -3751,11 +3991,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
|
3751
3991
|
*/
|
|
3752
3992
|
function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
|
|
3753
3993
|
registry: TRegistry,
|
|
3754
|
-
): (client:
|
|
3994
|
+
): (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>> {
|
|
3755
3995
|
const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
|
|
3756
|
-
|
|
3757
|
-
client: ClientPGlite;
|
|
3758
|
-
relations: RegistryRelations<TRegistry>;
|
|
3759
|
-
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3760
|
-
return (client) => createDatabase({ client, relations });
|
|
3996
|
+
return (client) => drizzle(client, { relations });
|
|
3761
3997
|
}
|