@pgxsinkit/client 0.1.49 → 0.1.50

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.
@@ -25,6 +25,8 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
25
25
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
26
26
  import {
27
27
  buildRegistryReadHandles,
28
+ ClientDisposedError,
29
+ createMutationsApi,
28
30
  type LiveQueryDiagnostics,
29
31
  type LiveRowsSubscription,
30
32
  type MutationBatchItem,
@@ -166,9 +168,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
166
168
  // ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
167
169
  const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
168
170
  let resolveReady!: () => void;
169
- const ready = new Promise<void>((resolve) => {
171
+ // FIX 2: `ready` gains a reject path so a detach BEFORE initial sync settles it (an attached client stopped
172
+ // pre-ready would otherwise leave `client.ready` / `client.start()` pending forever). Guarded below.
173
+ let rejectReady!: (error: unknown) => void;
174
+ const ready = new Promise<void>((resolve, reject) => {
170
175
  resolveReady = resolve;
176
+ rejectReady = reject;
171
177
  });
178
+ void ready.catch(() => undefined);
172
179
  let readyResolved = false;
173
180
  const readyGroups = new Set<string>();
174
181
  const groupWaiters = new Map<string, Array<() => void>>();
@@ -219,6 +226,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
219
226
  markGroupReady(event.groupKey);
220
227
  break;
221
228
  }
229
+ case "milestone": {
230
+ // Staged boot readiness (ADR-0041 stage 2): the engine crossed a background stage while this tab was
231
+ // attached. Idempotent with the ack's late-attach fold — whichever observes it first wins.
232
+ if (event.stage === "writeReady") settleWriteReady();
233
+ else if (event.stage === "bootSettled") settleBootSettled();
234
+ break;
235
+ }
236
+ case "milestone-error": {
237
+ // The background write/sync tail rejected a downstream stage (ADR-0041): fail the matching stage so a
238
+ // gated write / `bootSettled` awaiter fails loudly. `localReadReady` and the resolved attach are
239
+ // unaffected — the engine reached local-read readiness before the tail failed.
240
+ if (event.stage === "writeReady") failWriteReady(rebuildError(event.error));
241
+ else if (event.stage === "bootSettled") failBootSettled(rebuildError(event.error));
242
+ break;
243
+ }
222
244
  case "conflict":
223
245
  options.onConflict?.(event.details as MutationDetail[]);
224
246
  break;
@@ -263,14 +285,22 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
263
285
  switch (envelope.type) {
264
286
  case "attach-ack": {
265
287
  const ack = payload as AttachAckPayload;
266
- // A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so
267
- // `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the
268
- // status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already
269
- // fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.
288
+ // A LOCAL-READ-CORE boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake
289
+ // so `attachSyncClient` rejects instead of hanging forever. On success, the engine reached
290
+ // `localReadReady` — resolve that stage now (the ack fires AT localReadReady, ADR-0041 Option B) and
291
+ // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`
292
+ // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).
270
293
  if (ack.error) {
271
294
  attachAckReject?.(rebuildError(ack.error));
272
295
  } else {
273
296
  if (ack.engineReady) markReady();
297
+ resolveLocalReadReady();
298
+ // Late-attach milestone fold: the stage may have already crossed (or failed) before this tab
299
+ // attached, in which case there is no broadcast to catch — settle it straight from the ack.
300
+ if (ack.writeReady) settleWriteReady();
301
+ if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
302
+ if (ack.bootSettled) settleBootSettled();
303
+ if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
274
304
  attachAckResolve?.(ack);
275
305
  }
276
306
  break;
@@ -352,6 +382,59 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
352
382
  attachAckReject = reject;
353
383
  });
354
384
 
385
+ // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the
386
+ // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and
387
+ // `localReadReady` is settled off the ack. `writeReady`/`bootSettled` cross in the engine's background tail:
388
+ // they resolve off the `milestone` broadcast when this tab is attached as the stage fires, OR off the ack's
389
+ // late-attach fold when the stage had already fired before this tab attached — one engine crosses each stage
390
+ // once, so both routes observe the same monotonic sequence. A tail failure rejects the matching stage via
391
+ // the `milestone-error` broadcast / the ack's stage-error fold, so a gated write or a `bootSettled` awaiter
392
+ // fails loudly rather than hanging. All guarded so a rejection on an unconsumed stage is never unhandled.
393
+ let resolveLocalReadReady!: () => void;
394
+ const localReadReady = new Promise<void>((resolve) => {
395
+ resolveLocalReadReady = resolve;
396
+ });
397
+ let resolveWriteReady!: () => void;
398
+ let rejectWriteReady!: (error: unknown) => void;
399
+ const writeReady = new Promise<void>((resolve, reject) => {
400
+ resolveWriteReady = resolve;
401
+ rejectWriteReady = reject;
402
+ });
403
+ let resolveBootSettled!: () => void;
404
+ let rejectBootSettled!: (error: unknown) => void;
405
+ const bootSettled = new Promise<void>((resolve, reject) => {
406
+ resolveBootSettled = resolve;
407
+ rejectBootSettled = reject;
408
+ });
409
+ void localReadReady.catch(() => undefined);
410
+ void writeReady.catch(() => undefined);
411
+ void bootSettled.catch(() => undefined);
412
+ // Idempotent settlers — a stage may be signalled by BOTH the ack fold and a milestone event (or by a
413
+ // detach), and must settle exactly once. `localReadReady` never rejects (a local-read-core failure rejects
414
+ // the attach handshake instead, so this client is never handed out).
415
+ let writeReadySettled = false;
416
+ let bootSettledSettled = false;
417
+ const settleWriteReady = () => {
418
+ if (writeReadySettled) return;
419
+ writeReadySettled = true;
420
+ resolveWriteReady();
421
+ };
422
+ const failWriteReady = (error: unknown) => {
423
+ if (writeReadySettled) return;
424
+ writeReadySettled = true;
425
+ rejectWriteReady(error);
426
+ };
427
+ const settleBootSettled = () => {
428
+ if (bootSettledSettled) return;
429
+ bootSettledSettled = true;
430
+ resolveBootSettled();
431
+ };
432
+ const failBootSettled = (error: unknown) => {
433
+ if (bootSettledSettled) return;
434
+ bootSettledSettled = true;
435
+ rejectBootSettled(error);
436
+ };
437
+
355
438
  // ─── Detach (explicit stop AND page teardown) ──────────────────────────────────────────────────────
356
439
  // The platform fires NO close event on a SharedWorker port — a tab that simply closes would leave its
357
440
  // subscriptions (and their per-write rerun cost) alive in the worker for the worker's whole lifetime
@@ -379,6 +462,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
379
462
  // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
380
463
  // it has already settled).
381
464
  attachAckReject?.(detachError());
465
+ // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so
466
+ // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the
467
+ // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription
468
+ // rejections below, where the more specific "client detached" message is useful for a data operation.
469
+ // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already
470
+ // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.
471
+ const disposedError = new ClientDisposedError();
472
+ failWriteReady(disposedError);
473
+ failBootSettled(disposedError);
474
+ // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave
475
+ // `client.ready` / `client.start()` pending forever. Settle it once with the same disposed error.
476
+ if (!readyResolved) {
477
+ readyResolved = true;
478
+ rejectReady(disposedError);
479
+ }
382
480
  for (const pending of rpcPending.values()) pending.reject(detachError());
383
481
  rpcPending.clear();
384
482
  for (const pending of initialPending.values()) pending.reject(detachError());
@@ -551,6 +649,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
551
649
  },
552
650
  ]),
