@pgxsinkit/client 0.2.5 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/event-lane.d.ts +266 -0
- package/dist/event-lane.d.ts.map +1 -0
- package/dist/index.d.ts +94 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2797 -1995
- package/dist/index.js.map +16 -15
- package/dist/local-tables.d.ts +170 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +37 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +12 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +7 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +3 -3
- package/skills/core/SKILL.md +47 -9
- package/skills/operating/SKILL.md +359 -352
- package/src/event-lane.ts +1194 -0
- package/src/index.ts +244 -8
- package/src/local-tables.ts +48 -1
- package/src/mutation.ts +13 -1
- package/src/schema.ts +81 -1
- package/src/worker/attach-sync-client.ts +81 -2
- package/src/worker/define-sync-worker.ts +48 -0
- package/src/worker/protocol.ts +14 -0
|
@@ -27,6 +27,7 @@ import { StorageDeclarationRefusedError } from "@pgxsinkit/contracts";
|
|
|
27
27
|
|
|
28
28
|
import type { BootReport } from "../boot-report";
|
|
29
29
|
import { syncDebug } from "../debug";
|
|
30
|
+
import type { EventAppendResult, EventLaneReport, OutboxStatus } from "../event-lane";
|
|
30
31
|
import type { DataExportOptions, DataExportResult } from "../export-data";
|
|
31
32
|
import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-dump";
|
|
32
33
|
import type { StoreExportOptions, StoreExportResult } from "../export-store";
|
|
@@ -575,6 +576,12 @@ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
|
|
|
575
576
|
"discardQuarantined",
|
|
576
577
|
"desync",
|
|
577
578
|
"discardEphemeral",
|
|
579
|
+
// The Event lane's two write-capable ops (ADR-0053). `appendEvent` STAGES a durable row, so a lost
|
|
580
|
+
// response is genuinely `"unknown"` — a blind repeat would stamp a FRESH `eventId` and append a second
|
|
581
|
+
// event (the server's dedupe keys on the id we never learned). `flushEvents` settles verdicts into the
|
|
582
|
+
// Outbox, so its outcome is likewise unknown on a lost response.
|
|
583
|
+
"appendEvent",
|
|
584
|
+
"flushEvents",
|
|
578
585
|
// `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
|
|
579
586
|
// dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
|
|
580
587
|
"rawExec",
|
|
@@ -1095,6 +1102,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1095
1102
|
// `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
|
|
1096
1103
|
// resolution here guarantees the rows have already been applied by the materializer.
|
|
1097
1104
|
const hydratedPending = new Map<string, () => void>();
|
|
1105
|
+
// The Event lane's two tab-side subscriber sets (ADR-0053 decision 2). The worker holds ONE Outbox and
|
|
1106
|
+
// broadcasts its transitions/reports; each tab fans them out to its own observers. `lastOutboxStatus`
|
|
1107
|
+
// caches the most recent broadcast so a subscriber arriving between transitions is served without a
|
|
1108
|
+
// round trip (a tab that has seen NO broadcast pulls the current state instead).
|
|
1109
|
+
const outboxStatusListeners = new Set<(status: OutboxStatus) => void>();
|
|
1110
|
+
const eventLaneReportListeners = new Set<(report: EventLaneReport) => void>();
|
|
1111
|
+
let lastOutboxStatus: OutboxStatus | null = null;
|
|
1098
1112
|
// Set once this tab detaches (explicit `stop()` OR a terminal `pagehide`). Guards NEW operations (they
|
|
1099
1113
|
// reject at once) and lets `detachFromWorker` settle every outstanding promise — the port listener is torn
|
|
1100
1114
|
// down on detach, so an unsettled `rpc`/`live-initial` waiter would otherwise hang forever (ADR-0040 P2).
|
|
@@ -1186,6 +1200,27 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
1186
1200
|
case "reject":
|
|
1187
1201
|
options.onReject?.(event.details as MutationDetail[]);
|
|
1188
1202
|
break;
|
|
1203
|
+
case "outbox-status": {
|
|
1204
|
+
// The drain signal's transition push (ADR-0053 decision 2), fanned out to this tab's observers and
|
|
1205
|
+
// cached so a later subscriber is served without a pull.
|
|
1206
|
+
const status = event.status as OutboxStatus;
|
|
1207
|
+
lastOutboxStatus = status;
|
|
1208
|
+
for (const listener of outboxStatusListeners) listener(status);
|
|
1209
|
+
break;
|
|
1210
|
+
}
|
|
1211
|
+
case "event-lane-report": {
|
|
1212
|
+
const report = event.report as EventLaneReport;
|
|
1213
|
+
if (eventLaneReportListeners.size === 0) {
|
|
1214
|
+
// The default warn lives HERE, not in the worker: the engine always has the bridge as a
|
|
1215
|
+
// subscriber, and a SharedWorker's console is invisible anyway. Same `onDeadLetter` rule — a
|
|
1216
|
+
// terminal verdict must never be silent, because once the row is deleted the Outbox cannot
|
|
1217
|
+
// answer for it.
|
|
1218
|
+
console.warn("pgxsinkit: event-lane report (no `onEventLaneReport` subscriber)", report);
|
|
1219
|
+
break;
|
|
1220
|
+
}
|
|
1221
|
+
for (const listener of eventLaneReportListeners) listener(report);
|
|
1222
|
+
break;
|
|
1223
|
+
}
|
|
1189
1224
|
case "schema-change":
|
|
1190
1225
|
options.onSchemaChange?.(event.event as LocalStoreVersionEvent);
|
|
1191
1226
|
break;
|
|
@@ -2226,7 +2261,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2226
2261
|
const peers = await queryDestroyPeers();
|
|
2227
2262
|
if (peers > 1) throw new StoreDestroyRefusedError(peers);
|
|
2228
2263
|
if (!destroyOptions?.force) {
|
|
2229
|
-
const { mutation } = await client.diagnostics();
|
|
2264
|
+
const { mutation, outbox } = await client.diagnostics();
|
|
2230
2265
|
const owed =
|
|
2231
2266
|
mutation.pendingCount +
|
|
2232
2267
|
mutation.sendingCount +
|
|
@@ -2238,6 +2273,16 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2238
2273
|
`destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
|
|
2239
2274
|
);
|
|
2240
2275
|
}
|
|
2276
|
+
// ADR-0053 decision 8, the Event lane's half of the same refusal. It rides the diagnostics round
|
|
2277
|
+
// trip already taken above rather than a second one: the tab has no local Outbox (exactly as it has
|
|
2278
|
+
// no local journal), and a destroy must not add a network-shaped hop it can avoid. Absent `outbox`
|
|
2279
|
+
// means the engine has no Event lane, which is not a reason to block a destroy.
|
|
2280
|
+
if (outbox?.empty === false) {
|
|
2281
|
+
throw new Error(
|
|
2282
|
+
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
2283
|
+
"Flush them first (`flushEvents()`) or call destroy({ force: true }).",
|
|
2284
|
+
);
|
|
2285
|
+
}
|
|
2241
2286
|
}
|
|
2242
2287
|
const storePath = resolveDestroyStorePath();
|
|
2243
2288
|
// ADR-0049 D8 ordering (elected placement): RETIRE this tab's own elected engine and AWAIT its teardown —
|
|
@@ -2253,6 +2298,40 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2253
2298
|
await runStoreDestruction(effects);
|
|
2254
2299
|
},
|
|
2255
2300
|
dropReadCache: notSupported("client.dropReadCache"),
|
|
2301
|
+
// The Event lane (ADR-0053) over the bridge. `appendEvent` is ONE round trip — the validation, the
|
|
2302
|
+
// stamps, and the durable insert all run on the worker's engine, so both client forms share one
|
|
2303
|
+
// implementation and one Outbox; a refusal rebuilds tab-side as the same name-tagged error.
|
|
2304
|
+
appendEvent: (stream, payload) => rpc<EventAppendResult>("appendEvent", [stream, payload]),
|
|
2305
|
+
flushEvents: () => rpc<void>("flushEvents", []),
|
|
2306
|
+
outboxStatus: () => rpc<OutboxStatus>("outboxStatus", []),
|
|
2307
|
+
onOutboxStatus: (listener) => {
|
|
2308
|
+
outboxStatusListeners.add(listener);
|
|
2309
|
+
// Current state on subscribe, matching the in-process contract. The engine broadcasts TRANSITIONS
|
|
2310
|
+
// only, so a tab that attached after the last one has nothing to fold — pull it (the `bootReport`
|
|
2311
|
+
// pull/push pattern). A cached broadcast, when we have one, answers synchronously-enough without a
|
|
2312
|
+
// round trip. A failed pull (detached, or a lane-less engine) leaves the subscription silent rather
|
|
2313
|
+
// than throwing at an observer.
|
|
2314
|
+
if (lastOutboxStatus != null) {
|
|
2315
|
+
listener(lastOutboxStatus);
|
|
2316
|
+
} else {
|
|
2317
|
+
void client
|
|
2318
|
+
.outboxStatus()
|
|
2319
|
+
.then((status) => {
|
|
2320
|
+
lastOutboxStatus ??= status;
|
|
2321
|
+
if (outboxStatusListeners.has(listener)) listener(status);
|
|
2322
|
+
})
|
|
2323
|
+
.catch(() => undefined);
|
|
2324
|
+
}
|
|
2325
|
+
return () => {
|
|
2326
|
+
outboxStatusListeners.delete(listener);
|
|
2327
|
+
};
|
|
2328
|
+
},
|
|
2329
|
+
onEventLaneReport: (listener) => {
|
|
2330
|
+
eventLaneReportListeners.add(listener);
|
|
2331
|
+
return () => {
|
|
2332
|
+
eventLaneReportListeners.delete(listener);
|
|
2333
|
+
};
|
|
2334
|
+
},
|
|
2256
2335
|
flush: (table) => rpc<void>("flush", [table]),
|
|
2257
2336
|
reconcile: (table) => rpc<void>("reconcile", [table]),
|
|
2258
2337
|
retryFailed: (table) => rpc<void>("retryFailed", [table]),
|
|
@@ -2275,7 +2354,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2275
2354
|
},
|
|
2276
2355
|
discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
|
|
2277
2356
|
discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
|
|
2278
|
-
diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
|
|
2357
|
+
diagnostics: (table) => rpc<{ mutation: MutationDiagnostics; outbox?: OutboxStatus }>("diagnostics", [table]),
|
|
2279
2358
|
// The registry-wide mutation-status API (slice 4) over the SAME factory the in-process client uses,
|
|
2280
2359
|
// wired to this facade's shared seams: the live-rows bridge (`subscribeLiveRows`) and the one-shot
|
|
2281
2360
|
// `rawQuery` RPC. No new bridge message — `client.mutations` behaves identically to the in-process client.
|
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
30
30
|
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
31
31
|
import { describeErrorChain } from "../error-chain";
|
|
32
|
+
import type { EventLaneOptions } from "../event-lane";
|
|
32
33
|
import {
|
|
33
34
|
type ClientPGlite,
|
|
34
35
|
createClientPGlite,
|
|
@@ -143,6 +144,17 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
143
144
|
storePath?: string;
|
|
144
145
|
maxMutationAttempts?: number;
|
|
145
146
|
syncEnabled?: boolean;
|
|
147
|
+
/**
|
|
148
|
+
* The **Event lane**'s ingestion endpoint (ADR-0053 decision 3). Omit it and the worker derives it from
|
|
149
|
+
* {@link batchWriteUrl} (`…/api/mutations` → `…/api/events`). See `createSyncClient`'s `batchEventUrl`.
|
|
150
|
+
*/
|
|
151
|
+
batchEventUrl?: string;
|
|
152
|
+
/**
|
|
153
|
+
* The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff, and
|
|
154
|
+
* per-Event-stream overrides. A worker-ENTRY option, never an attach option — flush cadence is one
|
|
155
|
+
* engine-wide policy, and the Outbox it drains is shared by every attached tab.
|
|
156
|
+
*/
|
|
157
|
+
events?: EventLaneOptions;
|
|
146
158
|
/**
|
|
147
159
|
* How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull
|
|
148
160
|
* broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.
|
|
@@ -621,6 +633,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
621
633
|
...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
|
|
622
634
|
...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),
|
|
623
635
|
...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
|
|
636
|
+
// The Event lane (ADR-0053): endpoint + flush policy are worker-entry config, exactly like the write
|
|
637
|
+
// path's. The Outbox is engine-wide, so one policy governs every attached tab's appends.
|
|
638
|
+
...(options.batchEventUrl ? { batchEventUrl: options.batchEventUrl } : {}),
|
|
639
|
+
...(options.events ? { events: options.events } : {}),
|
|
624
640
|
onStatusChange: (status) => emitStatus(status),
|
|
625
641
|
onConflict: (details) => broadcastEvent({ kind: "conflict", details }),
|
|
626
642
|
onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
|
|
@@ -643,6 +659,25 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
643
659
|
|
|
644
660
|
const whenBooted = () => bootedPromise;
|
|
645
661
|
|
|
662
|
+
// ─── Event-lane broadcast bridge (ADR-0053 decision 2) ───────────────────────────────────────────
|
|
663
|
+
// ONE Outbox lives in the worker, so the engine's two observation surfaces are subscribed ONCE here and
|
|
664
|
+
// fanned out to every attached port. The drain signal's push carries only TRANSITIONS (the engine's own
|
|
665
|
+
// semantics); a tab attaching later folds the current state from the `outboxStatus` pull instead, exactly
|
|
666
|
+
// as a late attach folds the boot report. Subscribing here also means the ENGINE always has a report
|
|
667
|
+
// subscriber, so its no-subscriber warn never fires in the worker's invisible console — the tab-side
|
|
668
|
+
// surface owns that default logging, where a developer can actually see it.
|
|
669
|
+
const wireEventLaneBroadcast = (booted: SyncClient<TRegistry>): void => {
|
|
670
|
+
try {
|
|
671
|
+
booted.onOutboxStatus((status) => broadcastEvent({ kind: "outbox-status", status }));
|
|
672
|
+
booted.onEventLaneReport((report) => broadcastEvent({ kind: "event-lane-report", report }));
|
|
673
|
+
} catch (error) {
|
|
674
|
+
// A client with no Event lane (a non-canonical write URL, or a caller-owned PGlite) refuses these
|
|
675
|
+
// subscriptions. Nothing to bridge then — the RPCs refuse identically, so the tab still gets the
|
|
676
|
+
// honest error at its own call site.
|
|
677
|
+
syncDebug("worker: no Event lane to bridge", { error });
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
|
|
646
681
|
// ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
|
|
647
682
|
const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
|
|
648
683
|
// Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
|
|
@@ -707,6 +742,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
707
742
|
return active.desync(args[0] as TableKey);
|
|
708
743
|
case "discardEphemeral":
|
|
709
744
|
return active.discardEphemeral(args[0] as TableKey);
|
|
745
|
+
case "appendEvent":
|
|
746
|
+
// The Event lane (ADR-0053 decision 2) in ONE round trip: validation (the registered zod schema +
|
|
747
|
+
// the payload-size cap), the uuid/`occurredAtUs` stamps, and the durable Outbox insert all happen
|
|
748
|
+
// HERE, on the engine that owns the store — so the attach client and the in-process client share one
|
|
749
|
+
// implementation. A refusal rejects the RPC and rebuilds tab-side as the same name-tagged error.
|
|
750
|
+
return active.appendEvent(args[0] as string, args[1]);
|
|
751
|
+
case "flushEvents":
|
|
752
|
+
return active.flushEvents();
|
|
753
|
+
case "outboxStatus":
|
|
754
|
+
// The drain signal's PULL: a tab attaching after the engine's last transition has no broadcast to
|
|
755
|
+
// fold, so its first `onOutboxStatus` subscriber is served from this (the `bootReport` pattern).
|
|
756
|
+
return active.outboxStatus();
|
|
710
757
|
case "ensureSynced":
|
|
711
758
|
// Lazy activation (ADR-0021) on the worker's real client. Engine-wide but additive/idempotent — a tab
|
|
712
759
|
// activating a group another tab already started is a no-op, so no cross-tab revert hazard (cf. desync).
|
|
@@ -1152,6 +1199,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
1152
1199
|
// and fold the current set into every subsequent ack for late attachers.
|
|
1153
1200
|
if (!milestonesWired) {
|
|
1154
1201
|
milestonesWired = true;
|
|
1202
|
+
wireEventLaneBroadcast(booted);
|
|
1155
1203
|
void booted.writeReady.then(
|
|
1156
1204
|
() => markMilestone("writeReady"),
|
|
1157
1205
|
(error: unknown) => failMilestone("writeReady", error),
|
package/src/worker/protocol.ts
CHANGED
|
@@ -290,6 +290,14 @@ export type RpcOp =
|
|
|
290
290
|
| "discardQuarantined"
|
|
291
291
|
| "desync"
|
|
292
292
|
| "discardEphemeral"
|
|
293
|
+
// The Event lane (ADR-0053 decision 2). `appendEvent` is ONE round trip carrying `[stream, payload]`: the
|
|
294
|
+
// registered zod validation, the size cap, and the uuid/timestamp stamps all run WORKER-side on the shared
|
|
295
|
+
// engine, so both client forms share one implementation and one Outbox. It rejects with the same typed
|
|
296
|
+
// refusals (name-tagged across the bridge). `flushEvents` is the manual drain; `outboxStatus` is the PULL
|
|
297
|
+
// that gives a newly-attached tab the drain signal's CURRENT state (the push is the `outbox-status` event).
|
|
298
|
+
| "appendEvent"
|
|
299
|
+
| "flushEvents"
|
|
300
|
+
| "outboxStatus"
|
|
293
301
|
// Lazy activation (ADR-0021): start the consistency groups of the given relation keys on the shared engine.
|
|
294
302
|
// Engine-WIDE but additive/idempotent (unlike `desync`), so it is a plain fire-and-await RPC — carries
|
|
295
303
|
// `[keys]`, resolves once the streams are started (catch-up may still be in flight).
|
|
@@ -467,6 +475,12 @@ export type BridgeEvent =
|
|
|
467
475
|
| { kind: "conflict"; details: unknown }
|
|
468
476
|
| { kind: "quarantine"; details: unknown }
|
|
469
477
|
| { kind: "reject"; details: unknown }
|
|
478
|
+
// The Event lane's two observation surfaces (ADR-0053 decision 2), broadcast from the engine's single
|
|
479
|
+
// Outbox to every attached tab. `outbox-status` is the drain signal's TRANSITION push (a tab that attaches
|
|
480
|
+
// later folds the current state from the `outboxStatus` pull instead); `event-lane-report` carries one
|
|
481
|
+
// flush pass's terminal verdicts, deferred verdicts, and backoff transitions.
|
|
482
|
+
| { kind: "outbox-status"; status: unknown }
|
|
483
|
+
| { kind: "event-lane-report"; report: unknown }
|
|
470
484
|
| { kind: "schema-change"; event: unknown }
|
|
471
485
|
| { kind: "sync-error"; message: string }
|
|
472
486
|
| { kind: "timing"; label: string; ms: number; data?: Record<string, unknown> }
|