@pgxsinkit/client 0.2.4 → 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 +103 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2886 -2009
- package/dist/index.js.map +18 -16
- 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/read-stream-stall.d.ts +54 -0
- package/dist/read-stream-stall.d.ts.map +1 -0
- package/dist/schema.d.ts +37 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +11 -0
- package/dist/shape-sync.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 +326 -8
- package/src/local-tables.ts +48 -1
- package/src/mutation.ts +13 -1
- package/src/read-stream-stall.ts +102 -0
- package/src/schema.ts +81 -1
- package/src/shape-sync.ts +38 -14
- package/src/worker/attach-sync-client.ts +85 -2
- package/src/worker/define-sync-worker.ts +51 -0
- package/src/worker/protocol.ts +14 -0
package/src/index.ts
CHANGED
|
@@ -38,6 +38,17 @@ import { type BootReport, type BootReportBuilder, createBootReportBuilder } from
|
|
|
38
38
|
import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
|
|
39
39
|
import { syncDebug, timeAsync } from "./debug";
|
|
40
40
|
import { describeErrorChain } from "./error-chain";
|
|
41
|
+
import {
|
|
42
|
+
createEventFlushDriver,
|
|
43
|
+
createEventLaneRuntime,
|
|
44
|
+
deriveBatchEventUrl,
|
|
45
|
+
type EventAppendResult,
|
|
46
|
+
type EventFlushDriver,
|
|
47
|
+
type EventLaneOptions,
|
|
48
|
+
type EventLaneReport,
|
|
49
|
+
type EventLaneRuntime,
|
|
50
|
+
type OutboxStatus,
|
|
51
|
+
} from "./event-lane";
|
|
41
52
|
import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
|
|
42
53
|
import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
|
|
43
54
|
import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
|
|
@@ -152,6 +163,39 @@ export {
|
|
|
152
163
|
type StoreExportResult,
|
|
153
164
|
} from "./export-store";
|
|
154
165
|
export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
|
|
166
|
+
// The Event lane's client half (ADR-0053). The runtime/driver factories are exported alongside the types
|
|
167
|
+
// because the lane is composable the same way the mutation runtime is (the harness and tests drive them
|
|
168
|
+
// directly); app code reaches it through `client.appendEvent` / `onOutboxStatus` / `onEventLaneReport`.
|
|
169
|
+
export {
|
|
170
|
+
classifyEventBatchFailure,
|
|
171
|
+
computeEventBackoffMs,
|
|
172
|
+
createEventFlushDriver,
|
|
173
|
+
createEventLaneRuntime,
|
|
174
|
+
DEFAULT_EVENT_BACKOFF_BASE_MS,
|
|
175
|
+
DEFAULT_EVENT_BACKOFF_CEILING_MS,
|
|
176
|
+
DEFAULT_EVENT_BATCH_SIZE,
|
|
177
|
+
DEFAULT_EVENT_FLUSH_INTERVAL_MS,
|
|
178
|
+
deriveBatchEventUrl,
|
|
179
|
+
type EventAppendResult,
|
|
180
|
+
type EventBackoffOptions,
|
|
181
|
+
type EventFlushDriver,
|
|
182
|
+
type EventFlushDriverOptions,
|
|
183
|
+
type EventFlushGate,
|
|
184
|
+
type EventLaneBackoffTransition,
|
|
185
|
+
type EventLaneDb,
|
|
186
|
+
type EventLaneOptions,
|
|
187
|
+
type EventLaneReport,
|
|
188
|
+
type EventLaneRuntime,
|
|
189
|
+
type EventLaneVerdict,
|
|
190
|
+
EventPayloadInvalidError,
|
|
191
|
+
EventPayloadTooLargeError,
|
|
192
|
+
type EventStreamFlushOptions,
|
|
193
|
+
EventStreamsNotRegisteredError,
|
|
194
|
+
type OutboxStatus,
|
|
195
|
+
parseRetryAfterMs,
|
|
196
|
+
resolveBatchEventUrl,
|
|
197
|
+
UnknownEventStreamError,
|
|
198
|
+
} from "./event-lane";
|
|
155
199
|
export {
|
|
156
200
|
destroyStoreArtifacts,
|
|
157
201
|
type ElectedEngineWorker,
|
|
@@ -254,17 +298,22 @@ export {
|
|
|
254
298
|
type LazyGuardIndex,
|
|
255
299
|
LazyRelationNotActivatedError,
|
|
256
300
|
} from "./lazy-guard";
|
|
301
|
+
// The Outbox's object NAMES are public contract like its shape (ADR-0053 decision 2) — inspection
|
|
302
|
+
// surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
|
|
303
|
+
export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
|
|
257
304
|
export {
|
|
258
305
|
type AllMutationsView,
|
|
259
306
|
getAllMutationsView,
|
|
260
307
|
getJournalTable,
|
|
261
308
|
getLocalMetaTable,
|
|
309
|
+
getOutboxTable,
|
|
262
310
|
getOverlayTable,
|
|
263
311
|
getReadModelView,
|
|
264
312
|
getSyncedLocalTable,
|
|
265
313
|
getSyncStateView,
|
|
266
314
|
type JournalTable,
|
|
267
315
|
type LocalMetaTable,
|
|
316
|
+
type OutboxTable,
|
|
268
317
|
type OverlayTable,
|
|
269
318
|
type ReadModelView,
|
|
270
319
|
type SyncStateView,
|
|
@@ -401,6 +450,20 @@ const OPFS_OPEN_ATTEMPTS = 10;
|
|
|
401
450
|
const OPFS_OPEN_BACKOFF_MS = 100;
|
|
402
451
|
/** The opfs-repacked store extent size (ADR-0049 step 10a). */
|
|
403
452
|
const OPFS_STORE_EXTENT_SIZE = 65536;
|
|
453
|
+
/**
|
|
454
|
+
* `status.lastError` for a read stream that cannot reach the server at all (board ADR-0010). Unlike every
|
|
455
|
+
* other `degraded` cause there is no Error to describe: Electric's `onFailedAttempt` carries no argument,
|
|
456
|
+
* because the failure never escaped its retry wrapper. The string says what is knowable and no more.
|
|
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.
|
|
463
|
+
*/
|
|
464
|
+
const READ_SILENCE_MS = 45_000;
|
|
465
|
+
/** `status.lastError` for the read-silence watchdog: nothing failed — that is exactly the problem. */
|
|
466
|
+
const READ_STREAM_SILENT = "read stream silent: no server response inside the silence window while reporting ready";
|
|
404
467
|
/**
|
|
405
468
|
* Non-enumerable brand stamped on an opfs-repacked instance {@link createClientPGlite} mints (ADR-0049): the
|
|
406
469
|
* opfs-repacked VFS owns its store on a dedicated OPFS directory and reports NO `dataDir` (a custom VFS, the
|
|
@@ -880,6 +943,15 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
880
943
|
*/
|
|
881
944
|
writeRequestHeaders?: Record<string, string>;
|
|
882
945
|
syncEnabled?: boolean;
|
|
946
|
+
/**
|
|
947
|
+
* 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 (the stall probe hears only settled
|
|
949
|
+
* attempts), nothing delivers — so without this a session that once reached `ready` would report
|
|
950
|
+
* "up to date" for as long as the outage lasts. A healthy stream is never silent (the long-poll cycles
|
|
951
|
+
* ~every 20-25s), so the default of 45s spans two full cycles. Self-recovering: the next delivered batch
|
|
952
|
+
* returns `ready`. Status honesty only — nothing is retired or torn down.
|
|
953
|
+
*/
|
|
954
|
+
readSilenceMs?: number;
|
|
883
955
|
/**
|
|
884
956
|
* The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
|
|
885
957
|
* is DERIVED from the engine home (capability-selected opfs-repacked with IndexedDB fallback in a browser,
|
|
@@ -1042,6 +1114,21 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
|
1042
1114
|
autoSync?: ConvergenceTrigger;
|
|
1043
1115
|
/** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
|
|
1044
1116
|
onConvergencePass?: (error: unknown) => void;
|
|
1117
|
+
/**
|
|
1118
|
+
* The **Event lane**'s ingestion endpoint (ADR-0053 decision 3) — `"/api/events"`, or an absolute
|
|
1119
|
+
* deployment URL ending in it, under the same hard-required-path rule as {@link batchWriteUrl}. Omit it and
|
|
1120
|
+
* the client DERIVES it from `batchWriteUrl` (`…/api/mutations` → `…/api/events`), which is correct for the
|
|
1121
|
+
* ordinary deployment where one `createSyncServer` mounts both; set it explicitly when the two endpoints
|
|
1122
|
+
* are not siblings.
|
|
1123
|
+
*/
|
|
1124
|
+
batchEventUrl?: string;
|
|
1125
|
+
/**
|
|
1126
|
+
* 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 — the registry is the contract, cadence is
|
|
1128
|
+
* deployment tuning, and a batch-size tweak must not surface as a registry diff. Client batching is
|
|
1129
|
+
* additionally clamped by the contracts-level request-shape limits the server enforces independently.
|
|
1130
|
+
*/
|
|
1131
|
+
events?: EventLaneOptions;
|
|
1045
1132
|
/**
|
|
1046
1133
|
* Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
|
|
1047
1134
|
* The runtime enters the `degraded` phase and holds the read cache at the last applied commit
|
|
@@ -1312,23 +1399,86 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1312
1399
|
haltActivity: () => void;
|
|
1313
1400
|
stop: () => Promise<void>;
|
|
1314
1401
|
/**
|
|
1315
|
-
* Wipe the entire local store (synced cache + overlay + journal) and close the handle
|
|
1316
|
-
* (ADR-0005). Refuses if mutations are still owed to the server
|
|
1317
|
-
*
|
|
1402
|
+
* Wipe the entire local store (synced cache + overlay + journal + Outbox) and close the handle
|
|
1403
|
+
* (ADR-0005). Refuses if mutations are still owed to the server — OR if the Outbox still holds staged
|
|
1404
|
+
* events (ADR-0053 decision 8: the same "never discard without a server verdict" rule the owed-mutations
|
|
1405
|
+
* refusal upholds) — unless `force` is set, so it never silently drops un-flushed writes or un-delivered
|
|
1406
|
+
* events. The refusal names which of the two blocked it. Distinct from `stop()`, which only halts sync.
|
|
1318
1407
|
* Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another
|
|
1319
1408
|
* `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather
|
|
1320
1409
|
* than interleaving the wipe with a running export.
|
|
1321
1410
|
*/
|
|
1322
1411
|
destroy: (options?: { force?: boolean }) => Promise<void>;
|
|
1323
1412
|
/**
|
|
1324
|
-
* Drop and rebuild the reconstructible synced read cache, preserving the overlay
|
|
1325
|
-
* mutation journal (ADR-0006
|
|
1413
|
+
* Drop and rebuild the reconstructible synced read cache, preserving the overlay, the
|
|
1414
|
+
* mutation journal, and the Outbox (ADR-0006; ADR-0053 decision 8 — the Outbox is not read cache, so this
|
|
1415
|
+
* never touches it). The next sync refills it. Use to recover from a corrupt or
|
|
1326
1416
|
* stale read cache without losing un-flushed writes. Runs under the single lifecycle slot
|
|
1327
1417
|
* (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a
|
|
1328
1418
|
* half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
|
|
1329
1419
|
* {@link LifecycleBusyError}.
|
|
1330
1420
|
*/
|
|
1331
1421
|
dropReadCache: () => Promise<void>;
|
|
1422
|
+
/**
|
|
1423
|
+
* Append one client event to the **Outbox** (ADR-0053 decision 2) — the Event lane's entry point, and the
|
|
1424
|
+
* only way an app produces an event. Fire-and-forget by design: nothing echoes back, nothing is overlaid,
|
|
1425
|
+
* nothing converges. The promise resolves on DURABLE local enqueue under the store's declared durability,
|
|
1426
|
+
* NOT on delivery; the flush loop drains the Outbox in the background (and after reconnect/boot), and the
|
|
1427
|
+
* server's per-event verdicts surface on {@link onEventLaneReport}.
|
|
1428
|
+
*
|
|
1429
|
+
* Four refusals, all synchronous call-site failures rather than runtime conditions — the invariant
|
|
1430
|
+
* "everything in the Outbox is well-formed" is what the flush loop and any best-guess view lean on:
|
|
1431
|
+
*
|
|
1432
|
+
* - no Event stream registered at all → {@link EventStreamsNotRegisteredError};
|
|
1433
|
+
* - an unregistered Event-stream name → {@link UnknownEventStreamError};
|
|
1434
|
+
* - a payload failing the stream's registered zod schema → {@link EventPayloadInvalidError};
|
|
1435
|
+
* - a serialized payload over the contracts-level per-event cap → {@link EventPayloadTooLargeError}.
|
|
1436
|
+
*
|
|
1437
|
+
* The library stamps `eventId` (uuid — the server's dedupe key, which is what makes at-least-once delivery
|
|
1438
|
+
* idempotent end-to-end) and `occurredAtUs`, and returns both plus the local append ordinal.
|
|
1439
|
+
*
|
|
1440
|
+
* `stream`/`payload` are typed as `string`/`unknown`: a registry's Event streams ride a symbol and are
|
|
1441
|
+
* type-erased by `defineSyncRegistry`'s return type, so the REGISTERED ZOD SCHEMA is the enforced contract
|
|
1442
|
+
* (at append, and again at ingest for non-library callers).
|
|
1443
|
+
*/
|
|
1444
|
+
appendEvent: (stream: string, payload: unknown) => Promise<EventAppendResult>;
|
|
1445
|
+
/**
|
|
1446
|
+
* Drain the Outbox now — the Event lane's manual primitive, the twin of {@link flush}. Assembles batches
|
|
1447
|
+
* in append (`seq`) order across every Event stream, POSTs them, and applies the per-event verdicts, until
|
|
1448
|
+
* nothing more is eligible this pass. A no-op while the lane is in batch-level backoff, and a no-op for a
|
|
1449
|
+
* registry with no Event streams. With `autoSync` installed the lane drives itself (appends nudge a pass,
|
|
1450
|
+
* an interval is the fallback, and boot/reconnect drain what was written offline); this is the escape
|
|
1451
|
+
* hatch for a fully-manual host.
|
|
1452
|
+
*/
|
|
1453
|
+
flushEvents: () => Promise<void>;
|
|
1454
|
+
/**
|
|
1455
|
+
* The **drain signal** (ADR-0053 decision 2): subscribe to the Outbox's empty ↔ non-empty transitions, with
|
|
1456
|
+
* the CURRENT state delivered on subscribe. Returns an unsubscribe.
|
|
1457
|
+
*
|
|
1458
|
+
* The invalidation hook for a best-guess view that composes pending events with down-synced aggregates:
|
|
1459
|
+
* when the Outbox drains, the aggregate is authoritative again. Deliberately carries no count — a count
|
|
1460
|
+
* that updates only on transitions is stale by construction, and one that updates per append is a worse
|
|
1461
|
+
* live query; for richer detail, query the Outbox table (`getOutboxTable(registry)`).
|
|
1462
|
+
*/
|
|
1463
|
+
onOutboxStatus: (listener: (status: OutboxStatus) => void) => () => void;
|
|
1464
|
+
/**
|
|
1465
|
+
* The drain signal as a one-shot READ — the pull twin of {@link onOutboxStatus}'s push (the
|
|
1466
|
+
* {@link bootReport} pattern). Reads the store, so it is always current: a tab attaching long after the
|
|
1467
|
+
* engine's last transition folds its initial state from here rather than waiting for the next one.
|
|
1468
|
+
*/
|
|
1469
|
+
outboxStatus: () => Promise<OutboxStatus>;
|
|
1470
|
+
/**
|
|
1471
|
+
* The Event lane's verdict/report surface (ADR-0053 decision 2): per flush pass, the TERMINAL non-`acked`
|
|
1472
|
+
* verdicts (`refused` — the server's gating hook said no; `rejected` — a schema-invalid or oversized
|
|
1473
|
+
* payload for a KNOWN stream), the `deferred` ones (an Event stream the server does not yet know — ordinary
|
|
1474
|
+
* rollout skew; the rows stay and retry), and the batch-level backoff transitions. `acked` is not reported:
|
|
1475
|
+
* a high-volume append-only lane would drown the app in its own success.
|
|
1476
|
+
*
|
|
1477
|
+
* An EPHEMERAL subscription, deliberately — a durable client-side verdict table would be retention-bearing
|
|
1478
|
+
* state for a debugging need. With nothing subscribed the library logs each report at warn level rather
|
|
1479
|
+
* than dropping it, because once a terminal row is deleted the Outbox cannot answer what happened to it.
|
|
1480
|
+
*/
|
|
1481
|
+
onEventLaneReport: (listener: (report: EventLaneReport) => void) => () => void;
|
|
1332
1482
|
flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
1333
1483
|
reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
1334
1484
|
retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
@@ -1368,7 +1518,16 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
1368
1518
|
table: TKey,
|
|
1369
1519
|
entityKey: Record<string, string>,
|
|
1370
1520
|
) => Promise<void>;
|
|
1371
|
-
|
|
1521
|
+
/**
|
|
1522
|
+
* The store's owed-state diagnostics: the mutation journal's per-status counts, plus — when this client has
|
|
1523
|
+
* an Event lane — the Outbox's drain signal (ADR-0053 decision 8: the Event lane's durable state takes a
|
|
1524
|
+
* 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.
|
|
1526
|
+
*/
|
|
1527
|
+
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
|
|
1528
|
+
mutation: MutationDiagnostics;
|
|
1529
|
+
outbox?: OutboxStatus;
|
|
1530
|
+
}>;
|
|
1372
1531
|
/**
|
|
1373
1532
|
* The registry-wide reactive mutation-status surface: a global per-status summary and a
|
|
1374
1533
|
* filtered normalized detail list over EVERY writable journal, each available one-shot or as a live
|
|
@@ -2002,6 +2161,36 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2002
2161
|
// `onSyncActivity` must not clear it.
|
|
2003
2162
|
let degradedReason: "stream" | "commit" | null = null;
|
|
2004
2163
|
|
|
2164
|
+
// ─── Read-silence watchdog ───────────────────────────────────────────────────────────────────────
|
|
2165
|
+
// The "up to date offline" lie: a pulled cable HANGS the live long-poll, so the stall probe (which hears
|
|
2166
|
+
// only SETTLED attempts) stays quiet and no batch ever delivers — a runtime that reached `ready` this
|
|
2167
|
+
// session would claim it for the whole outage, and in worker mode broadcast that claim to every attaching
|
|
2168
|
+
// tab. Silence past the window while claiming `ready` is therefore itself the evidence, and the phase
|
|
2169
|
+
// drops to the shared stream-degraded state, recovering exactly where every stream flavour does (the next
|
|
2170
|
+
// delivered batch). This is timing-based STATUS honesty, not timing-based retirement — nothing is torn
|
|
2171
|
+
// down or restarted (ADR-0049 D5 governs the latter). Armed on `ready` and re-armed on every activity;
|
|
2172
|
+
// never armed with sync disabled (`ready` there means "boot complete", with no server to hear from).
|
|
2173
|
+
const readSilenceMs = options.readSilenceMs ?? READ_SILENCE_MS;
|
|
2174
|
+
let readSilenceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
2175
|
+
const clearReadSilenceWatchdog = (): void => {
|
|
2176
|
+
if (readSilenceTimer != null) {
|
|
2177
|
+
clearTimeout(readSilenceTimer);
|
|
2178
|
+
readSilenceTimer = null;
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
const armReadSilenceWatchdog = (): void => {
|
|
2182
|
+
if (!syncEnabled) return;
|
|
2183
|
+
clearReadSilenceWatchdog();
|
|
2184
|
+
readSilenceTimer = setTimeout(() => {
|
|
2185
|
+
readSilenceTimer = null;
|
|
2186
|
+
if (disposed || status.phase !== "ready") return;
|
|
2187
|
+
status.phase = "degraded";
|
|
2188
|
+
degradedReason = "stream";
|
|
2189
|
+
status.lastError = READ_STREAM_SILENT;
|
|
2190
|
+
options.onStatusChange?.(status);
|
|
2191
|
+
}, readSilenceMs);
|
|
2192
|
+
};
|
|
2193
|
+
|
|
2005
2194
|
// ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────
|
|
2006
2195
|
// On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape
|
|
2007
2196
|
// catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which
|
|
@@ -2060,6 +2249,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2060
2249
|
// finalize below never double-fires it.
|
|
2061
2250
|
finalizeBootReport();
|
|
2062
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();
|
|
2063
2255
|
},
|
|
2064
2256
|
onSyncError: (error) => {
|
|
2065
2257
|
// A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than
|
|
@@ -2088,6 +2280,25 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2088
2280
|
status.lastError = describeErrorChain(error);
|
|
2089
2281
|
options.onStatusChange?.(status);
|
|
2090
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
|
+
},
|
|
2091
2302
|
// Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
|
|
2092
2303
|
// again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,
|
|
2093
2304
|
// so only `onSyncError` clearing (a clean commit) would lift it.
|
|
@@ -2097,6 +2308,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2097
2308
|
status.phase = initialSyncCompleted ? "ready" : "syncing";
|
|
2098
2309
|
options.onStatusChange?.(status);
|
|
2099
2310
|
}
|
|
2311
|
+
// Every delivered batch (including a bare up-to-date) is proof of life: re-arm the silence window.
|
|
2312
|
+
// Harmless pre-`ready` — the watchdog's callback only ever acts on a runtime claiming `ready`.
|
|
2313
|
+
armReadSilenceWatchdog();
|
|
2100
2314
|
},
|
|
2101
2315
|
// ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the
|
|
2102
2316
|
// app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token
|
|
@@ -2208,6 +2422,35 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2208
2422
|
...(options.onReject ? { onReject: options.onReject } : {}),
|
|
2209
2423
|
});
|
|
2210
2424
|
|
|
2425
|
+
// The Event lane (ADR-0053). Constructed on EVERY boot, registry streams or not: the Outbox DDL is
|
|
2426
|
+
// stream-independent and the runtime is inert without streams (`appendEvent` throws, `flushEvents` no-ops,
|
|
2427
|
+
// no driver is stood up), so there is no conditional to get wrong when a registry gains its first stream.
|
|
2428
|
+
// The ingestion endpoint is the mutation endpoint's sibling — derived from `batchWriteUrl` unless the
|
|
2429
|
+
// consumer names it — and it shares the write path's headers (same ingress, same gateway credentials).
|
|
2430
|
+
// A caller-owned PGlite (`pgliteInstance`) never had the toolkit's schema applied, so the Outbox table may
|
|
2431
|
+
// not exist: the lane stays unconstructed there, exactly as the meta-table marker is left alone.
|
|
2432
|
+
const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
|
|
2433
|
+
const eventLane: EventLaneRuntime | null =
|
|
2434
|
+
eventLaneUrl != null && !options.pgliteInstance
|
|
2435
|
+
? createEventLaneRuntime({
|
|
2436
|
+
db: pglite,
|
|
2437
|
+
registry: options.registry,
|
|
2438
|
+
batchEventUrl: eventLaneUrl,
|
|
2439
|
+
...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
|
|
2440
|
+
...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
|
|
2441
|
+
...(options.events ? { events: options.events } : {}),
|
|
2442
|
+
})
|
|
2443
|
+
: null;
|
|
2444
|
+
/** The refusal a lane-less client gives, naming the two ways a lane can be absent. */
|
|
2445
|
+
const requireEventLane = (): EventLaneRuntime => {
|
|
2446
|
+
if (eventLane) return eventLane;
|
|
2447
|
+
throw new Error(
|
|
2448
|
+
"pgxsinkit: the Event lane is not available on this client — either `batchWriteUrl` is not the canonical " +
|
|
2449
|
+
'"…/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' +
|
|
2450
|
+
"`pgliteInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
|
|
2451
|
+
);
|
|
2452
|
+
};
|
|
2453
|
+
|
|
2211
2454
|
// Activation buffer (ADR-0041): a read (`ensureSynced`) OR a write (`onOrdinaryEnqueue`) can reference a
|
|
2212
2455
|
// lazy group after `localReadReady` but BEFORE `sync` is wired (the Option B window). With a null `sync` the
|
|
2213
2456
|
// seams cannot start a group, so BOTH feed this one buffer; the tail replays it once sync is wired, so the
|
|
@@ -2273,6 +2516,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2273
2516
|
|
|
2274
2517
|
let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
|
|
2275
2518
|
let convergenceDriver: ConvergenceDriver | null = null;
|
|
2519
|
+
let eventFlushDriver: EventFlushDriver | null = null;
|
|
2276
2520
|
|
|
2277
2521
|
// Lifecycle guard (ADR-0041): `stop()`/`destroy()` can now be called while the background write/sync tail is
|
|
2278
2522
|
// still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
|
|
@@ -2302,6 +2546,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2302
2546
|
// manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
|
|
2303
2547
|
const quiesceTailForTeardown = async (): Promise<void> => {
|
|
2304
2548
|
disposed = true;
|
|
2549
|
+
// A disposed client must leave no pending timer behind (the close-hang discipline): the callback's
|
|
2550
|
+
// `disposed` guard already suppresses a late fire, but the cleared handle is what lets the realm quiesce.
|
|
2551
|
+
clearReadSilenceWatchdog();
|
|
2305
2552
|
// FIX 2: a stopped client can never reach `writeReady` / `ready`, so reject them (idempotent — a race with
|
|
2306
2553
|
// the tail's own resolve is settled first-wins; a normal stop AFTER boot is a no-op on the already-resolved
|
|
2307
2554
|
// promises) so a parked mutation or an `await ready` / `start()` fails FAST rather than hanging past
|
|
@@ -2324,9 +2571,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2324
2571
|
// after; this only guarantees the network + scheduling are already dead when it does.
|
|
2325
2572
|
const haltActivity = (): void => {
|
|
2326
2573
|
disposed = true;
|
|
2574
|
+
clearReadSilenceWatchdog();
|
|
2327
2575
|
mutationRuntime.abortInFlight();
|
|
2576
|
+
// The Event lane's in-flight POST is aborted on the same synchronous edge as the write path's: a flush
|
|
2577
|
+
// must not still be settling verdicts into a store the teardown is about to close.
|
|
2578
|
+
eventLane?.abortInFlight();
|
|
2328
2579
|
void engine.close();
|
|
2329
2580
|
void convergenceDriver?.stop();
|
|
2581
|
+
void eventFlushDriver?.stop();
|
|
2330
2582
|
};
|
|
2331
2583
|
|
|
2332
2584
|
// The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
|
|
@@ -2448,6 +2700,30 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2448
2700
|
);
|
|
2449
2701
|
}
|
|
2450
2702
|
|
|
2703
|
+
// The Event-lane flush driver (ADR-0053 decision 3), standing on the SAME scheduling seam as convergence:
|
|
2704
|
+
// one `autoSync` trigger answers both "is the app online/foregrounded?" (the offline pause) and "something
|
|
2705
|
+
// changed, try now" (online/visibility signals). It keeps its own, slower interval — an append nudges a
|
|
2706
|
+
// pass, so the interval only has to catch retries and recovery — and `start()` runs a pass immediately,
|
|
2707
|
+
// which is what drains events written offline after a boot or reconnect with no new append.
|
|
2708
|
+
//
|
|
2709
|
+
// Gated exactly like convergence on a restore boot that stays OFFLINE, for the mirrored reason: recovered
|
|
2710
|
+
// Outbox rows are NOT quarantined (ADR-0053 decision 8), but a store whose recovered JOURNAL is parked is
|
|
2711
|
+
// being held for human inspection, and starting network activity under it would contradict that.
|
|
2712
|
+
if (eventLane?.hasStreams && options.autoSync && (!restoreBoot || syncEnabled)) {
|
|
2713
|
+
const autoSync = options.autoSync;
|
|
2714
|
+
eventFlushDriver = createEventFlushDriver({
|
|
2715
|
+
flush: () => eventLane.flush(),
|
|
2716
|
+
gate: { subscribe: autoSync.subscribe, shouldFlush: () => autoSync.shouldConverge() },
|
|
2717
|
+
...(options.events?.intervalMs != null ? { intervalMs: options.events.intervalMs } : {}),
|
|
2718
|
+
});
|
|
2719
|
+
// Start once initial sync is ready, mirroring convergence: the first pass never races the first shape
|
|
2720
|
+
// load, and a rejected `ready` (a failed background tail) leaves the driver un-started.
|
|
2721
|
+
void ready.then(
|
|
2722
|
+
() => eventFlushDriver?.start(),
|
|
2723
|
+
() => undefined,
|
|
2724
|
+
);
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2451
2727
|
// Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
|
|
2452
2728
|
// write flushes immediately rather than waiting for the trigger's next interval tick. This is what
|
|
2453
2729
|
// lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
|
|
@@ -2899,8 +3175,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2899
3175
|
// PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
|
|
2900
3176
|
await quiesceTailForTeardown();
|
|
2901
3177
|
// Await any in-flight convergence pass before closing PGlite, so a pass never queries a
|
|
2902
|
-
// closed handle.
|
|
3178
|
+
// closed handle. The Event-lane flush pass is awaited on the same rule, for the same reason.
|
|
2903
3179
|
await convergenceDriver?.stop();
|
|
3180
|
+
await eventFlushDriver?.stop();
|
|
2904
3181
|
sync?.unsubscribe();
|
|
2905
3182
|
status.isRunning = false;
|
|
2906
3183
|
options.onStatusChange?.(status);
|
|
@@ -2938,11 +3215,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
2938
3215
|
`destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
|
|
2939
3216
|
);
|
|
2940
3217
|
}
|
|
3218
|
+
|
|
3219
|
+
// ADR-0053 decision 8: the same refusal, for the Event lane's durable state. A non-empty Outbox
|
|
3220
|
+
// holds events the SERVER has not yet ruled on, and "never discard without a server verdict" is
|
|
3221
|
+
// 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.
|
|
3223
|
+
if (eventLane && !(await eventLane.outboxStatus()).empty) {
|
|
3224
|
+
throw new Error(
|
|
3225
|
+
"destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
|
|
3226
|
+
"Flush them first (`flushEvents()`) or call destroy({ force: true }).",
|
|
3227
|
+
);
|
|
3228
|
+
}
|
|
2941
3229
|
}
|
|
2942
3230
|
|
|
2943
3231
|
// Drain any in-flight convergence pass before wiping, so a pass never writes into a store
|
|
2944
|
-
// being torn down underneath it.
|
|
3232
|
+
// being torn down underneath it. Same for the Event lane's flush pass.
|
|
2945
3233
|
await convergenceDriver?.stop();
|
|
3234
|
+
await eventFlushDriver?.stop();
|
|
2946
3235
|
sync?.unsubscribe();
|
|
2947
3236
|
status.isRunning = false;
|
|
2948
3237
|
options.onStatusChange?.(status);
|
|
@@ -3000,6 +3289,31 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3000
3289
|
})
|
|
3001
3290
|
);
|
|
3002
3291
|
},
|
|
3292
|
+
// The Event lane (ADR-0053). An append touches only the Outbox — no journal, no overlay, no recovery
|
|
3293
|
+
// pass — so it gates on `localReadReady` (the store is open and its durable schema, Outbox included, is
|
|
3294
|
+
// provisioned), NOT on `writeReady`. That is deliberate: an app that instruments its very first paint
|
|
3295
|
+
// should not have its telemetry blocked behind the mutation runtime's boot recovery.
|
|
3296
|
+
appendEvent: async (stream, payload) => {
|
|
3297
|
+
const lane = requireEventLane();
|
|
3298
|
+
await localReadReady;
|
|
3299
|
+
const result = await lane.appendEvent(stream, payload);
|
|
3300
|
+
// Nudge the driver so a fresh event flushes now rather than at the next interval tick — the
|
|
3301
|
+
// event-driven path, coalesced exactly like an interval signal (and a no-op when no driver runs).
|
|
3302
|
+
eventFlushDriver?.requestPass();
|
|
3303
|
+
return result;
|
|
3304
|
+
},
|
|
3305
|
+
flushEvents: async () => {
|
|
3306
|
+
const lane = requireEventLane();
|
|
3307
|
+
await localReadReady;
|
|
3308
|
+
return lane.flush();
|
|
3309
|
+
},
|
|
3310
|
+
onOutboxStatus: (listener) => requireEventLane().onOutboxStatus(listener),
|
|
3311
|
+
outboxStatus: async () => {
|
|
3312
|
+
const lane = requireEventLane();
|
|
3313
|
+
await localReadReady;
|
|
3314
|
+
return lane.outboxStatus();
|
|
3315
|
+
},
|
|
3316
|
+
onEventLaneReport: (listener) => requireEventLane().onEventLaneReport(listener),
|
|
3003
3317
|
// Write-path methods gate on `writeReady` (ADR-0041): each enqueues, drains, or mutates a journal, so
|
|
3004
3318
|
// none may run before the write runtime + boot recovery have completed. `writeReady` is already resolved
|
|
3005
3319
|
// on the steady-state client, so these are settled-promise awaits.
|
|
@@ -3035,6 +3349,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
|
|
|
3035
3349
|
// See the `readMutationDetails` note: a read, ungated, so pre-`writeReady` it may show pre-recovery counts.
|
|
3036
3350
|
diagnostics: async (table) => ({
|
|
3037
3351
|
mutation: await mutationRuntime.readMutationStats(table),
|
|
3352
|
+
// The Event lane's durable state belongs in the store's diagnostics too (ADR-0053 decision 8). It is
|
|
3353
|
+
// the BOOLEAN drain signal, not a count: the read is a `LIMIT 1`, so adding it costs nothing even on
|
|
3354
|
+
// the export drain's polling loop. Absent when this client has no lane at all.
|
|
3355
|
+
...(eventLane ? { outbox: await eventLane.outboxStatus() } : {}),
|
|
3038
3356
|
}),
|
|
3039
3357
|
// The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over
|
|
3040
3358
|
// this client's own `subscribeLiveRows` + `pglite.query` seams — the SAME factory the worker facade uses.
|
package/src/local-tables.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
customType,
|
|
7
7
|
getTableConfig,
|
|
8
8
|
integer,
|
|
9
|
+
jsonb,
|
|
9
10
|
pgSchema,
|
|
10
11
|
pgTable,
|
|
11
12
|
pgView,
|
|
@@ -27,7 +28,7 @@ import {
|
|
|
27
28
|
type SyncTableRegistry,
|
|
28
29
|
} from "@pgxsinkit/contracts";
|
|
29
30
|
|
|
30
|
-
import { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE } from "./schema";
|
|
31
|
+
import { ALL_MUTATIONS_VIEW, LOCAL_META_TABLE, OUTBOX_TABLE } from "./schema";
|
|
31
32
|
|
|
32
33
|
/**
|
|
33
34
|
* Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table
|
|
@@ -146,6 +147,29 @@ const localMetaShape = pgTable(LOCAL_META_TABLE, {
|
|
|
146
147
|
value: text("value").notNull(),
|
|
147
148
|
});
|
|
148
149
|
|
|
150
|
+
/**
|
|
151
|
+
* The **Outbox**'s columns (ADR-0053 decision 2), mirroring the DDL in `schema.ts` — see {@link OUTBOX_TABLE}
|
|
152
|
+
* there for the column-by-column public contract. The `_us` bigints and `seq` are the same `bigintText`
|
|
153
|
+
* passthrough the journal object uses (rows come back through the raw seam UNMAPPED, so the runtime reads
|
|
154
|
+
* them as strings); `payload` is real `jsonb` (PGlite parses it, so the flush loop gets the object back).
|
|
155
|
+
* `seq` is DEFAULTed by the sequence, so an insert omits it — hence no `.notNull()` footgun on `$inferInsert`.
|
|
156
|
+
*/
|
|
157
|
+
function buildOutboxColumns() {
|
|
158
|
+
return {
|
|
159
|
+
seq: bigintText("seq"),
|
|
160
|
+
eventId: uuid("event_id").notNull(),
|
|
161
|
+
stream: text("stream").notNull(),
|
|
162
|
+
occurredAtUs: bigintText("occurred_at_us").notNull(),
|
|
163
|
+
payload: jsonb("payload").notNull(),
|
|
164
|
+
enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
|
|
165
|
+
attemptCount: integer("attempt_count").notNull().default(0),
|
|
166
|
+
nextRetryAtUs: bigintText("next_retry_at_us"),
|
|
167
|
+
lastReason: text("last_reason"),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const outboxShape = pgTable(OUTBOX_TABLE, buildOutboxColumns());
|
|
172
|
+
|
|
149
173
|
/**
|
|
150
174
|
* The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,
|
|
151
175
|
* exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete
|
|
@@ -212,6 +236,8 @@ export type JournalTable = typeof journalShape & { [columnName: string]: PgColum
|
|
|
212
236
|
export type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };
|
|
213
237
|
/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */
|
|
214
238
|
export type LocalMetaTable = typeof localMetaShape;
|
|
239
|
+
/** The `pgxsinkit_outbox` Event-lane staging table (ADR-0053). */
|
|
240
|
+
export type OutboxTable = typeof outboxShape;
|
|
215
241
|
|
|
216
242
|
/**
|
|
217
243
|
* Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)
|
|
@@ -280,6 +306,7 @@ interface EntryLocalTables {
|
|
|
280
306
|
|
|
281
307
|
const localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();
|
|
282
308
|
const localMetaCache = new Map<string, LocalMetaTable>();
|
|
309
|
+
const outboxCache = new Map<string, OutboxTable>();
|
|
283
310
|
|
|
284
311
|
function cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {
|
|
285
312
|
let byKey = localTablesCache.get(registry);
|
|
@@ -585,6 +612,26 @@ export function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsV
|
|
|
585
612
|
return allMutationsShape;
|
|
586
613
|
}
|
|
587
614
|
|
|
615
|
+
/**
|
|
616
|
+
* The **Outbox** (ADR-0053 decision 2) under the registry's local schema, as a runtime Drizzle object — the
|
|
617
|
+
* one relation the Event lane stages into. Registry-WIDE (one table, a `stream` column) and memoized per
|
|
618
|
+
* local schema, exactly like {@link getLocalMetaTable}; it takes the registry only to resolve that schema.
|
|
619
|
+
*
|
|
620
|
+
* Public on purpose: the table's shape is contract, so an app composing a best-guess view (pending events
|
|
621
|
+
* over down-synced aggregates) authors it as tier-① Drizzle instead of hand-written SQL —
|
|
622
|
+
* `client.query((c) => c.drizzle.select().from(getOutboxTable(registry)).where(eq(outbox.stream, "…")))`.
|
|
623
|
+
*/
|
|
624
|
+
export function getOutboxTable(registry: SyncTableRegistry): OutboxTable {
|
|
625
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
626
|
+
const cached = outboxCache.get(localSchema);
|
|
627
|
+
if (cached) {
|
|
628
|
+
return cached;
|
|
629
|
+
}
|
|
630
|
+
const table = makeTable(localSchema, OUTBOX_TABLE, buildOutboxColumns()) as OutboxTable;
|
|
631
|
+
outboxCache.set(localSchema, table);
|
|
632
|
+
return table;
|
|
633
|
+
}
|
|
634
|
+
|
|
588
635
|
/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */
|
|
589
636
|
export function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {
|
|
590
637
|
const localSchema = getSyncRegistrySchema(registry);
|
package/src/mutation.ts
CHANGED
|
@@ -96,6 +96,7 @@ import {
|
|
|
96
96
|
fingerprintRegistry,
|
|
97
97
|
getProjectedColumns as getProjectedTableColumns,
|
|
98
98
|
getSyncRegistrySchema,
|
|
99
|
+
isManagedFieldGuarded,
|
|
99
100
|
maybeQuoteIdentifier,
|
|
100
101
|
quoteIdentifier,
|
|
101
102
|
resolveServerVersionColumnName,
|
|
@@ -3006,6 +3007,17 @@ function resolveMutationUrls(batchWriteUrl: string): { batch: string; authoritat
|
|
|
3006
3007
|
return { batch: batchWriteUrl, authoritative: `${batchWriteUrl}/unit` };
|
|
3007
3008
|
}
|
|
3008
3009
|
|
|
3010
|
+
/**
|
|
3011
|
+
* Drop the server-owned keys from an outgoing payload. What counts as server-owned is decided by
|
|
3012
|
+
* contracts' {@link isManagedFieldGuarded} — the single definition of the guard rule, shared with the
|
|
3013
|
+
* write route's `getGuardedManagedFields` and the apply-function generator, so this strip and the
|
|
3014
|
+
* server's rejection can never disagree (notably: an update strips **every** managed field, a create-only
|
|
3015
|
+
* one included, because it is inert on update and the server 400-rejects a payload carrying it — so
|
|
3016
|
+
* stripping keeps a locally-authored patch from round-tripping to that rejection).
|
|
3017
|
+
*
|
|
3018
|
+
* `SyncTableUpdateInput` already omits every managed key at the type level, so this is the runtime half;
|
|
3019
|
+
* a payload reaching here with a managed key came through an untyped path.
|
|
3020
|
+
*/
|
|
3009
3021
|
function stripManagedFields(
|
|
3010
3022
|
context: TableContext,
|
|
3011
3023
|
payload: Record<string, unknown>,
|
|
@@ -3014,7 +3026,7 @@ function stripManagedFields(
|
|
|
3014
3026
|
const managedColumns = new Set<string>();
|
|
3015
3027
|
|
|
3016
3028
|
for (const mf of context.entry.governance?.managedFields ?? []) {
|
|
3017
|
-
if (mf
|
|
3029
|
+
if (isManagedFieldGuarded(mf, operation)) {
|
|
3018
3030
|
managedColumns.add(mf.column);
|
|
3019
3031
|
}
|
|
3020
3032
|
}
|