553
651
  ) as SyncClient<TRegistry>["tables"],
652
+ localReadReady,
653
+ writeReady,
654
+ bootSettled,
554
655
  ready,
555
656
  status,
556
657
  start: async () => {
@@ -579,6 +680,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
579
680
  discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
580
681
  discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
581
682
  diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
683
+ // The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,
684
+ // wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot
685
+ // `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.
686
+ mutations: createMutationsApi({
687
+ registry: options.registry,
688
+ subscribeLiveRows,
689
+ query: (sql, params) => rpc<Results>("rawQuery", [sql, params]),
690
+ }),
582
691
  query: notSupported("client.query"),
583
692
  queryRow: notSupported("client.queryRow"),
584
693
  queryRaw: notSupported("client.queryRaw"),
@@ -34,6 +34,7 @@ import {
34
34
  } from "./live-query-manager";
35
35
  import {
36
36
  type AttachPayload,
37
+ type BootMilestone,
37
38
  type BridgeCodec,
38
39
  type BridgeEnvelope,
39
40
  type BridgeEvent,
@@ -314,6 +315,37 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
314
315
  resolveBooted = resolve;
315
316
  });
316
317
 
318
+ // ─── Boot milestone bridge (ADR-0041 stage 2) ────────────────────────────────────────────────────
319
+ // One engine crosses each background boot stage once. Broadcast a one-shot `milestone` as it crosses
320
+ // `writeReady`/`bootSettled` (or a `milestone-error` if the tail rejects the stage), and FOLD the current
321
+ // set into every `attach-ack` so a tab that attached after a stage fired resolves it from the ack. The
322
+ // ack itself fires AT `localReadReady` (the Option B contract), so that stage needs no milestone. Wired
323
+ // exactly once off the booted client's stage promises (`milestonesWired`), then driven purely by them.
324
+ const milestones = { writeReady: false, bootSettled: false };
325
+ const stageErrors: {
326
+ writeReady?: { message: string; detail?: unknown };
327
+ bootSettled?: { message: string; detail?: unknown };
328
+ } = {};
329
+ let milestonesWired = false;
330
+ const markMilestone = (stage: BootMilestone) => {
331
+ if (milestones[stage]) return;
332
+ milestones[stage] = true;
333
+ broadcastEvent({ kind: "milestone", stage });
334
+ };
335
+ const failMilestone = (stage: BootMilestone, error: unknown) => {
336
+ if (stageErrors[stage]) return;
337
+ const serialized = serializeError(error);
338
+ stageErrors[stage] = serialized;
339
+ broadcastEvent({ kind: "milestone-error", stage, error: serialized });
340
+ };
341
+ // Attach-ack fold fields for a LATE attach — the milestones/failures already crossed at ack time.
342
+ const milestoneAckFields = () => ({
343
+ ...(milestones.writeReady ? { writeReady: true as const } : {}),
344
+ ...(milestones.bootSettled ? { bootSettled: true as const } : {}),
345
+ ...(stageErrors.writeReady ? { writeReadyError: stageErrors.writeReady } : {}),
346
+ ...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),
347
+ });
348
+
317
349
  const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
