@pgxsinkit/client 0.2.0 → 0.2.1

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/src/index.ts CHANGED
@@ -15,6 +15,7 @@ import type {
15
15
  SyncRuntimeStatus,
16
16
  SyncTableCreateInput,
17
17
  SyncTableEntry,
18
+ SyncStorageDeclaration,
18
19
  SyncTableName,
19
20
  SyncTableRegistry,
20
21
  SyncTableUpdateInput,
@@ -26,6 +27,7 @@ import {
26
27
  getSyncRegistrySchema,
27
28
  getSyncRegistryStorage,
28
29
  isClaimsDependentRowFilter,
30
+ resolveStorageDeclaration,
29
31
  } from "@pgxsinkit/contracts";
30
32
  // Type-only import (erased at runtime): the opfs-repacked factory's option/return types for the `opfs://`
31
33
  // branch. The factory VALUE is loaded lazily via dynamic `import()` inside that branch so a Bun unit test
@@ -168,9 +170,14 @@ export {
168
170
  } from "./adoption";
169
171
  export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
170
172
  export {
173
+ destroyStoreArtifacts,
171
174
  type ElectedEngineWorker,
172
175
  ElectedEngineUnconstructibleError,
176
+ quiesceStoreWorker,
173
177
  StoreDestroyRefusedError,
178
+ type StoreDestructionRetryOptions,
179
+ type StoreWorkerQuiesceOptions,
180
+ type StoreWorkerQuiesceOutcome,
174
181
  wrapEngineWorker,
175
182
  } from "./worker/attach-sync-client";
176
183
  export {
@@ -210,8 +217,6 @@ export {
210
217
  attachSyncClient,
211
218
  type AttachSyncClientOptions,
212
219
  provisionSyncWorker,
213
- retireSyncWorkerHost,
214
- type RetireSyncWorkerHostOptions,
215
220
  } from "./worker/attach-sync-client";
216
221
  export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
217
222
  export {
@@ -1178,6 +1183,15 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1178
1183
  * `@pgxsinkit/client/testing` instead of naming one here.
1179
1184
  */
1180
1185
  storePath?: string;
1186
+ /**
1187
+ * @internal Toolkit-internal WIRE-declaration carrier (ADR-0050), NOT a public per-boot knob. The worker
1188
+ * host threads the store's BOUND storage declaration (registry static + the first payload's wire
1189
+ * declaration + defaults) in here, and this boot's single storage resolution point folds it with the
1190
+ * registry's own static declaration — an explicit disagreement is a typed
1191
+ * `StorageDeclarationRefusedError` (the worker handlers refuse conflicts before this ever throws).
1192
+ * In-process consumers never set it: their registry IS the declaration.
1193
+ */
1194
+ storage?: SyncStorageDeclaration;
1181
1195
  /**
1182
1196
  * ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
1183
1197
  * (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
@@ -1595,6 +1609,14 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1595
1609
  ready: Promise<void>;
1596
1610
  status: SyncRuntimeStatus;
1597
1611
  start: () => Promise<void>;
1612
+ /**
1613
+ * Synchronously abort all sync/write activity (in-flight write fetches, shape-stream long-polls, convergence
1614
+ * scheduling) without awaiting. Idempotent. The first action of every teardown path — stop()/destroy() call it,
1615
+ * and the SharedWorker host calls it before draining subscribes / disposing live queries so no teardown step
1616
+ * races a still-live engine. Not a substitute for stop()/destroy(): the awaited teardown (unsubscribe, dispose,
1617
+ * pglite.close) still follows. Callers rarely invoke it directly.
1618
+ */
1619
+ haltActivity: () => void;
1598
1620
  stop: () => Promise<void>;
1599
1621
  /**
1600
1622
  * Wipe the entire local store (synced cache + overlay + journal) and close the handle
@@ -2050,11 +2072,17 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2050
2072
  // once the adoption + fresh phase machine has settled (never on a plain idb boot, where `probeGranted` is false).
2051
2073
  const probeGranted = options.hasOpfsSyncAccess === true;
2052
2074
  let storageFallbackReason: string | undefined;
2053
- // Durability (ADR-0047 D2): resolve the registry's declared mode ONCE here — this is the single resolution
2054
- // point — and thread it into every client-owned mint (its own boot create and the precreated-reject fallback)
2055
- // via the internal carrier on `createClientPGlite`. `storage.durability ?? "relaxed"` is the toolkit default;
2056
- // no open site takes a durability option, so no mint can contradict the data contract.
2057
- const resolvedDurability: StorageDurability = getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
2075
+ // Durability (ADR-0047 D2 + ADR-0050): resolve the store's declared mode ONCE here — this is the single
2076
+ // resolution point — from the registry's static declaration folded with the worker-threaded wire
2077
+ // declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
2078
+ // explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
2079
+ // The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
2080
+ // fallback) via the internal carrier on `createClientPGlite`; no open site takes a durability option, so
2081
+ // no mint can contradict the data contract.
2082
+ const resolvedDurability: StorageDurability = resolveStorageDeclaration(
2083
+ getSyncRegistryStorage(options.registry),
2084
+ options.storage,
2085
+ ).durability;
2058
2086
  const createClientOptions: CreateClientPGliteOptions = {
2059
2087
  ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
2060
2088
  ...(backendOverride ? { backendOverride } : {}),
@@ -2617,6 +2645,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2617
2645
  await bootSettled.catch(() => undefined);
2618
2646
  };
2619
2647
 
2648
+ // Synchronously halt ALL sync/write ACTIVITY without awaiting anything — the first action of every teardown
2649
+ // entry point (stop()/destroy() here, and the SharedWorker host's closeHost, which calls this before it drains
2650
+ // pending subscribes or disposes live queries). Abort the mutation runtime's in-flight write fetches + any
2651
+ // stalled auth resolve, abort every shape-stream long-poll (engine.close's AbortControllers fire synchronously),
2652
+ // and stop convergence scheduling (the in-flight pass then settles fast — its fetch is aborted). Idempotent.
2653
+ // Without this, a teardown step that runs BEFORE the streams are aborted (live-query dispose, pending-subscribe
2654
+ // drain) races an engine still committing shape data and never settles. The full AWAITED teardown still runs
2655
+ // after; this only guarantees the network + scheduling are already dead when it does.
2656
+ const haltActivity = (): void => {
2657
+ disposed = true;
2658
+ mutationRuntime.abortInFlight();
2659
+ void engine.close();
2660
+ void convergenceDriver?.stop();
2661
+ };
2662
+
2620
2663
  // The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
2621
2664
  // `localReadReady` resolves, so `createSyncClient` resolves at `localReadReady` (the Option B contract). On a
2622
2665
  // restore boot recovery already ran in the core, so the tail only opens the (unused) gate and settles. It
@@ -3178,7 +3221,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3178
3221
  start: async () => {
3179
3222
  await ready;
3180
3223
  },
3224
+ haltActivity,
3181
3225
  stop: async () => {
3226
+ // Halt all activity FIRST (see haltActivity) — before any await.
3227
+ haltActivity();
3182
3228
  // ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
3183
3229
  // and await its settlement — so no shape stream is left running and nothing execs against the closing
3184
3230
  // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
@@ -3204,6 +3250,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3204
3250
  // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
3205
3251
  // inside the slot run.
3206
3252
  lifecycleSlot.run("destroy", async () => {
3253
+ // Halt all activity FIRST (see haltActivity) — before any await.
3254
+ haltActivity();
3207
3255
  // ADR-0041: quiesce the background boot tail BEFORE the owed-mutations read and the wipe, so neither
3208
3256
  // races the tail's recovery journal updates / sync start (BLOCKER 2). After this the tail has settled.
3209
3257
  await quiesceTailForTeardown();
package/src/mutation.ts CHANGED
@@ -379,6 +379,12 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
379
379
  */
380
380
  flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;
381
381
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
382
+ /**
383
+ * Fire the runtime's dispose signal: abort every in-flight write-path fetch AND unblock any await parked on
384
+ * a stalled getAuthToken(). Called FIRST by the client's stop()/destroy() so teardown halts all write-network
385
+ * activity before it awaits the convergence pass. Idempotent; a disposed runtime performs no further network.
386
+ */
387
+ abortInFlight: () => void;
382
388
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
383
389
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
384
390
  /**
@@ -508,6 +514,24 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
508
514
  const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
509
515
  let flushQueue = Promise.resolve();
510
516
 
517
+ // Teardown halt (see stop()/destroy()): a disposed runtime stops ALL activity at once. The signal is
518
+ // fired once by abortInFlight() and never reset. Every write-path fetch rides it (aborting an in-flight
519
+ // POST), and every getAuthToken() await is raced against it — the board's getAuthToken calls
520
+ // supabase.auth.getSession(), which can stall on token refresh (see flushBatch), so a fetch signal alone
521
+ // would not release teardown. On abort, flush()/flushUnit() reject promptly and the convergence pass settles.
522
+ const disposeController = new AbortController();
523
+ // Reject a pending await the instant the runtime is disposed. Cleans up its listener so per-flush use never leaks.
524
+ const untilAborted = <T>(work: Promise<T>): Promise<T> => {
525
+ if (disposeController.signal.aborted) {
526
+ return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
527
+ }
528
+ return new Promise<T>((resolve, reject) => {
529
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
530
+ disposeController.signal.addEventListener("abort", onAbort, { once: true });
531
+ work.then(resolve, reject).finally(() => disposeController.signal.removeEventListener("abort", onAbort));
532
+ });
533
+ };
534
+
511
535
  // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
512
536
  // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
513
537
  // touched and the SET/clear seams below are no-ops.
@@ -995,6 +1019,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
995
1019
  options.requestHeaders,
996
1020
  ensureRecoveryMarker,
997
1021
  markSendingScope,
1022
+ disposeController.signal,
998
1023
  );
999
1024
 
1000
1025
  processedCount = batchResult.processedCount;
@@ -1117,6 +1142,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1117
1142
  flushQueue = nextFlush.catch(() => undefined);
1118
1143
  await nextFlush;
1119
1144
  },
1145
+ abortInFlight: () => disposeController.abort(),
1120
1146
  flushUnit: async (unitId) => {
1121
1147
  const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);
1122
1148
  const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
@@ -1200,18 +1226,21 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1200
1226
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1201
1227
 
1202
1228
  try {
1203
- const authToken = await options.getAuthToken?.();
1229
+ const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
1204
1230
  let response = await fetch(url, {
1205
1231
  method: "POST",
1206
1232
  headers: buildRequestHeaders(authToken, options.requestHeaders),
1207
1233
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1234
+ signal: disposeController.signal,
1208
1235
  });
1209
1236
 
1210
1237
  if ([401, 403].includes(response.status) && options.getAuthToken) {
1238
+ const retryToken = await untilAborted(Promise.resolve(options.getAuthToken()));
1211
1239
  response = await fetch(url, {
1212
1240
  method: "POST",
1213
- headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),
1241
+ headers: buildRequestHeaders(retryToken, options.requestHeaders),
1214
1242
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1243
+ signal: disposeController.signal,
1215
1244
  });
1216
1245
  }
1217
1246
 
@@ -2546,6 +2575,18 @@ async function readUnitPendingRows(
2546
2575
  return result.rows;
2547
2576
  }
2548
2577
 
2578
+ // Race a promise against an AbortSignal so a disposed runtime's teardown never parks on it (mirrors
2579
+ // createMutationRuntime's untilAborted; used by the module-level flushBatch). A missing signal is a passthrough.
2580
+ function raceAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
2581
+ if (!signal) return work;
2582
+ if (signal.aborted) return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
2583
+ return new Promise<T>((resolve, reject) => {
2584
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
2585
+ signal.addEventListener("abort", onAbort, { once: true });
2586
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2587
+ });
2588
+ }
2589
+
2549
2590
  async function flushBatch(
2550
2591
  db: MutationDb,
2551
2592
  tableContexts: Record<string, TableContext>,
@@ -2557,6 +2598,7 @@ async function flushBatch(
2557
2598
  requestHeaders?: Record<string, string>,
2558
2599
  ensureRecoveryMarker?: () => Promise<void>,
2559
2600
  markSendingScope?: MarkSendingScope,
2601
+ signal?: AbortSignal,
2560
2602
  ): Promise<FlushBatchResult> {
2561
2603
  const contexts = filterContexts(tableContexts, tableFilter);
2562
2604
  const nowUs = nowMicroseconds();
@@ -2671,7 +2713,7 @@ async function flushBatch(
2671
2713
  // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
2672
2714
  // be invisibly folded into "the write was slow".
2673
2715
  const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2674
- const authToken = await getAuthToken?.();
2716
+ const authToken = await raceAbort(getAuthToken?.() ?? Promise.resolve(undefined), signal);
2675
2717
  const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2676
2718
  syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
2677
2719
 
@@ -2679,13 +2721,15 @@ async function flushBatch(
2679
2721
  method: "POST",
2680
2722
  headers: buildRequestHeaders(authToken, requestHeaders),
2681
2723
  body: jsonStringifyPayload({ mutations }),
2724
+ signal: signal ?? null,
2682
2725
  });
2683
2726
 
2684
2727
  if ([401, 403].includes(response.status) && getAuthToken) {
2685
2728
  response = await fetch(batchMutationUrl, {
2686
2729
  method: "POST",
2687
- headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
2730
+ headers: buildRequestHeaders(await raceAbort(getAuthToken(), signal), requestHeaders),
2688
2731
  body: jsonStringifyPayload({ mutations }),
2732
+ signal: signal ?? null,
2689
2733
  });
2690
2734
  }
2691
2735