@pgxsinkit/client 0.2.7 → 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 +11 -3
- package/dist/boot-report.d.ts +11 -8
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +39 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +96 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.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 +237 -113
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7037 -6665
- package/dist/index.js.map +46 -43
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +59 -1
- 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 +17 -25
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +84 -8
- 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/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +26 -7
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +4 -3
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +27 -14
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +52 -19
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.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 -9
- package/skills/core/SKILL.md +145 -63
- package/skills/operating/SKILL.md +221 -221
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +13 -12
- package/src/circuits/envelope-to-change.ts +211 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +191 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +643 -0
- package/src/debug.ts +1 -85
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +24 -28
- package/src/export-store.ts +17 -17
- package/src/index.ts +797 -544
- package/src/lazy-guard.ts +1 -1
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +76 -5
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +126 -29
- 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 +104 -156
- package/src/sync/copy.ts +116 -21
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +43 -2
- package/src/sync/subscription-state.ts +28 -10
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +4 -4
- package/src/worker/attach-sync-client.ts +150 -57
- package/src/worker/define-sync-worker.ts +325 -87
- package/src/worker/engine-control.ts +89 -0
- 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/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
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 {
|
|
@@ -11,7 +7,6 @@ import type {
|
|
|
11
7
|
RegistryRelations,
|
|
12
8
|
RegistryTables,
|
|
13
9
|
RegistryViews,
|
|
14
|
-
SyncConfigInput,
|
|
15
10
|
SyncRuntimeStatus,
|
|
16
11
|
SyncTableCreateInput,
|
|
17
12
|
SyncTableEntry,
|
|
@@ -19,22 +14,35 @@ import type {
|
|
|
19
14
|
SyncTableName,
|
|
20
15
|
SyncTableRegistry,
|
|
21
16
|
SyncTableUpdateInput,
|
|
17
|
+
StorageBuild,
|
|
22
18
|
StorageDurability,
|
|
19
|
+
StoreBuildCheckSite,
|
|
23
20
|
WriteMode,
|
|
24
21
|
} from "@pgxsinkit/contracts";
|
|
25
22
|
import {
|
|
26
23
|
fingerprintRegistry,
|
|
27
|
-
getSyncRegistrySchema,
|
|
28
24
|
getSyncRegistryStorage,
|
|
29
25
|
isClaimsDependentRowFilter,
|
|
30
26
|
resolveStorageDeclaration,
|
|
31
27
|
} from "@pgxsinkit/contracts";
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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";
|
|
36
43
|
|
|
37
44
|
import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
|
|
45
|
+
import { startCircuitsSync, type CircuitsGroupSyncResult } from "./circuits/group-sync";
|
|
38
46
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
39
47
|
import { syncDebug, timeAsync } from "./debug";
|
|
40
48
|
import { describeErrorChain } from "./error-chain";
|
|
@@ -91,7 +99,6 @@ import {
|
|
|
91
99
|
generateEphemeralLocalSchemaSql,
|
|
92
100
|
generateLocalSchemaSql,
|
|
93
101
|
} from "./schema";
|
|
94
|
-
import { startConfiguredSync } from "./shape-sync";
|
|
95
102
|
import {
|
|
96
103
|
resolveDeniedBootAuthority,
|
|
97
104
|
type ResolveStoreBootOptions,
|
|
@@ -99,6 +106,7 @@ import {
|
|
|
99
106
|
type ResolvedStorageBackend,
|
|
100
107
|
type StoreBootResolution,
|
|
101
108
|
} from "./store-boot";
|
|
109
|
+
import { assertStoreBuild, isStoreBuildRefusal } from "./store-build";
|
|
102
110
|
import { runCommitmentBarrier } from "./store-lifecycle";
|
|
103
111
|
import {
|
|
104
112
|
META_STORE_UNAVAILABLE,
|
|
@@ -107,8 +115,9 @@ import {
|
|
|
107
115
|
type StoreMetaDeps,
|
|
108
116
|
writeStoreMetaRecord,
|
|
109
117
|
} from "./store-meta";
|
|
118
|
+
import { acquireStoreOwnership } from "./store-ownership-lock";
|
|
110
119
|
import {
|
|
111
|
-
|
|
120
|
+
classifyNonPersistentStorage,
|
|
112
121
|
NonPersistentStoreError,
|
|
113
122
|
normaliseStorePathInput,
|
|
114
123
|
readTestStoreMarker,
|
|
@@ -117,8 +126,8 @@ import {
|
|
|
117
126
|
storeTargetExists,
|
|
118
127
|
type StorePathInput,
|
|
119
128
|
} from "./store-path";
|
|
120
|
-
import {
|
|
121
|
-
import {
|
|
129
|
+
import { DEFAULT_METADATA_SCHEMA } from "./sync/metadata-tables";
|
|
130
|
+
import { deleteSubscriptionState, migrateSubscriptionMetadataTables } from "./sync/subscription-state";
|
|
122
131
|
import { LiveRowsMaterializer } from "./worker/live-diff";
|
|
123
132
|
import {
|
|
124
133
|
createLiveQueryManager,
|
|
@@ -214,8 +223,15 @@ export {
|
|
|
214
223
|
type EngineRelocatedOutcome,
|
|
215
224
|
type ExecutionLimitConfig,
|
|
216
225
|
ExecutionLimitMismatchError,
|
|
226
|
+
PROVISION_STALLED_CODE,
|
|
227
|
+
// The typed refusal a stalled spare-store adoption raises — the companion to `ProvisionExpiredError`
|
|
228
|
+
// above: that one bounds the PROVISION call, this one bounds an ATTACH waiting on the spare.
|
|
229
|
+
ProvisionStalledError,
|
|
230
|
+
provisionStalledFromWire,
|
|
231
|
+
type ProvisionStalledWire,
|
|
217
232
|
} from "./worker/engine-control";
|
|
218
233
|
export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
|
|
234
|
+
export { STORE_OWNERSHIP_WAIT_MS, StoreOwnershipWaitError } from "./store-ownership-lock";
|
|
219
235
|
export {
|
|
220
236
|
COMMITTED_STORE_UNREACHABLE_CODE,
|
|
221
237
|
CommittedStoreUnreachableError,
|
|
@@ -226,6 +242,15 @@ export {
|
|
|
226
242
|
type ResolveStoreBootOptions,
|
|
227
243
|
type StoreBootResolution,
|
|
228
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";
|
|
229
254
|
export {
|
|
230
255
|
InvalidStorePathError,
|
|
231
256
|
NonPersistentStoreError,
|
|
@@ -243,7 +268,7 @@ export {
|
|
|
243
268
|
createConvergenceDriver,
|
|
244
269
|
createIntervalConvergenceTrigger,
|
|
245
270
|
} from "./convergence";
|
|
246
|
-
export {
|
|
271
|
+
export { setSyncDebugSink, syncDebug, timeAsync } from "./debug";
|
|
247
272
|
export {
|
|
248
273
|
type AttachedSyncClient,
|
|
249
274
|
attachSyncClient,
|
|
@@ -301,6 +326,47 @@ export {
|
|
|
301
326
|
// The Outbox's object NAMES are public contract like its shape (ADR-0053 decision 2) — inspection
|
|
302
327
|
// surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
|
|
303
328
|
export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
|
|
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
|
+
|
|
343
|
+
// The Circuits-native read transport (ADR-0055 decision 10). Reads terminate on durable-streams
|
|
344
|
+
// through the edge; everything above the transport stays ours.
|
|
345
|
+
export { createTokenRecovery, readShapeStream, STREAM_START } from "./circuits/stream-source";
|
|
346
|
+
export type { ShapeStreamSubscription, StreamBatch, StreamSourceOptions } from "./circuits/stream-source";
|
|
347
|
+
export { createShapeGroup } from "./circuits/shape-group";
|
|
348
|
+
export type { GroupShapeSpec, ShapeGroup, ShapeGroupBatch, ShapeGroupOptions } from "./circuits/shape-group";
|
|
349
|
+
export { envelopeToChange, primaryKeyFromStreamKey } from "./circuits/envelope-to-change";
|
|
350
|
+
export type { ChangeLike } from "./circuits/envelope-to-change";
|
|
351
|
+
export { StreamInbox } from "./circuits/stream-inbox";
|
|
352
|
+
export type { BufferedBatch } from "./circuits/stream-inbox";
|
|
353
|
+
export { createBarrierReader, openSubscriptionSession } from "./circuits/subscription-client";
|
|
354
|
+
export type {
|
|
355
|
+
GrantedStream,
|
|
356
|
+
RefusedStream,
|
|
357
|
+
ShapeSubscriptionRequest,
|
|
358
|
+
SubscriptionClientOptions,
|
|
359
|
+
SubscriptionSession,
|
|
360
|
+
} from "./circuits/subscription-client";
|
|
361
|
+
export { startCircuitsSync } from "./circuits/group-sync";
|
|
362
|
+
export type { CircuitsGroupSyncOptions, CircuitsGroupSyncResult, CircuitsTableSyncResult } from "./circuits/group-sync";
|
|
363
|
+
export { syncCircuitsShapes } from "./circuits/sync-engine";
|
|
364
|
+
export type {
|
|
365
|
+
CircuitsShapeSpec,
|
|
366
|
+
CircuitsSyncHandle,
|
|
367
|
+
CircuitsSyncOptions,
|
|
368
|
+
ConvergenceBarrier,
|
|
369
|
+
} from "./circuits/sync-engine";
|
|
304
370
|
export {
|
|
305
371
|
type AllMutationsView,
|
|
306
372
|
getAllMutationsView,
|
|
@@ -359,40 +425,39 @@ export class ClientDisposedError extends Error {
|
|
|
359
425
|
}
|
|
360
426
|
}
|
|
361
427
|
|
|
362
|
-
// The store carries
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
//
|
|
366
|
-
export type
|
|
428
|
+
// The store carries pgwasm's own `live` extension and nothing else. The pgxsinkit sync runtime is not an
|
|
429
|
+
// extension at all (ADR-0032 S1): `createSyncClient` starts it BESIDE the store (`startCircuitsSync`)
|
|
430
|
+
// rather than attaching a namespace to the instance, so a store's type is exactly pgwasm + `live`
|
|
431
|
+
// whether or not sync ever runs on it.
|
|
432
|
+
export type PgwasmClient = PgwasmWithLive;
|
|
367
433
|
|
|
368
|
-
/**
|
|
369
|
-
|
|
370
|
-
* {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
|
|
371
|
-
* compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
|
|
372
|
-
* asset load — see the field's JSDoc for the accelerator geometry.
|
|
373
|
-
*/
|
|
374
|
-
export interface PgliteBootAssets {
|
|
375
|
-
pgliteWasmModule?: WebAssembly.Module;
|
|
376
|
-
initdbWasmModule?: WebAssembly.Module;
|
|
377
|
-
fsBundle?: Blob;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
/** Options for {@link createClientPGlite}. */
|
|
381
|
-
export interface CreateClientPGliteOptions {
|
|
434
|
+
/** Options for {@link createPgwasmClient}. */
|
|
435
|
+
export interface CreatePgwasmClientOptions {
|
|
382
436
|
/**
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
* 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.
|
|
386
440
|
*/
|
|
387
|
-
|
|
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;
|
|
388
453
|
/**
|
|
389
454
|
* @internal Toolkit-internal durability carrier (ADR-0047), NOT a public per-open knob. Durability is
|
|
390
455
|
* registry-declared: {@link createSyncClient} resolves `storage.durability ?? "relaxed"` off its registry
|
|
391
456
|
* and threads the resolved mode in here — the ONE resolution point — for every mint it funnels through this
|
|
392
457
|
* factory (its own boot, the worker provision/spare mint, the pre-expose idb drain read). Defaults to
|
|
393
|
-
* `"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
|
|
394
459
|
* returns before the whole-datadir snapshot flush and schedules it asynchronously; strict keeps that
|
|
395
|
-
* 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
|
|
396
461
|
* awaited host path: relaxed routine sync asserts health without an ordinary physical flush, while strict
|
|
397
462
|
* flushes arena data before metadata. Initialization, activation, and open-state close retain strict
|
|
398
463
|
* ordering in both OPFS modes.
|
|
@@ -406,10 +471,10 @@ export interface CreateClientPGliteOptions {
|
|
|
406
471
|
backendOverride?: "memory";
|
|
407
472
|
/**
|
|
408
473
|
* A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
|
|
409
|
-
* produced by {@link SyncClient.exportStore}. Passed straight to
|
|
474
|
+
* produced by {@link SyncClient.exportStore}. Passed straight to pgwasm's `loadDataDir`, so the created
|
|
410
475
|
* store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
|
|
411
476
|
* has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
|
|
412
|
-
* 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.
|
|
413
478
|
*/
|
|
414
479
|
restoreFrom?: File | Blob;
|
|
415
480
|
/**
|
|
@@ -422,12 +487,14 @@ export interface CreateClientPGliteOptions {
|
|
|
422
487
|
/**
|
|
423
488
|
* @internal ADR-0049 step 10a: the opfs-repacked factory + store-directory seam, injectable so Bun unit
|
|
424
489
|
* tests exercise the `opfs://` branch WITHOUT loading real WASM/OPFS. In production both default to the real
|
|
425
|
-
* implementations (`
|
|
490
|
+
* implementations (`createOpfsPgwasm` via a lazy `import()`, and the OPFS effects' store directory
|
|
426
491
|
* handle). Never consumer-facing.
|
|
427
492
|
*/
|
|
428
|
-
|
|
429
|
-
/** The
|
|
430
|
-
|
|
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 }>>;
|
|
431
498
|
/** The create-if-absent store directory handle for the factory; defaults to the real OPFS effects. */
|
|
432
499
|
getStoreDirectoryHandle?: () => Promise<unknown>;
|
|
433
500
|
/** Backoff between bounded open retries (ms); defaults to a small real delay. Tests pass `0`. */
|
|
@@ -451,43 +518,62 @@ const OPFS_OPEN_BACKOFF_MS = 100;
|
|
|
451
518
|
/** The opfs-repacked store extent size (ADR-0049 step 10a). */
|
|
452
519
|
const OPFS_STORE_EXTENT_SIZE = 65536;
|
|
453
520
|
/**
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
|
|
458
|
-
const READ_STREAM_UNREACHABLE = "read stream unreachable: a shape fetch failed and is retrying with backoff";
|
|
459
|
-
/**
|
|
460
|
-
* Default {@link CreateSyncClientOptions.readSilenceMs}. A healthy Electric read path is never silent —
|
|
461
|
-
* the live long-poll cycles roughly every 20-25s with at least a bare up-to-date, and every cycle fires
|
|
462
|
-
* `onSyncActivity` — so two full cycles of nothing while claiming `ready` is evidence, not caution.
|
|
521
|
+
* Default {@link CreateSyncClientOptions.readSilenceMs}. A healthy read path is never silent — the live
|
|
522
|
+
* long-poll returns on every hold, `204` with `stream-up-to-date` when nothing arrived, and every
|
|
523
|
+
* response fires `onSyncActivity` — so two full cycles of nothing while claiming `ready` is evidence,
|
|
524
|
+
* not caution.
|
|
463
525
|
*/
|
|
464
526
|
const READ_SILENCE_MS = 45_000;
|
|
465
527
|
/** `status.lastError` for the read-silence watchdog: nothing failed — that is exactly the problem. */
|
|
466
528
|
const READ_STREAM_SILENT = "read stream silent: no server response inside the silence window while reporting ready";
|
|
529
|
+
/** `status.lastError` while subscribe keeps failing for a reason the subject cannot act on. */
|
|
530
|
+
const CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is failing and retrying";
|
|
531
|
+
/**
|
|
532
|
+
* `status.lastError` while a live read has died and its group is re-subscribing (ADR-0056 decision 7,
|
|
533
|
+
* backlog 0010). Distinct from {@link READ_STREAM_SILENT}, which is the opposite evidence: nothing
|
|
534
|
+
* failed, and that is the problem.
|
|
535
|
+
*/
|
|
536
|
+
const STREAM_LOST = "read stream lost; re-subscribing";
|
|
467
537
|
/**
|
|
468
|
-
*
|
|
469
|
-
*
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
* `precreatedPglite` (the provision-then-attach path). This brand lets the guard recognise it as PROVABLY
|
|
473
|
-
* 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.
|
|
474
542
|
*/
|
|
475
|
-
|
|
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";
|
|
476
550
|
|
|
477
551
|
/**
|
|
478
|
-
*
|
|
479
|
-
*
|
|
480
|
-
*
|
|
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.
|
|
481
555
|
*/
|
|
482
|
-
function
|
|
483
|
-
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;
|
|
484
569
|
}
|
|
485
570
|
|
|
486
571
|
/**
|
|
487
|
-
* 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,
|
|
488
573
|
* then propagate the last error — a committed store's final failure is HARD, and an uncommitted candidate's
|
|
489
|
-
* likewise propagates (the caller never exposes an unopened store).
|
|
490
|
-
*
|
|
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.
|
|
491
577
|
*/
|
|
492
578
|
async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: number): Promise<T> {
|
|
493
579
|
let lastError: unknown;
|
|
@@ -495,6 +581,7 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
|
|
|
495
581
|
try {
|
|
496
582
|
return await open();
|
|
497
583
|
} catch (error) {
|
|
584
|
+
if (isStoreBuildRefusal(error)) throw error;
|
|
498
585
|
lastError = error;
|
|
499
586
|
if (attempt < OPFS_OPEN_ATTEMPTS && backoffMs > 0) {
|
|
500
587
|
await new Promise<void>((resolve) => setTimeout(resolve, backoffMs * attempt));
|
|
@@ -505,47 +592,53 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
|
|
|
505
592
|
}
|
|
506
593
|
|
|
507
594
|
/**
|
|
508
|
-
* Create the raw local
|
|
509
|
-
* {@link createSyncClient} makes internally (the `
|
|
510
|
-
* consumption, and the `boot
|
|
595
|
+
* Create the raw local pgwasm store the sync client runs on — the SAME `pgwasm.create` call
|
|
596
|
+
* {@link createSyncClient} makes internally (the `live` extension, pre-warmed boot-asset
|
|
597
|
+
* consumption, and the `boot pgwasm.create` rail stamp), extracted so exactly one implementation exists
|
|
511
598
|
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
512
|
-
* instance to {@link CreateSyncClientOptions.
|
|
599
|
+
* instance to {@link CreateSyncClientOptions.precreatedPgwasm}: the client then owns schema exec, prepare
|
|
513
600
|
* hooks, journal recovery, and registry reconciliation, exactly as its own `storePath` path does.
|
|
514
601
|
*
|
|
515
602
|
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED from the engine home
|
|
516
603
|
* (capability-selected opfs-repacked with IndexedDB fallback in a browser, or the filesystem on Bun/Node);
|
|
517
604
|
* a scheme-bearing path throws {@link InvalidStorePathError}.
|
|
518
|
-
* Also accepts the testing helper's output (`
|
|
605
|
+
* Also accepts the testing helper's output (`createPgwasmClient(memoryStoreForTests("x"))`) so a test can
|
|
519
606
|
* mint a memory store without naming a backend.
|
|
520
607
|
*
|
|
521
608
|
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
522
609
|
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
523
610
|
* initdb (+ persistent-store open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
524
611
|
*
|
|
525
|
-
* `
|
|
526
|
-
*
|
|
612
|
+
* `build` is the Postgres build (see {@link CreateSyncClientOptions.build}); a `createCBuild({ assets })` whose
|
|
613
|
+
* warm rejects loads its own assets — never a failure.
|
|
527
614
|
*/
|
|
528
|
-
export async function
|
|
615
|
+
export async function createPgwasmClient(
|
|
529
616
|
store: StorePathInput,
|
|
530
|
-
options?:
|
|
531
|
-
): Promise<
|
|
617
|
+
options?: CreatePgwasmClientOptions,
|
|
618
|
+
): Promise<PgwasmClient> {
|
|
532
619
|
// Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),
|
|
533
|
-
// then derive the concrete
|
|
620
|
+
// then derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
|
|
534
621
|
// empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
|
|
535
622
|
const normalised = normaliseStorePathInput(store);
|
|
536
623
|
const storePath = normalised.storePath;
|
|
537
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
|
+
}
|
|
538
631
|
// An eager precreate is itself a store mint, so it passes the SAME pre-mint meta gate the ordinary
|
|
539
632
|
// createSyncClient path does before a denied browser home opens an IDB store: settle any durable `deleting`
|
|
540
633
|
// authority, retire an unexposed `opfs-candidate`, and REFUSE an `opfs-committed` store outright ({@link
|
|
541
634
|
// CommittedStoreUnreachableError}) — an eager tab-side precreate must never be the thing that mints an empty
|
|
542
635
|
// sibling over the committed store, nor one exposed beneath a record still claiming a candidate.
|
|
543
636
|
// Keeping this at the documented precreate factory protects callers outside defineSyncWorker; the worker
|
|
544
|
-
// 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.
|
|
545
638
|
if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
|
|
546
639
|
await resolveDeniedBootAuthority(storePath);
|
|
547
640
|
}
|
|
548
|
-
// Derive the concrete
|
|
641
|
+
// Derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
|
|
549
642
|
// Bun/Node → `file://`, the sanctioned test lane → `memory://`. A scheme-bearing/empty storePath throws here.
|
|
550
643
|
// ADR-0049 step 10a: when the caller threads the placement probe's grant (`hasOpfsSyncAccess`), the browser
|
|
551
644
|
// store resolves to `opfs://` and routes to the opfs-repacked factory below. Default (undefined/false) leaves
|
|
@@ -556,99 +649,113 @@ export async function createClientPGlite(
|
|
|
556
649
|
// Stamp the store's scheme on the boot rail (never the full path — it can carry an identity-specific store
|
|
557
650
|
// name): "idb:" / "file:" / "memory:".
|
|
558
651
|
const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
|
|
559
|
-
//
|
|
560
|
-
//
|
|
561
|
-
//
|
|
562
|
-
|
|
563
|
-
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;
|
|
564
656
|
// Durability (ADR-0047) is registry-declared and resolved by createSyncClient; the resolved mode is threaded
|
|
565
657
|
// in via the internal `durability` carrier. Every store minting path (createSyncClient's own create, the
|
|
566
|
-
// worker's default
|
|
658
|
+
// worker's default createStore factory, spare/prewarm mints) funnels through this function, so the
|
|
567
659
|
// `?? "relaxed"` here is the terminal fallback when no mode was threaded (e.g. an eager caller-owned
|
|
568
|
-
// precreate). Maps to
|
|
660
|
+
// precreate). Maps to pgwasm's `relaxedDurability` boolean (`"strict"` → false). On idb the per-query
|
|
569
661
|
// synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
|
|
570
662
|
const relaxedDurability = (options?.durability ?? "relaxed") !== "strict";
|
|
571
|
-
|
|
572
|
-
//
|
|
573
|
-
//
|
|
574
|
-
|
|
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
|
|
575
671
|
// unit test drives this branch with no real WASM/OPFS. Durability maps from the same `relaxedDurability`
|
|
576
672
|
// resolution above (ADR-0047's default logic is untouched): `relaxed` → the factory's `"relaxed"`, else
|
|
577
673
|
// `"strict"`. The open is retried a bounded number of times for transient failures, then propagates.
|
|
578
674
|
if (dataDir.startsWith("opfs://")) {
|
|
579
675
|
const opfsPglite = (await timeAsync(
|
|
580
|
-
"boot
|
|
676
|
+
"boot pgwasm.create",
|
|
581
677
|
async () => {
|
|
582
|
-
const
|
|
583
|
-
options?.
|
|
584
|
-
|
|
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
|
|
681
|
+
// it — indistinguishable from a lost worker. These four phase lines split the create into its long
|
|
682
|
+
// steps (module load, directory handle, handle acquisition, pgwasm boot), so a stall is attributable.
|
|
683
|
+
syncDebug("boot pgwasm.create phase", { phase: "module-loaded" });
|
|
585
684
|
const getStoreDirectoryHandle =
|
|
586
|
-
options?.
|
|
685
|
+
options?.opfsFactories?.getStoreDirectoryHandle ??
|
|
587
686
|
(() => createOpfsEffects(storePath).getStoreDirectoryHandle());
|
|
588
687
|
const directory = await getStoreDirectoryHandle();
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
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);
|
|
606
721
|
},
|
|
607
722
|
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
608
|
-
)) as
|
|
609
|
-
//
|
|
610
|
-
// non-persistent guard
|
|
611
|
-
try {
|
|
612
|
-
Object.defineProperty(opfsPglite, OPFS_REPACKED_PERSISTENT, {
|
|
613
|
-
value: true,
|
|
614
|
-
enumerable: false,
|
|
615
|
-
configurable: true,
|
|
616
|
-
});
|
|
617
|
-
} catch {
|
|
618
|
-
// A frozen/exotic instance — the guard still falls back to its dataDir classification (best-effort brand).
|
|
619
|
-
}
|
|
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).
|
|
620
726
|
return opfsPglite;
|
|
621
727
|
}
|
|
622
728
|
|
|
623
729
|
const pglite = (await timeAsync(
|
|
624
|
-
"boot
|
|
730
|
+
"boot pgwasm.create",
|
|
625
731
|
() => {
|
|
626
|
-
const createOptions:
|
|
627
|
-
|
|
732
|
+
const createOptions: PgwasmOptions<{ live: typeof live }> = {
|
|
733
|
+
build,
|
|
734
|
+
dataDir,
|
|
628
735
|
relaxedDurability,
|
|
629
|
-
// 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
|
|
630
737
|
// `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
|
|
631
738
|
// the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
|
|
632
739
|
// create (the store initdbs empty).
|
|
633
740
|
...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
|
|
634
|
-
// Only
|
|
635
|
-
// (ADR-0032 S1) — it
|
|
636
|
-
//
|
|
637
|
-
//
|
|
638
|
-
//
|
|
741
|
+
// Only pgwasm's own `live` extension is a create-time extension; the pgxsinkit sync runtime is NOT
|
|
742
|
+
// (ADR-0032 S1) — `createSyncClient` starts it beside the store, never on it. So a store minted here
|
|
743
|
+
// is deliberately SYNC-LESS by construction: a spare/pre-warmed store (e.g. the board's login-screen
|
|
744
|
+
// mint) carries no subscription session, no shape streams, and no open stream connections until it
|
|
745
|
+
// is claimed and handed to `createSyncClient`.
|
|
639
746
|
extensions: {
|
|
640
747
|
live,
|
|
641
748
|
},
|
|
642
749
|
};
|
|
643
|
-
// idb/file/memory take the dataDir-string form;
|
|
644
|
-
return
|
|
750
|
+
// idb/file/memory take the dataDir-string form; pgwasm's own scheme parser selects the backend.
|
|
751
|
+
return createPgwasm(createOptions);
|
|
645
752
|
},
|
|
646
753
|
// Stamp the resolved durability mode + store scheme so every boot-rail capture shows the mode and lane the
|
|
647
754
|
// store was created under (ADR-0047 diagnosability).
|
|
648
755
|
{ ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
|
|
649
|
-
//
|
|
650
|
-
//
|
|
651
|
-
)) 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;
|
|
652
759
|
return pglite;
|
|
653
760
|
}
|
|
654
761
|
|
|
@@ -699,7 +806,7 @@ export interface FreshBootResolution {
|
|
|
699
806
|
}
|
|
700
807
|
|
|
701
808
|
/**
|
|
702
|
-
* Map a resolved
|
|
809
|
+
* Map a resolved pgwasm dataDir URL to the ADR-0049 decision 12 `storageBackend` diagnostic — the inverse of
|
|
703
810
|
* {@link resolveStoreDataDir}'s scheme selection (`opfs://` → opfs-repacked, `idb://` → idbfs, `file://` →
|
|
704
811
|
* filesystem, `memory://` → memory). Used to stamp the BootReport at the single client-owned mint seam. Returns
|
|
705
812
|
* `undefined` for an unrecognised scheme (a BYO instance whose dataDir the toolkit never minted — e.g. an
|
|
@@ -714,6 +821,26 @@ function storageBackendFromDataDir(dataDir: string | undefined): NonNullable<Boo
|
|
|
714
821
|
return undefined;
|
|
715
822
|
}
|
|
716
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
|
+
|
|
717
844
|
/** Does a boot verdict stand up an UNCOMMITTED opfs candidate the commitment barrier must promote (invariant 3)? */
|
|
718
845
|
function verdictNeedsCommitmentBarrier(
|
|
719
846
|
verdict: StoreBootVerdict | undefined,
|
|
@@ -796,19 +923,18 @@ export async function resolveFreshBoot(
|
|
|
796
923
|
* for unit tests via {@link FreshCommitmentSeams}.
|
|
797
924
|
*/
|
|
798
925
|
/**
|
|
799
|
-
*
|
|
800
|
-
* requires it (data-before-authority, invariant 3); a store that
|
|
801
|
-
*
|
|
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.
|
|
802
929
|
*/
|
|
803
|
-
function resolveEngineStrictSync(pglite:
|
|
804
|
-
|
|
805
|
-
if (typeof strictSync !== "function") {
|
|
930
|
+
function resolveEngineStrictSync(pglite: PgwasmClient): () => Promise<void> {
|
|
931
|
+
if (!isOpfsRepackedStore(pglite)) {
|
|
806
932
|
throw new Error(
|
|
807
|
-
"[pgxsinkit] fresh commitment: the
|
|
808
|
-
"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).",
|
|
809
935
|
);
|
|
810
936
|
}
|
|
811
|
-
return () => strictSync
|
|
937
|
+
return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pglite);
|
|
812
938
|
}
|
|
813
939
|
|
|
814
940
|
export async function runFreshCommitmentBarrier(
|
|
@@ -831,11 +957,11 @@ export async function runFreshCommitmentBarrier(
|
|
|
831
957
|
}
|
|
832
958
|
|
|
833
959
|
/**
|
|
834
|
-
* @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`
|
|
835
|
-
* `
|
|
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
|
|
836
962
|
* {@link resolveFreshBoot} never runs and nothing flags the barrier. Left alone, an adopted OPFS store therefore
|
|
837
963
|
* stays UNCOMMITTED for its whole life: no sentinel, and a record still at `opfs-candidate` (or absent, when the
|
|
838
|
-
* 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
|
|
839
965
|
* from a torn candidate, so the next client-owned boot classifies `delete-candidate-and-rebuild` and DESTROYS a
|
|
840
966
|
* populated store — offline, with nothing to rebuild from. An adopted opfs boot therefore owes the SAME barrier
|
|
841
967
|
* ({@link runFreshCommitmentBarrier}) a fresh one does, pre-expose (invariant 3).
|
|
@@ -921,7 +1047,23 @@ export async function fallbackVirginCandidateToIdb(
|
|
|
921
1047
|
|
|
922
1048
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
923
1049
|
registry: TRegistry;
|
|
924
|
-
|
|
1050
|
+
/**
|
|
1051
|
+
* The pgxsinkit control plane: where a client subscribes, re-mints its stream token, and reads the
|
|
1052
|
+
* engine convergence barrier (ADR-0055). Required, with {@link streamBaseUrl}.
|
|
1053
|
+
*
|
|
1054
|
+
* The client does not CONSTRUCT stream URLs, it **asks** and is told. Which shapes a subject may
|
|
1055
|
+
* read — and, on the shared tier, which scopes each expands to — is not something the client can
|
|
1056
|
+
* express at all, which is what removes shape selection from the wire.
|
|
1057
|
+
*/
|
|
1058
|
+
controlPlaneUrl: string;
|
|
1059
|
+
/**
|
|
1060
|
+
* The edge that serves durable-streams reads. Granted stream paths are appended to it.
|
|
1061
|
+
*
|
|
1062
|
+
* Separate from {@link controlPlaneUrl} because they are different deployments: the control plane
|
|
1063
|
+
* is a small authenticated origin, and this is the CDN-frontable read surface the shared tier
|
|
1064
|
+
* exists to make cacheable.
|
|
1065
|
+
*/
|
|
1066
|
+
streamBaseUrl: string;
|
|
925
1067
|
batchWriteUrl: string;
|
|
926
1068
|
getAuthToken?: () => Promise<string | undefined>;
|
|
927
1069
|
/**
|
|
@@ -933,27 +1075,28 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
933
1075
|
requestHeaders?: Record<string, string>;
|
|
934
1076
|
/**
|
|
935
1077
|
* Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
|
|
936
|
-
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`).
|
|
937
|
-
* see these. The seam exists because the two ingress points have opposite geometry:
|
|
938
|
-
* function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header)
|
|
939
|
-
* chatty function→DB protocol on a ~1ms loop; the read
|
|
940
|
-
*
|
|
941
|
-
*
|
|
942
|
-
* (e.g. `apikey`) in
|
|
1078
|
+
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Control-plane and stream
|
|
1079
|
+
* requests never see these. The seam exists because the two ingress points have opposite geometry:
|
|
1080
|
+
* the write function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header)
|
|
1081
|
+
* keeps its chatty function→DB protocol on a ~1ms loop; the read path terminates on the stream edge
|
|
1082
|
+
* in front of durable-streams, so pinning reads to the database's region rather than the caller's
|
|
1083
|
+
* pays an intercontinental round trip on every catch-up hop and every long-poll cycle. Put
|
|
1084
|
+
* region/DB-affinity headers here; keep gateway credentials the reads also need (e.g. `apikey`) in
|
|
1085
|
+
* the shared {@link requestHeaders}.
|
|
943
1086
|
*/
|
|
944
1087
|
writeRequestHeaders?: Record<string, string>;
|
|
945
1088
|
syncEnabled?: boolean;
|
|
946
1089
|
/**
|
|
947
1090
|
* The read-silence window (ms) after which a runtime claiming `ready` drops to `degraded` (reason
|
|
948
|
-
* "stream"). A pulled cable HANGS the live long-poll — nothing fails
|
|
949
|
-
*
|
|
950
|
-
*
|
|
951
|
-
*
|
|
1091
|
+
* "stream"). A pulled cable HANGS the live long-poll — nothing fails, nothing delivers — so without this
|
|
1092
|
+
* a session that once reached `ready` would report "up to date" for as long as the outage lasts. A
|
|
1093
|
+
* healthy stream is never silent: durable-streams answers every long-poll hold that times out with a
|
|
1094
|
+
* bare up-to-date response, so the default of 45s spans several cycles. Self-recovering: the next delivered batch
|
|
952
1095
|
* returns `ready`. Status honesty only — nothing is retired or torn down.
|
|
953
1096
|
*/
|
|
954
1097
|
readSilenceMs?: number;
|
|
955
1098
|
/**
|
|
956
|
-
* 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
|
|
957
1100
|
* is DERIVED from the engine home (capability-selected opfs-repacked with IndexedDB fallback in a browser,
|
|
958
1101
|
* or the filesystem on Bun/Node); a
|
|
959
1102
|
* scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
|
|
@@ -975,68 +1118,73 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
975
1118
|
* ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
|
|
976
1119
|
* (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
|
|
977
1120
|
* backend. Absent/false is the honest IDBFS home — the declared `backend: "idbfs"` mode or a capability-absence
|
|
978
|
-
* 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
|
|
979
1122
|
* resolves the actual dataDir from it.
|
|
980
1123
|
*/
|
|
981
1124
|
hasOpfsSyncAccess?: boolean;
|
|
982
1125
|
/**
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
*
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
*
|
|
989
|
-
*
|
|
990
|
-
*
|
|
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`.
|
|
991
1139
|
*/
|
|
992
|
-
|
|
1140
|
+
build?: PostgresBuild;
|
|
993
1141
|
resetSubscriptionKeys?: string[];
|
|
994
|
-
prepareLocalDbBeforeSchema?: (pglite:
|
|
995
|
-
prepareLocalDbAfterSchema?: (pglite:
|
|
1142
|
+
prepareLocalDbBeforeSchema?: (pglite: PgwasmClient) => Promise<void>;
|
|
1143
|
+
prepareLocalDbAfterSchema?: (pglite: PgwasmClient) => Promise<void>;
|
|
996
1144
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
997
1145
|
onTableInitialSync?: (tableKey: string) => void;
|
|
998
1146
|
/**
|
|
999
|
-
* A fully-provisioned
|
|
1147
|
+
* A fully-provisioned pgwasm instance the CALLER owns end-to-end. The client runs NONE of its
|
|
1000
1148
|
* post-create boot steps against it — no schema exec, prepare hooks, or registry reconciliation
|
|
1001
1149
|
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
1002
1150
|
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
1003
1151
|
* - {@link storePath} (default) — the client creates the store AND runs every post-create step.
|
|
1004
|
-
* - {@link
|
|
1152
|
+
* - {@link precreatedPgwasm} — the caller creates the raw store (via {@link createPgwasmClient}), but
|
|
1005
1153
|
* the client still runs every post-create step (schema, prepare hooks, and reconciliation), exactly as
|
|
1006
1154
|
* `storePath` does.
|
|
1007
|
-
* - `
|
|
1155
|
+
* - `pgwasmInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
1008
1156
|
*
|
|
1009
1157
|
* A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
|
|
1010
|
-
* non-persistent (a `new
|
|
1158
|
+
* non-persistent (a `new pgwasm()` default, or an in-memory store) — pgxsinkit's durability semantics
|
|
1011
1159
|
* assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
|
|
1012
1160
|
* `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
|
|
1013
1161
|
*
|
|
1014
|
-
* Mutually exclusive with {@link
|
|
1162
|
+
* Mutually exclusive with {@link precreatedPgwasm} (supplying both throws).
|
|
1015
1163
|
*/
|
|
1016
|
-
|
|
1164
|
+
pgwasmInstance?: PgwasmClient;
|
|
1017
1165
|
/**
|
|
1018
|
-
* A raw
|
|
1166
|
+
* A raw pgwasm instance the caller created EAGERLY (via {@link createPgwasmClient}) — typically on an
|
|
1019
1167
|
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
1020
1168
|
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and registry
|
|
1021
1169
|
* reconciliation all run exactly as on the {@link storePath} path. This is the difference from
|
|
1022
|
-
* {@link
|
|
1170
|
+
* {@link pgwasmInstance} (which skips schema, prepare hooks, and reconciliation because the caller owns
|
|
1023
1171
|
* them); see that
|
|
1024
1172
|
* option's JSDoc for the three-way distinction.
|
|
1025
1173
|
*
|
|
1026
1174
|
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
1027
|
-
* - Supplying both this and {@link
|
|
1175
|
+
* - Supplying both this and {@link pgwasmInstance} throws — they claim different ownership.
|
|
1028
1176
|
* - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
|
|
1029
1177
|
* create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
|
|
1030
|
-
* consuming {@link
|
|
1178
|
+
* consuming {@link build} if provided). The pattern is a pure accelerator, never a boot
|
|
1031
1179
|
* dependency.
|
|
1032
1180
|
* - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
|
|
1033
|
-
* {@link
|
|
1181
|
+
* {@link pgwasmInstance} (checked after resolution, so the refusal propagates rather than being
|
|
1034
1182
|
* swallowed by the reject-fallback).
|
|
1035
1183
|
*/
|
|
1036
|
-
|
|
1184
|
+
precreatedPgwasm?: Promise<PgwasmClient>;
|
|
1037
1185
|
/**
|
|
1038
1186
|
* Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
|
|
1039
|
-
* {@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
|
|
1040
1188
|
* `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
|
|
1041
1189
|
* bytes that travelled inside it). Three restore-only rules apply, none of them optional:
|
|
1042
1190
|
*
|
|
@@ -1055,7 +1203,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1055
1203
|
* ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
|
|
1056
1204
|
* (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
|
|
1057
1205
|
*
|
|
1058
|
-
* Mutually exclusive with {@link
|
|
1206
|
+
* Mutually exclusive with {@link pgwasmInstance} AND {@link precreatedPgwasm} — restore owns the store's
|
|
1059
1207
|
* creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
|
|
1060
1208
|
* with `restoreFrom` throws).
|
|
1061
1209
|
*/
|
|
@@ -1063,7 +1211,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1063
1211
|
/**
|
|
1064
1212
|
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
1065
1213
|
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
1066
|
-
* 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
|
|
1067
1215
|
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery, and registry
|
|
1068
1216
|
* reconciliation) and buffered in memory, with commits gated until those phases finish — so the network
|
|
1069
1217
|
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
@@ -1124,9 +1272,10 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1124
1272
|
batchEventUrl?: string;
|
|
1125
1273
|
/**
|
|
1126
1274
|
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff
|
|
1127
|
-
* tuning, and per-Event-stream overrides. NEVER on the registry —
|
|
1128
|
-
* deployment tuning, and a batch-size tweak must not surface as a
|
|
1129
|
-
* 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.
|
|
1130
1279
|
*/
|
|
1131
1280
|
events?: EventLaneOptions;
|
|
1132
1281
|
/**
|
|
@@ -1166,8 +1315,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1166
1315
|
/**
|
|
1167
1316
|
* @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
|
|
1168
1317
|
* minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
|
|
1169
|
-
* time here; the boot reports them as {@link BootReport.provision} and sets `phases.
|
|
1170
|
-
* 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}
|
|
1171
1320
|
* adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
|
|
1172
1321
|
*/
|
|
1173
1322
|
provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
|
|
@@ -1288,7 +1437,7 @@ export interface SubscribeLiveRowsInput {
|
|
|
1288
1437
|
/**
|
|
1289
1438
|
* The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
|
|
1290
1439
|
* compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
|
|
1291
|
-
* 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
|
|
1292
1441
|
* refuses to materialise (`column "title" specified more than once`) and which silently collapse
|
|
1293
1442
|
* same-named columns even in a plain query. When supplied, the seam wraps the query so every output
|
|
1294
1443
|
* column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
|
|
@@ -1356,14 +1505,14 @@ export interface PreparedQueryResult<TTable extends string = string> {
|
|
|
1356
1505
|
}
|
|
1357
1506
|
|
|
1358
1507
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
1359
|
-
drizzle:
|
|
1360
|
-
|
|
1508
|
+
drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
1509
|
+
pgwasm: PgwasmClient;
|
|
1361
1510
|
views: RegistryViews<TRegistry>;
|
|
1362
1511
|
tables: {
|
|
1363
1512
|
[TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
|
|
1364
1513
|
};
|
|
1365
1514
|
/**
|
|
1366
|
-
* Local-read readiness (ADR-0041): resolves once
|
|
1515
|
+
* Local-read readiness (ADR-0041): resolves once pgwasm is open, the durable schema is ready, registry
|
|
1367
1516
|
* reconciliation has completed, and the drizzle read
|
|
1368
1517
|
* facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
|
|
1369
1518
|
* start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
|
|
@@ -1522,7 +1671,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1522
1671
|
* The store's owed-state diagnostics: the mutation journal's per-status counts, plus — when this client has
|
|
1523
1672
|
* an Event lane — the Outbox's drain signal (ADR-0053 decision 8: the Event lane's durable state takes a
|
|
1524
1673
|
* position on every lifecycle surface). `outbox` is the boolean signal rather than a count, for the reason
|
|
1525
|
-
* {@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.
|
|
1526
1676
|
*/
|
|
1527
1677
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
|
|
1528
1678
|
mutation: MutationDiagnostics;
|
|
@@ -1543,17 +1693,45 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1543
1693
|
* issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
|
|
1544
1694
|
* {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
|
|
1545
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.
|
|
1546
1701
|
*/
|
|
1547
1702
|
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
1548
|
-
/** {@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`. */
|
|
1549
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[]>;
|
|
1550
1728
|
/**
|
|
1551
1729
|
* @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
|
|
1552
1730
|
* ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
|
|
1553
1731
|
* `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
|
|
1554
1732
|
* `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
|
|
1555
1733
|
* client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
|
|
1556
|
-
* worker-side. Accepts the full
|
|
1734
|
+
* worker-side. Accepts the full pgwasm {@link QueryOptions} (the worker re-applies drizzle's identity
|
|
1557
1735
|
* parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
|
|
1558
1736
|
* read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
|
|
1559
1737
|
* from the generated API docs (typedoc excludeInternal).
|
|
@@ -1599,8 +1777,19 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1599
1777
|
*/
|
|
1600
1778
|
ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
|
|
1601
1779
|
/**
|
|
1602
|
-
* Whether a relation's group
|
|
1603
|
-
*
|
|
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.
|
|
1604
1793
|
*/
|
|
1605
1794
|
isSynced: (key: SyncTableName<TRegistry>) => boolean;
|
|
1606
1795
|
/**
|
|
@@ -1703,8 +1892,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1703
1892
|
*/
|
|
1704
1893
|
liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
|
|
1705
1894
|
/**
|
|
1706
|
-
* Take a **store backup** (ADR-0035): a full-fidelity,
|
|
1707
|
-
* 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
|
|
1708
1897
|
* `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
|
|
1709
1898
|
* suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
|
|
1710
1899
|
* with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
|
|
@@ -1753,16 +1942,88 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1753
1942
|
export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };
|
|
1754
1943
|
|
|
1755
1944
|
/**
|
|
1756
|
-
* The structured-clone-safe subset of
|
|
1945
|
+
* The structured-clone-safe subset of pgwasm's `QueryOptions` the inspection surface carries. Kept
|
|
1757
1946
|
* narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
|
|
1758
1947
|
* `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
|
|
1759
|
-
* 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).
|
|
1760
1953
|
*/
|
|
1761
1954
|
export interface RawQueryOptions {
|
|
1762
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>;
|
|
1996
|
+
}
|
|
1997
|
+
|
|
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;
|
|
1763
2024
|
}
|
|
1764
2025
|
|
|
1765
|
-
/** The `{ query, exec }` duck `@
|
|
2026
|
+
/** The `{ query, exec }` duck `@pgxsinkit/pgwasm-repl` drives, backed by a client's inspection surface. */
|
|
1766
2027
|
export interface ReplInspectionSurface {
|
|
1767
2028
|
query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
1768
2029
|
exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
@@ -1770,9 +2031,9 @@ export interface ReplInspectionSurface {
|
|
|
1770
2031
|
|
|
1771
2032
|
/**
|
|
1772
2033
|
* Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
|
|
1773
|
-
* `@
|
|
1774
|
-
* each statement routes through the worker bridge, so the REPL works even though `client.
|
|
1775
|
-
* 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`).
|
|
1776
2037
|
* The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
|
|
1777
2038
|
*/
|
|
1778
2039
|
export function replAdapter(
|
|
@@ -1786,10 +2047,43 @@ export function replAdapter(
|
|
|
1786
2047
|
};
|
|
1787
2048
|
}
|
|
1788
2049
|
|
|
2050
|
+
/**
|
|
2051
|
+
* The read transport this boot runs on: the control plane that grants subscriptions, and the edge that
|
|
2052
|
+
* serves the streams it names.
|
|
2053
|
+
*
|
|
2054
|
+
* Both, resolved once at boot. They are separate deployments (ADR-0055 decision 8) and neither is
|
|
2055
|
+
* usable without the other, so a missing one is refused rather than defaulted — a client that derived
|
|
2056
|
+
* the other would sync against an ingress its caller never named, which is precisely the class of
|
|
2057
|
+
* mistake the native path's ask-don't-construct inversion exists to remove.
|
|
2058
|
+
*/
|
|
2059
|
+
interface ReadTransport {
|
|
2060
|
+
controlPlaneUrl: string;
|
|
2061
|
+
streamBaseUrl: string;
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
function resolveReadTransport(options: { controlPlaneUrl?: string; streamBaseUrl?: string }): ReadTransport {
|
|
2065
|
+
if (options.controlPlaneUrl == null || options.controlPlaneUrl === "") {
|
|
2066
|
+
throw new Error(
|
|
2067
|
+
"[pgxsinkit] createSyncClient needs `controlPlaneUrl` + `streamBaseUrl` — the control plane grants " +
|
|
2068
|
+
"the streams this client may read, and the edge serves them.",
|
|
2069
|
+
);
|
|
2070
|
+
}
|
|
2071
|
+
if (options.streamBaseUrl == null || options.streamBaseUrl === "") {
|
|
2072
|
+
throw new Error(
|
|
2073
|
+
"[pgxsinkit] `controlPlaneUrl` needs `streamBaseUrl` beside it: the control plane grants stream " +
|
|
2074
|
+
"paths and the edge serves them, and they are separate deployments.",
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
return { controlPlaneUrl: options.controlPlaneUrl, streamBaseUrl: options.streamBaseUrl };
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
/** What a started sync exposes to the client. */
|
|
2081
|
+
type SyncGroupsRuntime = CircuitsGroupSyncResult;
|
|
2082
|
+
|
|
1789
2083
|
export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
1790
2084
|
options: CreateSyncClientOptions<TRegistry>,
|
|
1791
2085
|
): Promise<SyncClient<TRegistry>> {
|
|
1792
|
-
// 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).
|
|
1793
2087
|
validateLiveQueryPolicy(options.liveQueries);
|
|
1794
2088
|
const status: SyncRuntimeStatus = {
|
|
1795
2089
|
phase: "booting",
|
|
@@ -1831,9 +2125,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1831
2125
|
rejectBootSettled = reject;
|
|
1832
2126
|
});
|
|
1833
2127
|
|
|
1834
|
-
if (options.
|
|
2128
|
+
if (options.pgwasmInstance && options.precreatedPgwasm) {
|
|
1835
2129
|
throw new Error(
|
|
1836
|
-
"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).",
|
|
1837
2131
|
);
|
|
1838
2132
|
}
|
|
1839
2133
|
|
|
@@ -1841,9 +2135,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1841
2135
|
// the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already
|
|
1842
2136
|
// exists and is provisioned). Fail loudly rather than silently ignore one.
|
|
1843
2137
|
const restoreBoot = options.restoreFrom != null;
|
|
1844
|
-
if (restoreBoot && (options.
|
|
2138
|
+
if (restoreBoot && (options.pgwasmInstance || options.precreatedPgwasm)) {
|
|
1845
2139
|
throw new Error(
|
|
1846
|
-
"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).",
|
|
1847
2141
|
);
|
|
1848
2142
|
}
|
|
1849
2143
|
|
|
@@ -1854,10 +2148,15 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1854
2148
|
// ledger. The decision is taken in the restore recovery block below (it needs the quarantine count) and
|
|
1855
2149
|
// honours an explicit `syncEnabled: false`. A normal boot resolves its final value here, up front.
|
|
1856
2150
|
let syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
|
|
1857
|
-
//
|
|
1858
|
-
//
|
|
1859
|
-
//
|
|
1860
|
-
const
|
|
2151
|
+
// Which read transport this boot uses. Resolved once, up front, and REFUSED when the answer is
|
|
2152
|
+
// ambiguous: two transports configured is a contradiction and none is an omission, and picking a
|
|
2153
|
+
// winner for either would silently sync against something the caller did not name.
|
|
2154
|
+
const readTransport = resolveReadTransport(options);
|
|
2155
|
+
// ADR-0032 S4 overlap prefetch is NOT available on the native read path: it works by holding commits
|
|
2156
|
+
// on a `dbReady` gate while the streams prefetch, and the native engine has no such gate. Boot is
|
|
2157
|
+
// strictly sequential until it grows one (backlog 0012). Kept as a named constant rather than deleted
|
|
2158
|
+
// because the boot report and several branches below are written against the concept.
|
|
2159
|
+
const overlapPrefetch = false;
|
|
1861
2160
|
// How the store presents at boot (ADR-0034 `storeKind`): a restore boot seeds a brand-new store from a
|
|
1862
2161
|
// backup; otherwise the caller's fresh-store hint (the same signal as `freshStore`) marks a fresh spare;
|
|
1863
2162
|
// everything else is a warm (existing persisted) store. Restore wins — a restore boot is never "fresh".
|
|
@@ -1870,7 +2169,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1870
2169
|
const engineHome: BootReport["engineHome"] | undefined = bootMode === "worker" ? options.engineHome : "in-process";
|
|
1871
2170
|
|
|
1872
2171
|
// Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
|
|
1873
|
-
// 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).
|
|
1874
2173
|
const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
|
|
1875
2174
|
mode: bootMode,
|
|
1876
2175
|
freshStore: options.freshStore === true,
|
|
@@ -1900,7 +2199,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1900
2199
|
const backendOverride = testStoreMarker === "memory" ? ("memory" as const) : undefined;
|
|
1901
2200
|
|
|
1902
2201
|
// Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
|
|
1903
|
-
// `
|
|
2202
|
+
// `precreatedPgwasm` reject-fallback), so both consume the same pre-warm + resolve the same backend.
|
|
1904
2203
|
// ADR-0049 step 11c: the OPFS-home grant the client-owned mint opens under. Starts at the placement probe's
|
|
1905
2204
|
// value and is ADJUSTED DOWN to `false` by the pre-mint phase machine (an existing idb store is opened in
|
|
1906
2205
|
// place — the backend is fixed at first mint). Read at mint time by `timedCreate` below, so the phase machine
|
|
@@ -1921,14 +2220,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1921
2220
|
// declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
|
|
1922
2221
|
// explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
|
|
1923
2222
|
// The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
|
|
1924
|
-
// fallback) via the internal carrier on `
|
|
2223
|
+
// fallback) via the internal carrier on `createPgwasmClient`; no open site takes a durability option, so
|
|
1925
2224
|
// no mint can contradict the data contract.
|
|
1926
|
-
const
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
).
|
|
1930
|
-
const
|
|
1931
|
-
|
|
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",
|
|
1932
2235
|
...(backendOverride ? { backendOverride } : {}),
|
|
1933
2236
|
durability: resolvedDurability,
|
|
1934
2237
|
// Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
|
|
@@ -1939,6 +2242,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1939
2242
|
const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
|
|
1940
2243
|
let openedStorageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
|
|
1941
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
|
+
|
|
1942
2252
|
// Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
|
|
1943
2253
|
// brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
|
|
1944
2254
|
// half-write) an existing datadir. The memory test lane is fresh by construction, so the probe is a no-op.
|
|
@@ -1952,20 +2262,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1952
2262
|
throw new RestoreTargetExistsError(fallbackStorePath);
|
|
1953
2263
|
}
|
|
1954
2264
|
}
|
|
1955
|
-
// Time a client-owned `
|
|
2265
|
+
// Time a client-owned `createPgwasmClient` into `phases.pgwasmCreateMs`; an ADOPTED store (spare or
|
|
1956
2266
|
// caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
|
|
1957
|
-
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?.();
|
|
1958
2271
|
const startedAt = performance.now();
|
|
1959
2272
|
// ADR-0049 step 10b/11c: the OPFS-home grant is spread in at MINT time (not baked into `createClientOptions`),
|
|
1960
2273
|
// so the pre-mint phase machine that ran just above can settle `bootHasOpfsSyncAccess` first — opening the
|
|
1961
2274
|
// committed opfs store or the existing idb store. Default absent keeps today's backend.
|
|
1962
2275
|
// ADR-0049 decision 12: this is the SINGLE client-owned mint seam, so stamp `storageBackend` from the resolved
|
|
1963
|
-
// dataDir scheme here — the same resolution `
|
|
2276
|
+
// dataDir scheme here — the same resolution `createPgwasmClient` performs, so the diagnostic never diverges
|
|
1964
2277
|
// from the backend actually opened. Covers every client-owned mint (in-process, worker, precreated-fallback).
|
|
1965
2278
|
const resolvedDataDir = bootHasOpfsSyncAccess
|
|
1966
2279
|
? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
|
|
1967
2280
|
: resolveStoreDataDir(fallbackStorePath, backendOverride);
|
|
1968
|
-
const created = await
|
|
2281
|
+
const created = await createPgwasmClient(fallbackStorePath, {
|
|
1969
2282
|
...createClientOptions,
|
|
1970
2283
|
...(bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}),
|
|
1971
2284
|
});
|
|
@@ -1982,21 +2295,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1982
2295
|
};
|
|
1983
2296
|
|
|
1984
2297
|
// Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
|
|
1985
|
-
// acknowledgment is present. `
|
|
1986
|
-
//
|
|
1987
|
-
//
|
|
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
|
|
1988
2301
|
// successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the
|
|
1989
|
-
// `
|
|
1990
|
-
const refuseIfNonPersistent = (instance:
|
|
2302
|
+
// `precreatedPgwasm` reject-fallback below (which only catches a create that never produced a store).
|
|
2303
|
+
const refuseIfNonPersistent = (instance: PgwasmClient): void => {
|
|
1991
2304
|
if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
|
|
1992
|
-
// An opfs-repacked instance
|
|
1993
|
-
// (
|
|
1994
|
-
|
|
1995
|
-
if (isOpfsRepackedPersistent(instance)) return;
|
|
1996
|
-
const observedDataDir = (instance as { dataDir?: string }).dataDir;
|
|
1997
|
-
// The two provably-non-persistent shapes: an undefined dataDir (a raw `new PGlite()` in-memory default)
|
|
1998
|
-
// and a `memory://` store. Every store the funnel mints carries a real `idb://`/`file://` dataDir string.
|
|
1999
|
-
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);
|
|
2000
2308
|
if (observed !== null) throw new NonPersistentStoreError(observed);
|
|
2001
2309
|
};
|
|
2002
2310
|
|
|
@@ -2004,7 +2312,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2004
2312
|
// accelerator MUST enter here: recovery/classification precede every persistent mint. Keeping the flow in one
|
|
2005
2313
|
// closure prevents a rejected eager create from bypassing live `deleting` authority or the OPFS commitment
|
|
2006
2314
|
// phase machine by jumping straight to `timedCreate()`.
|
|
2007
|
-
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");
|
|
2008
2318
|
// A capability-denied browser may inherit an interrupted destroy or an unexposed candidate from an earlier
|
|
2009
2319
|
// granted engine home, and it may be looking at a store that lives in OPFS it cannot open at all. ONE
|
|
2010
2320
|
// bounded meta read settles all three before any replacement IDB store is minted: a `deleting` handoff
|
|
@@ -2053,29 +2363,34 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2053
2363
|
return timedCreate();
|
|
2054
2364
|
};
|
|
2055
2365
|
|
|
2056
|
-
let pglite:
|
|
2057
|
-
// 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
|
|
2058
2368
|
// whether the provision stamp is honoured (ADR-0034).
|
|
2059
2369
|
let adoptedPrecreated = false;
|
|
2060
|
-
if (options.
|
|
2370
|
+
if (options.pgwasmInstance) {
|
|
2061
2371
|
// The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
|
|
2062
|
-
// (schema, prepare hooks, and reconciliation) — see the `
|
|
2063
|
-
// `
|
|
2064
|
-
refuseIfNonPersistent(options.
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
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
|
|
2068
2380
|
// post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
|
|
2069
2381
|
// `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN
|
|
2070
2382
|
// branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,
|
|
2071
2383
|
// outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create
|
|
2072
2384
|
// that never produced a store).
|
|
2073
|
-
const outcome = await options.
|
|
2385
|
+
const outcome = await options.precreatedPgwasm.then(
|
|
2074
2386
|
(instance) => ({ ok: true as const, instance }),
|
|
2075
2387
|
(error: unknown) => ({ ok: false as const, error }),
|
|
2076
2388
|
);
|
|
2077
2389
|
if (outcome.ok) {
|
|
2078
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");
|
|
2079
2394
|
pglite = outcome.instance;
|
|
2080
2395
|
adoptedPrecreated = true;
|
|
2081
2396
|
} else {
|
|
@@ -2100,10 +2415,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2100
2415
|
bootReportBuilder.setStorageFallbackReason(options.storageFallbackReason);
|
|
2101
2416
|
}
|
|
2102
2417
|
// ADR-0049 decision 12: a BYO instance / adopted-precreated store was created OUTSIDE the mint seam, so derive
|
|
2103
|
-
// its `storageBackend` from the instance's own
|
|
2104
|
-
//
|
|
2105
|
-
if (options.
|
|
2106
|
-
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);
|
|
2107
2422
|
if (byoBackend) {
|
|
2108
2423
|
openedStorageBackend = byoBackend;
|
|
2109
2424
|
bootReportBuilder.setStorageBackend(byoBackend);
|
|
@@ -2116,20 +2431,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2116
2431
|
// run, and the memory test lane has no meta machinery at all. The bounded meta read is kicked off HERE and folded
|
|
2117
2432
|
// into `commitmentBarrierPending` at the milestone below, so it overlaps schema exec instead of preceding it.
|
|
2118
2433
|
const adoptedCommitmentGate =
|
|
2119
|
-
(options.
|
|
2120
|
-
backendOverride !== "memory" &&
|
|
2121
|
-
isOpfsRepackedPersistent(pglite)
|
|
2434
|
+
(options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pglite)
|
|
2122
2435
|
? resolveAdoptedCommitmentBarrier(fallbackStorePath)
|
|
2123
2436
|
: null;
|
|
2124
2437
|
// The gate's rejection is observed at the milestone (fail closed, invariant 12); this only keeps an unrelated
|
|
2125
2438
|
// earlier boot failure from surfacing it as an unhandled rejection in the meantime.
|
|
2126
2439
|
if (adoptedCommitmentGate) void adoptedCommitmentGate.catch(() => undefined);
|
|
2127
2440
|
// Whether THIS client owns the store's lifecycle (so `destroy()` may run the supervised destruction machine
|
|
2128
|
-
// over it). A BYO `
|
|
2129
|
-
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;
|
|
2130
2443
|
|
|
2131
2444
|
// Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
|
|
2132
|
-
// 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`
|
|
2133
2446
|
// null (the create was paid at provision time, off this boot's clock).
|
|
2134
2447
|
if (adoptedPrecreated && options.provisionStamp) {
|
|
2135
2448
|
const stamp = await options.provisionStamp.catch(() => null);
|
|
@@ -2142,17 +2455,6 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2142
2455
|
}
|
|
2143
2456
|
|
|
2144
2457
|
// Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths
|
|
2145
|
-
// (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time
|
|
2146
|
-
// extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
|
|
2147
|
-
// `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
|
|
2148
|
-
// structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
|
|
2149
|
-
// BEFORE the schema/prepare steps below so a `prepareLocalDbAfterSchema` hook sees the same `.electric` it did when
|
|
2150
|
-
// the extension provided it at create time. `engine.close` (the former extension close hook — abort every
|
|
2151
|
-
// shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
|
|
2152
|
-
// `pglite.close()` used to trigger it.
|
|
2153
|
-
const engine: SyncEngine = await createSyncEngine(pglite);
|
|
2154
|
-
(pglite as { electric: SyncEngine["namespace"] }).electric = engine.namespace;
|
|
2155
|
-
|
|
2156
2458
|
// Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to
|
|
2157
2459
|
// the right steady-state phase (`ready` if already caught up, else `syncing`).
|
|
2158
2460
|
let initialSyncCompleted = false;
|
|
@@ -2191,159 +2493,127 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2191
2493
|
}, readSilenceMs);
|
|
2192
2494
|
};
|
|
2193
2495
|
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2496
|
+
/**
|
|
2497
|
+
* The native path's auth adapter.
|
|
2498
|
+
*
|
|
2499
|
+
* The SAME token lifecycle the write path uses (ADR-0003/ADR-0013), resolved per request rather
|
|
2500
|
+
* than captured — a subscription outlives its token by design. The static `requestHeaders` ride
|
|
2501
|
+
* along for the deployment gateway; a resolved `Authorization` wins over anything they carry, so a
|
|
2502
|
+
* gateway credential can never shadow the subject's own.
|
|
2503
|
+
*/
|
|
2504
|
+
const nativeAuthHeaders = async (): Promise<Record<string, string>> => {
|
|
2505
|
+
const headers: Record<string, string> = { ...(options.requestHeaders ?? {}) };
|
|
2506
|
+
const token = await options.getAuthToken?.();
|
|
2507
|
+
if (token != null && token !== "") headers["Authorization"] = `Bearer ${token}`;
|
|
2508
|
+
return headers;
|
|
2509
|
+
};
|
|
2208
2510
|
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
|
|
2234
|
-
// Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and
|
|
2235
|
-
// re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).
|
|
2236
|
-
onGroupReady: (groupKey) => {
|
|
2237
|
-
status.groups = { ...(status.groups ?? {}), [groupKey]: true };
|
|
2238
|
-
options.onStatusChange?.(status);
|
|
2239
|
-
},
|
|
2240
|
-
onInitialSync: () => {
|
|
2241
|
-
initialSyncCompleted = true;
|
|
2242
|
-
status.phase = "ready";
|
|
2243
|
-
options.onStatusChange?.(status);
|
|
2244
|
-
// Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp
|
|
2245
|
-
// closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).
|
|
2246
|
-
syncDebug("boot client ready");
|
|
2247
|
-
// Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`
|
|
2248
|
-
// rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own
|
|
2249
|
-
// finalize below never double-fires it.
|
|
2250
|
-
finalizeBootReport();
|
|
2251
|
-
resolveReady();
|
|
2252
|
-
// `ready` is now a CLAIM the watchdog holds to account: silence past the window drops it back to
|
|
2253
|
-
// degraded — the "up to date offline" lie a hung long-poll otherwise sustains.
|
|
2254
|
-
armReadSilenceWatchdog();
|
|
2255
|
-
},
|
|
2256
|
-
onSyncError: (error) => {
|
|
2257
|
-
// A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than
|
|
2258
|
-
// letting the read cache silently diverge from the server. Sticky (see below).
|
|
2259
|
-
status.phase = "degraded";
|
|
2260
|
-
degradedReason = "commit";
|
|
2261
|
-
// The cause chain, not just the wrapper: a drizzle "Failed query" message hides the actual
|
|
2262
|
-
// database error (SQLSTATE, detail) on `.cause`.
|
|
2263
|
-
status.lastError = describeErrorChain(error);
|
|
2264
|
-
options.onStatusChange?.(status);
|
|
2265
|
-
options.onSyncError?.(error);
|
|
2266
|
-
},
|
|
2267
|
-
// #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting
|
|
2268
|
-
// healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a
|
|
2269
|
-
// commit-failure degraded. Cleared on the next successful batch below.
|
|
2270
|
-
onReadStreamError: (error) => {
|
|
2271
|
-
// Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is
|
|
2272
|
-
// the more serious signal — a stream blip must not overwrite it).
|
|
2273
|
-
if (status.phase === "auth-needed") return;
|
|
2274
|
-
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2275
|
-
// Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most
|
|
2276
|
-
// recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one
|
|
2277
|
-
// way then another reports the current cause (observability).
|
|
2278
|
-
status.phase = "degraded";
|
|
2279
|
-
degradedReason = "stream";
|
|
2280
|
-
status.lastError = describeErrorChain(error);
|
|
2281
|
-
options.onStatusChange?.(status);
|
|
2282
|
-
},
|
|
2283
|
-
// Board ADR-0010: a shape FETCH ATTEMPT failed and Electric is retrying it inside its own backoff
|
|
2284
|
-
// wrapper. This is the only signal an outage produces — a rejected fetch is retryable, so it never
|
|
2285
|
-
// escapes to `onError` and `onReadStreamError` above is never called (Electric retries forever:
|
|
2286
|
-
// "clients may go offline and come back"). Without this the runtime reports `syncing` for as long as
|
|
2287
|
-
// the machine is offline, and a consumer keying off the phase can never say "connection needed". The
|
|
2288
|
-
// two seams partition the failures (see `read-stream-stall.ts`), so this can never pre-empt the
|
|
2289
|
-
// richer classification: an auth 4xx escapes the wrapper and lands on `onAuthError`, not here.
|
|
2290
|
-
//
|
|
2291
|
-
// TRANSITION-only: Electric calls this on every retry tick for as long as the outage lasts, so
|
|
2292
|
-
// re-entering `degraded` would re-emit to every status listener (and, in worker mode, re-broadcast to
|
|
2293
|
-
// every attached tab) roughly once a second, forever. Precedence matches `onReadStreamError`: never
|
|
2294
|
-
// mask `auth-needed` (more actionable) nor a commit-failure degraded (more serious).
|
|
2295
|
-
onReadStreamStalled: () => {
|
|
2296
|
-
if (status.phase === "auth-needed" || status.phase === "degraded") return;
|
|
2297
|
-
status.phase = "degraded";
|
|
2298
|
-
degradedReason = "stream";
|
|
2299
|
-
status.lastError = READ_STREAM_UNREACHABLE;
|
|
2300
|
-
options.onStatusChange?.(status);
|
|
2301
|
-
},
|
|
2302
|
-
// Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
|
|
2303
|
-
// again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,
|
|
2304
|
-
// so only `onSyncError` clearing (a clean commit) would lift it.
|
|
2305
|
-
onSyncActivity: () => {
|
|
2306
|
-
if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
|
|
2307
|
-
degradedReason = null;
|
|
2308
|
-
status.phase = initialSyncCompleted ? "ready" : "syncing";
|
|
2511
|
+
/**
|
|
2512
|
+
* Start sync on whichever read transport this boot resolved.
|
|
2513
|
+
*
|
|
2514
|
+
* The single place the read path is started. Everything above it — status, readiness, the boot
|
|
2515
|
+
* report, the activation replay — is written against {@link SyncGroupsRuntime}.
|
|
2516
|
+
*/
|
|
2517
|
+
const startSyncRuntime = (promotedGroups: ReadonlySet<string>): Promise<SyncGroupsRuntime> =>
|
|
2518
|
+
startCircuitsSync(pglite, {
|
|
2519
|
+
registry: options.registry,
|
|
2520
|
+
controlPlaneUrl: readTransport.controlPlaneUrl,
|
|
2521
|
+
streamBaseUrl: readTransport.streamBaseUrl,
|
|
2522
|
+
metadataSchema: DEFAULT_METADATA_SCHEMA,
|
|
2523
|
+
promotedGroups,
|
|
2524
|
+
// ADR-0034: the per-group rows of the boot report. Only the boot starts open an accumulator.
|
|
2525
|
+
bootCollector: bootReportBuilder,
|
|
2526
|
+
// Teardown must be able to reach the read path BEFORE this promise resolves. A stop while the
|
|
2527
|
+
// first subscribe is still in flight has no runtime handle to unsubscribe — and that is exactly
|
|
2528
|
+
// the window where a stop is most likely, since an unreachable control plane is why the boot is
|
|
2529
|
+
// still running. Without this, `stop()` waits on a TCP connect to a host that is not answering.
|
|
2530
|
+
signal: readPathAbort.signal,
|
|
2531
|
+
...(options.getAuthToken || options.requestHeaders ? { authHeaders: nativeAuthHeaders } : {}),
|
|
2532
|
+
onInitialSync: () => {
|
|
2533
|
+
initialSyncCompleted = true;
|
|
2534
|
+
status.phase = "ready";
|
|
2309
2535
|
options.onStatusChange?.(status);
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2536
|
+
syncDebug("boot client ready");
|
|
2537
|
+
finalizeBootReport();
|
|
2538
|
+
resolveReady();
|
|
2539
|
+
armReadSilenceWatchdog();
|
|
2540
|
+
},
|
|
2541
|
+
onGroupReady: (groupKey: string) => {
|
|
2542
|
+
status.groups = { ...(status.groups ?? {}), [groupKey]: true };
|
|
2543
|
+
options.onStatusChange?.(status);
|
|
2544
|
+
},
|
|
2545
|
+
onSyncError: (error: Error) => {
|
|
2546
|
+
status.phase = "degraded";
|
|
2547
|
+
degradedReason = "commit";
|
|
2548
|
+
status.lastError = describeErrorChain(error);
|
|
2549
|
+
options.onStatusChange?.(status);
|
|
2550
|
+
options.onSyncError?.(error);
|
|
2551
|
+
},
|
|
2552
|
+
// A subscribe that keeps failing on the deployment's side. Recoverable, so it takes the
|
|
2553
|
+
// `stream` reason rather than `commit`: the first delivered batch clears it.
|
|
2554
|
+
//
|
|
2555
|
+
// Precedence, and both halves matter. It never masks `auth-needed` (more actionable — the
|
|
2556
|
+
// subject can fix that one themselves), and it never masks a commit-failure degraded (more
|
|
2557
|
+
// serious — its `lastError` names a store that is diverging, which a transport blip must not
|
|
2558
|
+
// overwrite, and which the delivered-batch recovery must not then lift).
|
|
2559
|
+
//
|
|
2560
|
+
// It DOES refresh a stream-degraded status on each new fault rather than freezing on the
|
|
2561
|
+
// first, so a control plane that fails one way and then another reports its current cause.
|
|
2562
|
+
onSubscribeError: (error: Error) => {
|
|
2563
|
+
if (status.phase === "auth-needed") return;
|
|
2564
|
+
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2565
|
+
status.phase = "degraded";
|
|
2566
|
+
degradedReason = "stream";
|
|
2567
|
+
status.lastError = `${CONTROL_PLANE_UNREACHABLE}: ${describeErrorChain(error)}`;
|
|
2568
|
+
options.onStatusChange?.(status);
|
|
2569
|
+
},
|
|
2570
|
+
// A live read that ended — a stream the engine evicted, a `403` past a re-mint, a lost
|
|
2571
|
+
// connection — with the group already re-subscribing behind it. Same precedence and the same
|
|
2572
|
+
// recovery as `onSubscribeError`, because it is the same kind of fault: the transport, not the
|
|
2573
|
+
// store. It never masks `auth-needed` (the subject can fix that one) and never masks a
|
|
2574
|
+
// commit-failure degraded (that one names a store that is diverging), and the next delivered
|
|
2575
|
+
// batch clears it.
|
|
2576
|
+
onStreamError: (error: Error) => {
|
|
2577
|
+
if (status.phase === "auth-needed") return;
|
|
2578
|
+
if (status.phase === "degraded" && degradedReason === "commit") return;
|
|
2579
|
+
status.phase = "degraded";
|
|
2580
|
+
degradedReason = "stream";
|
|
2581
|
+
status.lastError = `${STREAM_LOST}: ${describeErrorChain(error)}`;
|
|
2582
|
+
options.onStatusChange?.(status);
|
|
2583
|
+
},
|
|
2584
|
+
// ADR-0013: a persistent read-path auth failure is its own status — the app prompts re-login
|
|
2585
|
+
// while subscribe keeps retrying for a fresh token. Only wired when a token provider exists;
|
|
2586
|
+
// without one there is no auth lifecycle to track.
|
|
2587
|
+
...(options.getAuthToken
|
|
2588
|
+
? {
|
|
2589
|
+
onAuthError: () => {
|
|
2590
|
+
if (status.phase === "auth-needed") return;
|
|
2322
2591
|
status.phase = "auth-needed";
|
|
2592
|
+
delete status.lastError;
|
|
2323
2593
|
options.onStatusChange?.(status);
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2594
|
+
},
|
|
2595
|
+
}
|
|
2596
|
+
: {}),
|
|
2597
|
+
onSyncActivity: () => {
|
|
2598
|
+
// A delivered batch is proof of life, so the two RECOVERABLE statuses clear here: an
|
|
2599
|
+
// `auth-needed` whose fresh token has started working (ADR-0013), and a `degraded` whose
|
|
2600
|
+
// reason was the read stream. Never a commit failure — that one is sticky by design
|
|
2601
|
+
// (ADR-0009 d5), because a fetch can keep succeeding while applies keep failing, and
|
|
2602
|
+
// clearing it on traffic would report healthy while the store diverges.
|
|
2603
|
+
if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
|
|
2604
|
+
status.phase = initialSyncCompleted ? "ready" : "syncing";
|
|
2605
|
+
degradedReason = null;
|
|
2606
|
+
delete status.lastError;
|
|
2607
|
+
options.onStatusChange?.(status);
|
|
2326
2608
|
}
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
let earlySync: ReturnType<typeof startConfiguredSync> | null = null;
|
|
2334
|
-
let earlySyncStartedAt = 0;
|
|
2335
|
-
if (overlapPrefetch) {
|
|
2336
|
-
status.isRunning = true;
|
|
2337
|
-
status.phase = "syncing";
|
|
2338
|
-
options.onStatusChange?.(status);
|
|
2339
|
-
earlySyncStartedAt = performance.now();
|
|
2340
|
-
earlySync = startConfiguredSync(
|
|
2341
|
-
pglite as unknown as Parameters<typeof startConfiguredSync>[0],
|
|
2342
|
-
buildStartOptions(new Set()),
|
|
2343
|
-
);
|
|
2344
|
-
}
|
|
2609
|
+
armReadSilenceWatchdog();
|
|
2610
|
+
},
|
|
2611
|
+
onLazyActivated: (groupKey: string) => {
|
|
2612
|
+
void writeLazyGroupActivation(pglite, options.registry, groupKey);
|
|
2613
|
+
},
|
|
2614
|
+
});
|
|
2345
2615
|
|
|
2346
|
-
if (!options.
|
|
2616
|
+
if (!options.pgwasmInstance) {
|
|
2347
2617
|
if (options.prepareLocalDbBeforeSchema) {
|
|
2348
2618
|
const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
|
|
2349
2619
|
await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
|
|
@@ -2411,8 +2681,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2411
2681
|
registry: options.registry,
|
|
2412
2682
|
batchWriteUrl: options.batchWriteUrl,
|
|
2413
2683
|
// pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
|
|
2414
|
-
// supplied their own
|
|
2415
|
-
ownsMetaTable: !options.
|
|
2684
|
+
// supplied their own pgwasm — then the marker is never touched and recovery runs unconditionally.
|
|
2685
|
+
ownsMetaTable: !options.pgwasmInstance,
|
|
2416
2686
|
onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
|
|
2417
2687
|
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
2418
2688
|
...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
|
|
@@ -2427,11 +2697,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2427
2697
|
// no driver is stood up), so there is no conditional to get wrong when a registry gains its first stream.
|
|
2428
2698
|
// The ingestion endpoint is the mutation endpoint's sibling — derived from `batchWriteUrl` unless the
|
|
2429
2699
|
// consumer names it — and it shares the write path's headers (same ingress, same gateway credentials).
|
|
2430
|
-
// A caller-owned
|
|
2700
|
+
// A caller-owned pgwasm (`pgwasmInstance`) never had the toolkit's schema applied, so the Outbox table may
|
|
2431
2701
|
// not exist: the lane stays unconstructed there, exactly as the meta-table marker is left alone.
|
|
2432
2702
|
const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
|
|
2433
2703
|
const eventLane: EventLaneRuntime | null =
|
|
2434
|
-
eventLaneUrl != null && !options.
|
|
2704
|
+
eventLaneUrl != null && !options.pgwasmInstance
|
|
2435
2705
|
? createEventLaneRuntime({
|
|
2436
2706
|
db: pglite,
|
|
2437
2707
|
registry: options.registry,
|
|
@@ -2447,7 +2717,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2447
2717
|
throw new Error(
|
|
2448
2718
|
"pgxsinkit: the Event lane is not available on this client — either `batchWriteUrl` is not the canonical " +
|
|
2449
2719
|
'"…/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' +
|
|
2450
|
-
"`
|
|
2720
|
+
"`pgwasmInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
|
|
2451
2721
|
);
|
|
2452
2722
|
};
|
|
2453
2723
|
|
|
@@ -2467,13 +2737,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2467
2737
|
// quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
|
|
2468
2738
|
const runBootRecoveryStage = async (): Promise<void> => {
|
|
2469
2739
|
const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
|
|
2470
|
-
mutationRuntime.runBootRecovery({ ownsMetaTable: !options.
|
|
2740
|
+
mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgwasmInstance, restore: restoreBoot }),
|
|
2471
2741
|
);
|
|
2472
2742
|
bootReportBuilder.setJournalRecovery(recoveryOutcome);
|
|
2473
2743
|
};
|
|
2474
2744
|
|
|
2475
2745
|
const runReconcileStage = async (): Promise<void> => {
|
|
2476
|
-
if (options.
|
|
2746
|
+
if (options.pgwasmInstance) return;
|
|
2477
2747
|
versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
|
|
2478
2748
|
reconcileLocalStoreVersion({
|
|
2479
2749
|
db: pglite,
|
|
@@ -2514,7 +2784,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2514
2784
|
// Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
|
|
2515
2785
|
const lazyGuardIndex = buildLazyGuardIndex(options.registry);
|
|
2516
2786
|
|
|
2517
|
-
let sync:
|
|
2787
|
+
let sync: SyncGroupsRuntime | null = null;
|
|
2518
2788
|
let convergenceDriver: ConvergenceDriver | null = null;
|
|
2519
2789
|
let eventFlushDriver: EventFlushDriver | null = null;
|
|
2520
2790
|
|
|
@@ -2522,7 +2792,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2522
2792
|
// still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
|
|
2523
2793
|
// each stage boundary — before setting `isRunning`, before starting sync — so no shape stream starts after a
|
|
2524
2794
|
// stop; and `stop`/`destroy` await `bootSettled` before teardown so the tail can never exec against a
|
|
2525
|
-
// closing
|
|
2795
|
+
// closing pgwasm.
|
|
2526
2796
|
let disposed = false;
|
|
2527
2797
|
// Resolves the moment `sync` is wired (and the activation buffer replayed); rejects if the boot is disposed
|
|
2528
2798
|
// or the tail fails before wiring — so a read seam awaiting it in the pre-wire window unblocks rather than
|
|
@@ -2538,11 +2808,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2538
2808
|
// to tell "sync disabled" (trivially ready) apart from "sync pending" (not yet ready / hydrating).
|
|
2539
2809
|
const isSyncPending = (): boolean => syncEnabled && sync == null && !disposed;
|
|
2540
2810
|
|
|
2811
|
+
/** Aborts the read path's control-plane traffic on teardown — see `haltActivity`. */
|
|
2812
|
+
const readPathAbort = new AbortController();
|
|
2813
|
+
|
|
2541
2814
|
// Quiesce the background write/sync tail before a teardown (ADR-0041 BLOCKER 2). `stop()`/`destroy()` can be
|
|
2542
2815
|
// called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails
|
|
2543
2816
|
// at its next stage boundary (never starting sync after this), gracefully release any read seam parked on
|
|
2544
2817
|
// `syncWired` (it then falls through to the local-only path), then AWAIT `bootSettled` — swallowing a tail
|
|
2545
|
-
// 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
|
|
2546
2819
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
2547
2820
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
2548
2821
|
disposed = true;
|
|
@@ -2576,7 +2849,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2576
2849
|
// The Event lane's in-flight POST is aborted on the same synchronous edge as the write path's: a flush
|
|
2577
2850
|
// must not still be settling verdicts into a store the teardown is about to close.
|
|
2578
2851
|
eventLane?.abortInFlight();
|
|
2579
|
-
|
|
2852
|
+
// Covers the read path whether or not sync has finished starting: `sync` is still null while the
|
|
2853
|
+
// first subscribe is in flight, and that is the case this abort exists for.
|
|
2854
|
+
readPathAbort.abort();
|
|
2855
|
+
sync?.unsubscribe();
|
|
2580
2856
|
void convergenceDriver?.stop();
|
|
2581
2857
|
void eventFlushDriver?.stop();
|
|
2582
2858
|
};
|
|
@@ -2605,23 +2881,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2605
2881
|
if (disposed) return;
|
|
2606
2882
|
status.isRunning = true;
|
|
2607
2883
|
|
|
2608
|
-
//
|
|
2609
|
-
//
|
|
2610
|
-
//
|
|
2611
|
-
|
|
2884
|
+
// Provision the subscription metadata store BEFORE anything reads it. The removed ingest engine did
|
|
2885
|
+
// this inside its own construction; the native path has no engine object, so it belongs here.
|
|
2886
|
+
//
|
|
2887
|
+
// Unconditional, outside the `syncEnabled` branch, for two reasons. Every sync-enabled boot reads a
|
|
2888
|
+
// cursor whether or not a reset was asked for — and `desync`/`discardEphemeral` clear one on a
|
|
2889
|
+
// client that may have booted with sync off, so the relations cannot be a function of a runtime
|
|
2890
|
+
// flag. It is also cheap and idempotent: `IF NOT EXISTS` throughout, and the session-scoped halves
|
|
2891
|
+
// (ADR-0042) have to be re-created every boot regardless, since they live in `pg_temp`.
|
|
2892
|
+
await migrateSubscriptionMetadataTables({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA });
|
|
2893
|
+
if (disposed) return;
|
|
2612
2894
|
|
|
2613
2895
|
if (syncEnabled) {
|
|
2614
|
-
|
|
2615
|
-
//
|
|
2616
|
-
//
|
|
2617
|
-
// `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
|
|
2618
|
-
// off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
|
|
2619
|
-
sync = await earlySync;
|
|
2620
|
-
bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
|
|
2621
|
-
bootReportBuilder.markSyncStartDone();
|
|
2622
|
-
} else {
|
|
2623
|
-
// Sequential path (warm store / no fresh hint): apply any explicit subscription resets, promote
|
|
2624
|
-
// durable lazy groups, then start (catch-up strictly after the local phases).
|
|
2896
|
+
{
|
|
2897
|
+
// Apply any explicit subscription resets, promote durable lazy groups, then start — catch-up
|
|
2898
|
+
// strictly after the local phases (ADR-0032 S4's overlap has no native form; backlog 0012).
|
|
2625
2899
|
const resetKeys =
|
|
2626
2900
|
versionEvent?.status === "rebuilt"
|
|
2627
2901
|
? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
|
|
@@ -2639,12 +2913,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2639
2913
|
const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
|
|
2640
2914
|
if (disposed) return;
|
|
2641
2915
|
|
|
2642
|
-
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
|
|
2643
|
-
startConfiguredSync(
|
|
2644
|
-
pglite as unknown as Parameters<typeof startConfiguredSync>[0],
|
|
2645
|
-
buildStartOptions(promotedGroups),
|
|
2646
|
-
),
|
|
2647
|
-
);
|
|
2916
|
+
sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startSyncRuntime(promotedGroups));
|
|
2648
2917
|
bootReportBuilder.markSyncStartDone();
|
|
2649
2918
|
}
|
|
2650
2919
|
// If a stop landed DURING the sync-start await, unsubscribe the just-started streams here rather than
|
|
@@ -2928,7 +3197,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2928
3197
|
// The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both
|
|
2929
3198
|
// revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes
|
|
2930
3199
|
// unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted
|
|
2931
|
-
//
|
|
3200
|
+
// stream subscription (so re-activation re-streams from scratch), then clean-truncate every member's
|
|
2932
3201
|
// local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own
|
|
2933
3202
|
// diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.
|
|
2934
3203
|
const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {
|
|
@@ -2950,7 +3219,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2950
3219
|
}
|
|
2951
3220
|
|
|
2952
3221
|
const activeSync = sync;
|
|
2953
|
-
// The group key IS the
|
|
3222
|
+
// The group key IS the read-path subscription key (`consistencyGroup ?? shapeKey`); fall back to the
|
|
2954
3223
|
// registry derivation when sync is disabled.
|
|
2955
3224
|
const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
|
|
2956
3225
|
// Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and
|
|
@@ -2958,7 +3227,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2958
3227
|
// holds the relation dormant again.
|
|
2959
3228
|
if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
|
|
2960
3229
|
if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
|
|
2961
|
-
// CRITICAL: delete the group's persisted
|
|
3230
|
+
// CRITICAL: delete the group's persisted stream subscription so a later re-activation re-streams the
|
|
2962
3231
|
// shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
|
|
2963
3232
|
// truncate below — leaving the relation permanently missing its pre-desync data.
|
|
2964
3233
|
if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
|
|
@@ -3123,7 +3392,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3123
3392
|
// The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
|
|
3124
3393
|
// `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
|
|
3125
3394
|
// drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
|
|
3126
|
-
// 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
|
|
3127
3396
|
// own result mapping runs on the tab.
|
|
3128
3397
|
const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
|
|
3129
3398
|
await gateAndGuardRead(sql, use);
|
|
@@ -3142,7 +3411,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3142
3411
|
|
|
3143
3412
|
const client: SyncClient<TRegistry> = {
|
|
3144
3413
|
drizzle: drizzleDb,
|
|
3145
|
-
pglite,
|
|
3414
|
+
pgwasm: pglite,
|
|
3146
3415
|
views: buildViews(options.registry),
|
|
3147
3416
|
tables: Object.fromEntries(
|
|
3148
3417
|
Object.keys(options.registry).map((tableKey) => [
|
|
@@ -3172,9 +3441,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3172
3441
|
haltActivity();
|
|
3173
3442
|
// ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
|
|
3174
3443
|
// and await its settlement — so no shape stream is left running and nothing execs against the closing
|
|
3175
|
-
//
|
|
3444
|
+
// pgwasm. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
|
|
3176
3445
|
await quiesceTailForTeardown();
|
|
3177
|
-
// Await any in-flight convergence pass before closing
|
|
3446
|
+
// Await any in-flight convergence pass before closing pgwasm, so a pass never queries a
|
|
3178
3447
|
// closed handle. The Event-lane flush pass is awaited on the same rule, for the same reason.
|
|
3179
3448
|
await convergenceDriver?.stop();
|
|
3180
3449
|
await eventFlushDriver?.stop();
|
|
@@ -3184,8 +3453,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3184
3453
|
// Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
|
|
3185
3454
|
// point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
|
|
3186
3455
|
// preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
|
|
3187
|
-
|
|
3188
|
-
// Dispose the live-query manager before closing
|
|
3456
|
+
sync?.unsubscribe();
|
|
3457
|
+
// Dispose the live-query manager before closing pgwasm (ADR-0040 decisions 1 & 6): it cancels any
|
|
3189
3458
|
// keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
|
|
3190
3459
|
await liveManager.dispose();
|
|
3191
3460
|
await pglite.close();
|
|
@@ -3219,7 +3488,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3219
3488
|
// ADR-0053 decision 8: the same refusal, for the Event lane's durable state. A non-empty Outbox
|
|
3220
3489
|
// holds events the SERVER has not yet ruled on, and "never discard without a server verdict" is
|
|
3221
3490
|
// exactly what at-least-once means on this edge — so a non-forced destroy refuses here too,
|
|
3222
|
-
// 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.
|
|
3223
3493
|
if (eventLane && !(await eventLane.outboxStatus()).empty) {
|
|
3224
3494
|
throw new Error(
|
|
3225
3495
|
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
@@ -3238,8 +3508,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3238
3508
|
await pglite.exec(buildWipeLocalStoreSql(options.registry));
|
|
3239
3509
|
// Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
|
|
3240
3510
|
// the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
|
|
3241
|
-
|
|
3242
|
-
// Dispose the live-query manager before closing
|
|
3511
|
+
sync?.unsubscribe();
|
|
3512
|
+
// Dispose the live-query manager before closing pgwasm — same close-vs-unsubscribe hang guard as
|
|
3243
3513
|
// `stop()` (ADR-0040 decisions 1 & 6).
|
|
3244
3514
|
await liveManager.dispose();
|
|
3245
3515
|
await pglite.close();
|
|
@@ -3247,7 +3517,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3247
3517
|
// now finish the store-meta / OPFS-namespace side. Every recorded browser store runs the full destructive
|
|
3248
3518
|
// lifecycle (set `deleting` → delete commitment
|
|
3249
3519
|
// sentinel → delete both possible backend stores → delete meta). Wiping application tables and closing
|
|
3250
|
-
//
|
|
3520
|
+
// pgwasm do NOT delete its IndexedDB database; retaining that shell would make the next granted boot
|
|
3251
3521
|
// classify it as an existing recordless idb store instead of a genuinely fresh path. A recordless lifecycle-owned
|
|
3252
3522
|
// IDB store therefore enters the same machine; memory, filesystem, non-browser, and caller-owned stores
|
|
3253
3523
|
// have no toolkit browser authority to finish.
|
|
@@ -3283,7 +3553,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3283
3553
|
options.registry,
|
|
3284
3554
|
computeLocalSchemaFingerprint(options.registry),
|
|
3285
3555
|
);
|
|
3286
|
-
// Reset the
|
|
3556
|
+
// Reset the read-path subscriptions so the rebuilt synced tables re-stream from scratch
|
|
3287
3557
|
// rather than the bookkeeping believing they are already caught up (ADR-0006).
|
|
3288
3558
|
await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
|
|
3289
3559
|
})
|
|
@@ -3359,8 +3629,37 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3359
3629
|
mutations: undefined as unknown as MutationsApi<TRegistry>,
|
|
3360
3630
|
// Inspection surface (see the interface doc): straight through to the underlying store, no journal /
|
|
3361
3631
|
// overlay involvement. The worker facade runs the identical call inside the worker's own client.
|
|
3362
|
-
|
|
3363
|
-
|
|
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
|
+
},
|
|
3364
3663
|
// @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
|
|
3365
3664
|
guardedRawQuery,
|
|
3366
3665
|
query: (build) => runGuardedQuery(build),
|
|
@@ -3388,7 +3687,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3388
3687
|
// per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
|
|
3389
3688
|
// public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
|
|
3390
3689
|
// identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
|
|
3391
|
-
// exactly as the inline seam was:
|
|
3690
|
+
// exactly as the inline seam was: pgwasm's `live.query` + the manager's value-identity diff.
|
|
3392
3691
|
subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
|
|
3393
3692
|
// Read gate (ADR-0041): do not register a live query before the local-read core has finished (a
|
|
3394
3693
|
// settled-promise await on the steady-state client — cheap, and stage-2-safe).
|
|
@@ -3444,7 +3743,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3444
3743
|
unsubscribe: () => {
|
|
3445
3744
|
unsubscribed = true;
|
|
3446
3745
|
// Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
|
|
3447
|
-
// `stop()`/`destroy()`) awaits it before closing
|
|
3746
|
+
// `stop()`/`destroy()`) awaits it before closing pgwasm (ADR-0040 decision 1 — the close race).
|
|
3448
3747
|
void subscription.unsubscribe();
|
|
3449
3748
|
},
|
|
3450
3749
|
...(lazyTables.length > 0 ? { lazyTables } : {}),
|
|
@@ -3461,7 +3760,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3461
3760
|
// Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
|
|
3462
3761
|
// take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
|
|
3463
3762
|
await ready;
|
|
3464
|
-
// 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
|
|
3465
3764
|
// resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name
|
|
3466
3765
|
// as something to imitate. The store id is the path's last segment (see `deriveStoreId`).
|
|
3467
3766
|
return lifecycleSlot.run("exportStore", () =>
|
|
@@ -3504,7 +3803,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3504
3803
|
return lifecycleSlot.run("exportData", () =>
|
|
3505
3804
|
performDataExport(
|
|
3506
3805
|
{
|
|
3507
|
-
pglite,
|
|
3806
|
+
pgwasm: pglite,
|
|
3508
3807
|
readMutationStats: () => mutationRuntime.readMutationStats(),
|
|
3509
3808
|
flush: () => mutationRuntime.flush(),
|
|
3510
3809
|
syncedTableNames: collectDataExportSyncedTableNames(options.registry),
|
|
@@ -3612,7 +3911,7 @@ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry:
|
|
|
3612
3911
|
return [...new Set(keys)];
|
|
3613
3912
|
}
|
|
3614
3913
|
|
|
3615
|
-
async function resetSubscriptionsIfRequested(pglite:
|
|
3914
|
+
async function resetSubscriptionsIfRequested(pglite: PgwasmClient, keys: string[] | undefined) {
|
|
3616
3915
|
if (!keys || keys.length === 0) {
|
|
3617
3916
|
return;
|
|
3618
3917
|
}
|
|
@@ -3623,22 +3922,21 @@ async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[
|
|
|
3623
3922
|
return;
|
|
3624
3923
|
}
|
|
3625
3924
|
|
|
3626
|
-
|
|
3627
|
-
await Promise.all(
|
|
3925
|
+
// No migrate here: boot provisions the metadata relations unconditionally, before this can run.
|
|
3926
|
+
await Promise.all(
|
|
3927
|
+
uniqueKeys.map((key) =>
|
|
3928
|
+
deleteSubscriptionState({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
|
|
3929
|
+
),
|
|
3930
|
+
);
|
|
3628
3931
|
}
|
|
3629
3932
|
|
|
3630
3933
|
function createDrizzleDatabase<TRegistry extends SyncTableRegistry>(
|
|
3631
|
-
client:
|
|
3934
|
+
client: PgwasmClient,
|
|
3632
3935
|
schema: RegistryTables<TRegistry>,
|
|
3633
3936
|
) {
|
|
3634
3937
|
const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
|
|
3635
3938
|
|
|
3636
|
-
|
|
3637
|
-
client: ClientPGlite;
|
|
3638
|
-
relations: RegistryRelations<TRegistry>;
|
|
3639
|
-
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3640
|
-
|
|
3641
|
-
return createDatabase({ client, relations });
|
|
3939
|
+
return drizzle(client, { relations });
|
|
3642
3940
|
}
|
|
3643
3941
|
|
|
3644
3942
|
function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
@@ -3659,15 +3957,15 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
|
|
|
3659
3957
|
* identically. The `client` argument is the executor Drizzle runs against:
|
|
3660
3958
|
* - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
|
|
3661
3959
|
* and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
|
|
3662
|
-
* - Pass a `
|
|
3960
|
+
* - Pass a `PgwasmClient`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
|
|
3663
3961
|
* that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
|
|
3664
3962
|
* queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
|
|
3665
3963
|
*/
|
|
3666
3964
|
export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
3667
3965
|
registry: TRegistry,
|
|
3668
|
-
client:
|
|
3966
|
+
client: PgwasmClient = {} as PgwasmClient,
|
|
3669
3967
|
): {
|
|
3670
|
-
drizzle:
|
|
3968
|
+
drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
3671
3969
|
views: RegistryViews<TRegistry>;
|
|
3672
3970
|
/**
|
|
3673
3971
|
* A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
|
|
@@ -3675,7 +3973,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
|
3675
3973
|
* without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
|
|
3676
3974
|
* bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
|
|
3677
3975
|
*/
|
|
3678
|
-
drizzleFor: (client:
|
|
3976
|
+
drizzleFor: (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>>;
|
|
3679
3977
|
} {
|
|
3680
3978
|
const drizzleFor = buildRegistryDrizzleFactory(registry);
|
|
3681
3979
|
return {
|
|
@@ -3693,52 +3991,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
|
|
|
3693
3991
|
*/
|
|
3694
3992
|
function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
|
|
3695
3993
|
registry: TRegistry,
|
|
3696
|
-
): (client:
|
|
3994
|
+
): (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>> {
|
|
3697
3995
|
const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
|
|
3698
|
-
|
|
3699
|
-
client: ClientPGlite;
|
|
3700
|
-
relations: RegistryRelations<TRegistry>;
|
|
3701
|
-
}) => PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
3702
|
-
return (client) => createDatabase({ client, relations });
|
|
3703
|
-
}
|
|
3704
|
-
|
|
3705
|
-
function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
|
|
3706
|
-
registry: TRegistry,
|
|
3707
|
-
electricUrl: string,
|
|
3708
|
-
): SyncConfigInput {
|
|
3709
|
-
return {
|
|
3710
|
-
electricUrl,
|
|
3711
|
-
localSchema: getSyncRegistrySchema(registry),
|
|
3712
|
-
tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),
|
|
3713
|
-
};
|
|
3714
|
-
}
|
|
3715
|
-
|
|
3716
|
-
function buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {
|
|
3717
|
-
const clientProjection = getClientProjection(entry, tableKey);
|
|
3718
|
-
|
|
3719
|
-
return {
|
|
3720
|
-
name: tableKey,
|
|
3721
|
-
mode: entry.mode,
|
|
3722
|
-
primaryKey: entry.primaryKey,
|
|
3723
|
-
...(entry.shape !== undefined ? { shape: entry.shape } : {}),
|
|
3724
|
-
clientProjection,
|
|
3725
|
-
// The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the
|
|
3726
|
-
// registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /
|
|
3727
|
-
// `classifyTableApplyStrategy` on the model, never carried through this config surface.
|
|
3728
|
-
// Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables
|
|
3729
|
-
// onto one MultiShapeStream; absent → singleton group.
|
|
3730
|
-
...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),
|
|
3731
|
-
// Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager
|
|
3732
|
-
// boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).
|
|
3733
|
-
...(entry.subscription ? { subscription: entry.subscription } : {}),
|
|
3734
|
-
...(entry.retention ? { retention: entry.retention } : {}),
|
|
3735
|
-
};
|
|
3736
|
-
}
|
|
3737
|
-
|
|
3738
|
-
function getClientProjection(entry: SyncTableEntry, tableKey: string) {
|
|
3739
|
-
if (!entry.clientProjection) {
|
|
3740
|
-
throw new Error(`clientProjection is required for client table ${tableKey}`);
|
|
3741
|
-
}
|
|
3742
|
-
|
|
3743
|
-
return entry.clientProjection;
|
|
3996
|
+
return (client) => drizzle(client, { relations });
|
|
3744
3997
|
}
|