318
350
  if (bootPromise) return bootPromise;
319
351
  // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
@@ -400,6 +432,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
400
432
  // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
401
433
  // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
402
434
  onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
435
+ // ADR-0041 stage 2 (Option B contract): `createSyncClient` resolves AT `localReadReady`, so the boot
436
+ // promise now resolves there too — the attach handler acks at local-read readiness and the write/sync
437
+ // tail runs in the background, announced to tabs via the `writeReady`/`bootSettled` milestone messages
438
+ // wired in the attach handler below. The stage-1 `await booted.bootSettled` shim is deleted: attach no
439
+ // longer waits for the whole boot, which is exactly the behavioural change this stage delivers.
403
440
  });
404
441
  return bootPromise;
405
442
  };
@@ -746,18 +783,42 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
746
783
  (booted) => {
747
784
  client = booted;
748
785
  resolveBooted(booted);
786
+ // Wire the engine's background stage promises to the milestone bridge exactly ONCE (ADR-0041
787
+ // stage 2). `createSyncClient` resolved at `localReadReady`, so by here the engine has crossed
788
+ // that stage — the ack below carries it implicitly. `writeReady`/`bootSettled` cross later (or
789
+ // fail): broadcast each as a one-shot `milestone`/`milestone-error` for currently-attached ports
790
+ // and fold the current set into every subsequent ack for late attachers.
791
+ if (!milestonesWired) {
792
+ milestonesWired = true;
793
+ void booted.writeReady.then(
794
+ () => markMilestone("writeReady"),
795
+ (error: unknown) => failMilestone("writeReady", error),
796
+ );
797
+ void booted.bootSettled.then(
798
+ () => markMilestone("bootSettled"),
799
+ (error: unknown) => failMilestone("bootSettled", error),
800
+ );
801
+ }
749
802
  // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the
750
803
  // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).
751
804
  if (!engineReadyFired) {
752
- void booted.ready.then(() => {
753
- engineReadyFired = true;
754
- });
805
+ // ADR-0041: `ready` can now reject if the background write/sync tail fails after the client was
806
+ // handed out; swallow that here so it is not an unhandled rejection (the failure surfaces to
807
+ // tabs via the `milestone-error` broadcast / the stage-error ack fold instead).
808
+ void booted.ready.then(
809
+ () => {
810
+ engineReadyFired = true;
811
+ },
812
+ () => undefined,
813
+ );
755
814
  }
756
815
  // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to
757
- // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).
816
+ // hit; the ack fires AT `localReadReady` (Option B) and folds the current milestone set +
817
+ // engine-ready edge for a late-joining tab (ADR-0041 / ADR-0032 FIX 3).
758
818
  postBridgeMessage(port, codec, "attach-ack", {
759
819
  alreadyBooted,
760
820
  ...(engineReadyFired ? { engineReady: true } : {}),
821
+ ...milestoneAckFields(),
761
822
  });
762
823
  postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
763
824
  },
@@ -179,6 +179,15 @@ export interface SetOnlinePayload {
179
179
  online: boolean;
180
180
  }
181
181
 
182
+ /**
183
+ * The two background boot stages the worker announces over the bridge as one-shot milestones (ADR-0041
184
+ * stage 2). `localReadReady` is NOT in this set: under the Option B contract the `attach-ack` fires AT the
185
+ * engine's `localReadReady`, so a tab resolves that stage from the ack itself (early OR late attach) — it
186
+ * needs no separate milestone. `writeReady` and `bootSettled` cross in the background write/sync tail, after
187
+ * the ack, so they DO ride milestone messages (and the late-attach ack fold).
188
+ */
189
+ export type BootMilestone = "writeReady" | "bootSettled";
190
+
182
191
  /** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */
183
192
  export interface AttachAckPayload {
184
193
  alreadyBooted: boolean;
@@ -189,9 +198,28 @@ export interface AttachAckPayload {
189
198
  * the ack, rather than wait for a phase-"ready" status that may never come again.
190
199
  */
191
200
  engineReady?: boolean;
201
+ /**
202
+ * Late-attach milestone fold (ADR-0041 stage 2): true when the engine had ALREADY crossed `writeReady` /
203
+ * `bootSettled` by the time this attach was acked, so a tab attaching after the stage fired resolves it
204
+ * straight from the ack rather than waiting for a `milestone` broadcast it missed. The ack fires AT
205
+ * `localReadReady`, so that stage is always implied by a non-error ack and carries no boolean.
206
+ */
207
+ writeReady?: boolean;
208
+ bootSettled?: boolean;
209
+ /**
210
+ * Late-attach failure fold (ADR-0041 stage 2): present when the engine's background write/sync tail had
211
+ * already REJECTED a downstream stage before this attach was acked. The tab rejects the matching stage
212
+ * promise (so a gated write / `bootSettled` awaiter fails loudly rather than hangs) — but the attach
213
+ * itself still RESOLVES (the engine reached `localReadReady`; only the tail failed). A live milestone
214
+ * failure after attach rides the `milestone-error` broadcast instead.
215
+ */
216
+ writeReadyError?: { message: string; detail?: unknown };
217
+ bootSettledError?: { message: string; detail?: unknown };
192
218
  /**
193
219
  * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this
194
- * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.
220
+ * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot. This
221
+ * is a LOCAL-READ-CORE failure (the engine never reached `localReadReady`); a tail failure after
222
+ * `localReadReady` uses the stage-error fields above and does NOT reject the attach.
195
223
  */
196
224
  error?: { message: string; detail?: unknown };
197
225
  }
@@ -363,6 +391,15 @@ export interface LiveDiffPayload {
363
391
  export type BridgeEvent =
364
392
  | { kind: "status"; status: SyncRuntimeStatus }
365
393
  | { kind: "groupReady"; groupKey: string }
394
+ // Staged boot readiness (ADR-0041 stage 2): a one-shot milestone as the engine crosses a background boot
395
+ // stage (`writeReady` / `bootSettled`), broadcast to currently-attached ports. A tab attaching AFTER a
396
+ // stage fired never sees the broadcast — it folds the current milestone set off its `attach-ack` instead.
397
+ // One engine crosses each stage once; every port observes the same monotonic sequence (ack fold + event).
398
+ | { kind: "milestone"; stage: BootMilestone }
399
+ // The mirror failure edge: the background write/sync tail REJECTED a downstream stage (ADR-0041). Rejects
400
+ // the tab's matching `writeReady` / `bootSettled` promise so an awaiter fails loudly rather than hanging;
401
+ // `localReadReady` (and the resolved attach) are unaffected — the engine reached local-read readiness.
402
+ | { kind: "milestone-error"; stage: BootMilestone; error: { message: string; detail?: unknown } }
366
403
  | { kind: "conflict"; details: unknown }
367
404
  | { kind: "quarantine"; details: unknown }
368
405
  | { kind: "reject"; details: unknown }