@pgxsinkit/client 0.1.53 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +270 -52
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4492 -1511
- package/dist/index.js.map +34 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +4 -4
- package/dist/mutation.d.ts +12 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +235 -12
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +138 -22
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +265 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +15 -10
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -12
- package/skills/operating/SKILL.md +103 -46
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1109 -115
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +2 -2
- package/src/mutation.ts +67 -49
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +63 -63
- package/src/sync/index.ts +2 -2
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1556 -97
- package/src/worker/define-sync-worker.ts +723 -73
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +4 -1
- package/src/worker/protocol.ts +13 -10
- package/src/worker/sw-placement.ts +64 -0
package/src/live-rows-sql.ts
CHANGED
|
@@ -32,7 +32,7 @@ const LIVE_QUERY_TABLE_ALIAS = "__pgx_live";
|
|
|
32
32
|
* keep DISTINCT values). `SELECT *` from the aliased derived table is safe precisely because the alias
|
|
33
33
|
* list has already made the names unique.
|
|
34
34
|
*
|
|
35
|
-
* Returns the SQL UNCHANGED when `fields` is absent or empty — the
|
|
35
|
+
* Returns the SQL UNCHANGED when `fields` is absent or empty — the default path for
|
|
36
36
|
* callers (raw SQL strings, or non-colliding queries that pass no `fields`): they keep name-keyed rows
|
|
37
37
|
* exactly as before. Only a caller that supplies `fields` opts into alias-keyed rows.
|
|
38
38
|
*/
|
package/src/local-store.ts
CHANGED
|
@@ -20,13 +20,6 @@ import {
|
|
|
20
20
|
// its tests own (and mock).
|
|
21
21
|
const metaQueryBuilder = drizzle.mock();
|
|
22
22
|
|
|
23
|
-
/**
|
|
24
|
-
* The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite
|
|
25
|
-
* database was provisioned under is recorded in the local-meta table; comparing it to the
|
|
26
|
-
* current fingerprint on boot is how a registry change is *detected* (rather than a
|
|
27
|
-
* hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
23
|
/** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */
|
|
31
24
|
export interface LocalStoreVersionEvent {
|
|
32
25
|
status: "rebuilt" | "deferred";
|
|
@@ -36,13 +29,13 @@ export interface LocalStoreVersionEvent {
|
|
|
36
29
|
owedMutations: number;
|
|
37
30
|
}
|
|
38
31
|
|
|
39
|
-
/** The
|
|
32
|
+
/** The mutation-runtime surface required by registry reconciliation. */
|
|
40
33
|
interface VersionReconcileRuntime {
|
|
41
34
|
registryVersion: string;
|
|
42
35
|
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
43
36
|
}
|
|
44
37
|
|
|
45
|
-
/** The registry fingerprint the local store was
|
|
38
|
+
/** The registry fingerprint under which the local store was provisioned, or null if unstamped. */
|
|
46
39
|
export async function readStoredRegistryFingerprint(
|
|
47
40
|
db: MutationDb,
|
|
48
41
|
registry: SyncTableRegistry,
|
|
@@ -79,7 +72,7 @@ export async function readActivatedLazyGroups(db: MutationDb, registry: SyncTabl
|
|
|
79
72
|
return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));
|
|
80
73
|
}
|
|
81
74
|
|
|
82
|
-
/** Upsert one meta key — the shared write shape for activations and
|
|
75
|
+
/** Upsert one meta key — the shared write shape for activations, schema identity, and safety markers. */
|
|
83
76
|
async function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {
|
|
84
77
|
const meta = getLocalMetaTable(registry);
|
|
85
78
|
const query = metaQueryBuilder
|
|
@@ -113,7 +106,7 @@ export async function clearLazyGroupActivation(
|
|
|
113
106
|
await db.query(query.sql, query.params as unknown[]);
|
|
114
107
|
}
|
|
115
108
|
|
|
116
|
-
/** Stamp the local store with the fingerprint it is
|
|
109
|
+
/** Stamp the local store with the registry fingerprint it is provisioned under. */
|
|
117
110
|
export async function writeStoredRegistryFingerprint(
|
|
118
111
|
db: MutationDb,
|
|
119
112
|
registry: SyncTableRegistry,
|
|
@@ -123,9 +116,8 @@ export async function writeStoredRegistryFingerprint(
|
|
|
123
116
|
}
|
|
124
117
|
|
|
125
118
|
/**
|
|
126
|
-
* The durable-schema fingerprint the local store was last provisioned under
|
|
127
|
-
* when
|
|
128
|
-
* Follows the raw-seam read shape of {@link readStoredRegistryFingerprint}.
|
|
119
|
+
* The durable-schema fingerprint the local store was last provisioned under, or null
|
|
120
|
+
* when initial provisioning has not completed.
|
|
129
121
|
*/
|
|
130
122
|
export async function readStoredLocalSchemaFingerprint(
|
|
131
123
|
db: MutationDb,
|
|
@@ -145,7 +137,7 @@ export async function readStoredLocalSchemaFingerprint(
|
|
|
145
137
|
|
|
146
138
|
/**
|
|
147
139
|
* Stamp the durable-schema fingerprint the store is now provisioned under (slice 3). Called ONLY after a
|
|
148
|
-
* successful durable-schema exec — every full durable exec (
|
|
140
|
+
* successful durable-schema exec — every full durable exec (initial provisioning,
|
|
149
141
|
* `dropReadCache`) and its stamp travel together, so the fingerprint never claims a schema that was not run.
|
|
150
142
|
*/
|
|
151
143
|
export async function writeStoredLocalSchemaFingerprint(
|
|
@@ -157,10 +149,10 @@ export async function writeStoredLocalSchemaFingerprint(
|
|
|
157
149
|
}
|
|
158
150
|
|
|
159
151
|
/**
|
|
160
|
-
* The durable recovery-required marker
|
|
152
|
+
* The durable recovery-required marker. Its
|
|
161
153
|
* `pgxsinkit_local_meta` value is `"true"` while a `sending` journal row MAY have been committed since the
|
|
162
|
-
* last clean settle, and `"false"` once pgxsinkit has PROVEN no `sending` row remains. Absent
|
|
163
|
-
*
|
|
154
|
+
* last clean settle, and `"false"` once pgxsinkit has PROVEN no `sending` row remains. Absent means the
|
|
155
|
+
* store has not initialized the marker yet: run one conservative recovery pass, then initialize it.
|
|
164
156
|
*
|
|
165
157
|
* The invariant the whole slice protects: **the marker is never `"false"` while a committed `sending`
|
|
166
158
|
* journal row exists.** It is upheld by marker-first ordering — {@link writeMutationRecoveryRequired}(true)
|
|
@@ -172,8 +164,7 @@ export const MUTATION_RECOVERY_REQUIRED_KEY = "mutation_recovery_required";
|
|
|
172
164
|
|
|
173
165
|
/**
|
|
174
166
|
* Read the durable recovery-required marker: `true`/`false` for the stored value, or `null` when the key is
|
|
175
|
-
* absent (
|
|
176
|
-
* {@link readStoredRegistryFingerprint}.
|
|
167
|
+
* absent (the marker has not been initialized).
|
|
177
168
|
*
|
|
178
169
|
* FIX 4 (fail closed): the marker is a SAFETY marker — `false` is the ONLY value that skips recovery, so any
|
|
179
170
|
* present value that is not exactly `"true"` or `"false"` (corruption, a future encoding, stray whitespace, a
|
|
@@ -208,7 +199,7 @@ export async function readMutationRecoveryRequired(
|
|
|
208
199
|
/**
|
|
209
200
|
* Upsert the durable recovery-required marker to `"true"`/`"false"` unconditionally. The `true` write is the
|
|
210
201
|
* marker-first SET (awaited before the first `sending` transition of a dirty epoch); the `false` write
|
|
211
|
-
* initializes an absent
|
|
202
|
+
* initializes an absent marker AFTER a conservative recovery pass has guaranteed no `sending` row remains.
|
|
212
203
|
*/
|
|
213
204
|
export async function writeMutationRecoveryRequired(
|
|
214
205
|
db: MutationDb,
|
|
@@ -224,7 +215,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
|
|
|
224
215
|
}
|
|
225
216
|
|
|
226
217
|
/**
|
|
227
|
-
* Self-verifying clear
|
|
218
|
+
* Self-verifying clear: set the marker to `"false"` in ONE guarded, Drizzle-composed
|
|
228
219
|
* statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built
|
|
229
220
|
* from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS
|
|
230
221
|
* bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays
|
|
@@ -233,7 +224,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
|
|
|
233
224
|
* row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.
|
|
234
225
|
*
|
|
235
226
|
* The marker row must already exist for this UPDATE to take effect; the absent-store INIT is a distinct
|
|
236
|
-
* unconditional {@link writeMutationRecoveryRequired}(false) after the
|
|
227
|
+
* unconditional {@link writeMutationRecoveryRequired}(false) after the initialization pass (a pure guarded UPDATE
|
|
237
228
|
* cannot create the row, and drizzle-rc.4 cannot render a from-less guarded insert-select).
|
|
238
229
|
*/
|
|
239
230
|
export async function clearMutationRecoveryMarkerIfSettled(
|
|
@@ -260,16 +251,9 @@ export async function clearMutationRecoveryMarkerIfSettled(
|
|
|
260
251
|
}
|
|
261
252
|
|
|
262
253
|
/**
|
|
263
|
-
* Reconcile
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
* otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined
|
|
267
|
-
* writes are never silently dropped. The drain happens across sessions: pending writes flush
|
|
268
|
-
* and reconcile during normal use, and the rebuild completes once the journal is clear.
|
|
269
|
-
*
|
|
270
|
-
* An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:
|
|
271
|
-
* the fingerprint mechanism shipped before launch, so every store in existence was
|
|
272
|
-
* provisioned with it (and a stamped store's journal therefore always has `registry_version`).
|
|
254
|
+
* Reconcile a store created by a supported release against the current registry fingerprint. An unstamped
|
|
255
|
+
* store is stamped; an unchanged fingerprint is a no-op. On a change, the read cache is rebuilt only when
|
|
256
|
+
* no mutations are owed. Otherwise the rebuild is deferred until a later boot, preserving local writes.
|
|
273
257
|
*/
|
|
274
258
|
export async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {
|
|
275
259
|
db: MutationDb;
|
|
@@ -293,11 +277,7 @@ export async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegi
|
|
|
293
277
|
return rebuildReadCacheOrDefer(args, stored);
|
|
294
278
|
}
|
|
295
279
|
|
|
296
|
-
/**
|
|
297
|
-
* The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when
|
|
298
|
-
* nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never
|
|
299
|
-
* dropped (the drain completes on a later boot).
|
|
300
|
-
*/
|
|
280
|
+
/** Rebuild the read cache after a clean drain, or defer while mutations remain owed. */
|
|
301
281
|
async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
|
|
302
282
|
args: {
|
|
303
283
|
db: MutationDb;
|
|
@@ -326,8 +306,6 @@ async function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(
|
|
|
326
306
|
await db.exec(buildWipeLocalStoreSql(registry));
|
|
327
307
|
await db.exec(generateLocalSchemaSql(registry));
|
|
328
308
|
await writeStoredRegistryFingerprint(db, registry, current);
|
|
329
|
-
// This is a full durable-schema exec, so re-stamp the durable-schema fingerprint alongside the registry
|
|
330
|
-
// fingerprint (slice 3): exec and stamp travel together, so the next boot's fast path can trust the skip.
|
|
331
309
|
await writeStoredLocalSchemaFingerprint(db, registry, computeLocalSchemaFingerprint(registry));
|
|
332
310
|
const event: LocalStoreVersionEvent = {
|
|
333
311
|
status: "rebuilt",
|
package/src/local-tables.ts
CHANGED
|
@@ -80,7 +80,7 @@ function buildJournalFixedColumns() {
|
|
|
80
80
|
mutationSeq: integer("mutation_seq").notNull(),
|
|
81
81
|
mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
|
|
82
82
|
status: varchar("status", { length: 24 }).notNull(),
|
|
83
|
-
registryVersion: text("registry_version"),
|
|
83
|
+
registryVersion: text("registry_version").notNull(),
|
|
84
84
|
baseServerVersion: bigintText("base_server_version"),
|
|
85
85
|
writeUnit: text("write_unit"),
|
|
86
86
|
writeMode: varchar("write_mode", { length: 24 }),
|
|
@@ -552,7 +552,7 @@ function buildAllMutationsViewColumns() {
|
|
|
552
552
|
mutationSeq: integer("mutation_seq").notNull(),
|
|
553
553
|
mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
|
|
554
554
|
status: varchar("status", { length: 24 }).notNull(),
|
|
555
|
-
registryVersion: text("registry_version"),
|
|
555
|
+
registryVersion: text("registry_version").notNull(),
|
|
556
556
|
baseServerVersion: bigintText("base_server_version"),
|
|
557
557
|
writeUnit: text("write_unit"),
|
|
558
558
|
writeMode: varchar("write_mode", { length: 24 }),
|
package/src/mutation.ts
CHANGED
|
@@ -166,8 +166,8 @@ export interface MutationDetail {
|
|
|
166
166
|
nextRetryAtUs: string | null;
|
|
167
167
|
serverUpdatedAtUs: string | null;
|
|
168
168
|
updatedAtUs: string;
|
|
169
|
-
/** Registry fingerprint
|
|
170
|
-
registryVersion: string
|
|
169
|
+
/** Registry fingerprint under which the mutation was authored. */
|
|
170
|
+
registryVersion: string;
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
export interface MutationDb {
|
|
@@ -181,20 +181,17 @@ export interface MutationDb {
|
|
|
181
181
|
export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {
|
|
182
182
|
db: MutationDb;
|
|
183
183
|
registry: TRegistry;
|
|
184
|
-
|
|
184
|
+
batchWriteUrl: string;
|
|
185
185
|
getAuthToken?: () => Promise<string | undefined>;
|
|
186
186
|
/** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */
|
|
187
187
|
requestHeaders?: Record<string, string>;
|
|
188
|
-
/**
|
|
189
|
-
* Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its
|
|
190
|
-
* `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).
|
|
191
|
-
*/
|
|
188
|
+
/** Registry fingerprint stamped onto each enqueued mutation; normally derived from {@link registry}. */
|
|
192
189
|
registryVersion?: string;
|
|
193
190
|
/**
|
|
194
191
|
* Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable
|
|
195
192
|
* recovery-required marker lives in). Defaults to `true`. A caller-owned `pgliteInstance` boot sets this
|
|
196
|
-
* `false`: the meta table may not exist, so the marker is never read/written and boot recovery
|
|
197
|
-
*
|
|
193
|
+
* `false`: the meta table may not exist, so the marker is never read/written and boot recovery runs
|
|
194
|
+
* unconditionally.
|
|
198
195
|
*/
|
|
199
196
|
ownsMetaTable?: boolean;
|
|
200
197
|
/**
|
|
@@ -323,7 +320,7 @@ interface TableContext {
|
|
|
323
320
|
* The result of {@link MutationRuntime.runBootRecovery}, shaped to feed the `warmBoot` BootReport fields
|
|
324
321
|
* directly (ADR-0034): whether the per-table recovery loop was skipped, whether recovery was required this
|
|
325
322
|
* boot, how many writable journals were visited, and how many rows were lifted `sending → pending` (`null`
|
|
326
|
-
* when the pass
|
|
323
|
+
* when the selected pass is uncounted, a real count on the marker-`true` path).
|
|
327
324
|
*/
|
|
328
325
|
export interface BootRecoveryOutcome {
|
|
329
326
|
skipped: boolean;
|
|
@@ -333,7 +330,7 @@ export interface BootRecoveryOutcome {
|
|
|
333
330
|
}
|
|
334
331
|
|
|
335
332
|
export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
|
|
336
|
-
/**
|
|
333
|
+
/** Registry fingerprint stamped onto mutations authored by this runtime. */
|
|
337
334
|
registryVersion: string;
|
|
338
335
|
create: <TKey extends SyncTableName<TRegistry>>(
|
|
339
336
|
table: TKey,
|
|
@@ -385,16 +382,16 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
|
|
|
385
382
|
retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
386
383
|
recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
387
384
|
/**
|
|
388
|
-
* Boot-time journal recovery driven by the durable recovery-required marker
|
|
385
|
+
* Boot-time journal recovery driven by the durable recovery-required marker. The
|
|
389
386
|
* internal boot entry point that decides — from the marker and the boot mode — whether the per-table
|
|
390
387
|
* `sending → pending` recovery loop runs at all, and clears/initializes the marker afterwards. It NEVER
|
|
391
388
|
* runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
|
|
392
389
|
* touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
|
|
393
390
|
*
|
|
394
|
-
* - `ownsMetaTable: false` (caller-owned PGlite) →
|
|
395
|
-
* - `restore: true` →
|
|
391
|
+
* - `ownsMetaTable: false` (caller-owned PGlite) → unconditional recovery, marker untouched.
|
|
392
|
+
* - `restore: true` → unconditional recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
|
|
396
393
|
* - marker `false` → skip the loop entirely.
|
|
397
|
-
* - marker absent (
|
|
394
|
+
* - marker absent (not initialized) → one conservative recovery pass, then initialize the marker.
|
|
398
395
|
* - marker `true` → the N per-table updates PLUS the self-verifying clear, wrapped in one transaction.
|
|
399
396
|
*/
|
|
400
397
|
runBootRecovery: (opts: { ownsMetaTable: boolean; restore: boolean }) => Promise<BootRecoveryOutcome>;
|
|
@@ -488,6 +485,7 @@ export function computeNextRetryAtUs(nowUs: string, attemptCount: number, random
|
|
|
488
485
|
export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
489
486
|
options: CreateMutationRuntimeOptions<TRegistry>,
|
|
490
487
|
): MutationRuntime<TRegistry> {
|
|
488
|
+
const mutationUrls = resolveMutationUrls(options.batchWriteUrl);
|
|
491
489
|
const resolveAuthToken = async () => {
|
|
492
490
|
if (options.getAuthToken) {
|
|
493
491
|
return await options.getAuthToken();
|
|
@@ -507,16 +505,14 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
507
505
|
const tableContexts = buildTableContexts(options.registry);
|
|
508
506
|
const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;
|
|
509
507
|
const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;
|
|
510
|
-
// The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime
|
|
511
|
-
// owns the registry, so it derives this itself; an explicit override is honoured for tests.
|
|
512
508
|
const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
|
|
513
509
|
let flushQueue = Promise.resolve();
|
|
514
510
|
|
|
515
511
|
// Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
|
|
516
512
|
// recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
|
|
517
|
-
// touched and the SET/clear seams below are no-ops
|
|
513
|
+
// touched and the SET/clear seams below are no-ops.
|
|
518
514
|
const ownsMetaTable = options.ownsMetaTable ?? true;
|
|
519
|
-
// Cached "this epoch has already committed the marker `true`" flag
|
|
515
|
+
// Cached "this epoch has already committed the marker `true`" flag. Marker-first ordering:
|
|
520
516
|
// `ensureRecoveryMarker` awaits ONE marker upsert before the first `sending` transition of a dirty epoch,
|
|
521
517
|
// then flips this true, so steady-state flushing pays zero extra crossings. Reset to false only after the
|
|
522
518
|
// self-verifying clear proves no `sending` row remains (`settleRecoveryMarker` / boot recovery).
|
|
@@ -547,7 +543,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
547
543
|
};
|
|
548
544
|
|
|
549
545
|
/**
|
|
550
|
-
* Marker-first SET
|
|
546
|
+
* Marker-first SET: commit the marker `true` BEFORE the first
|
|
551
547
|
* pending→sending transition of a dirty epoch. Invoked from the ONE choke point (`applyMutationStatusUpdates`,
|
|
552
548
|
* gated on a `sending` target) immediately before its UPDATE executes. The upsert auto-commits, so the
|
|
553
549
|
* marker is durable before any `sending` row can commit — the invariant the whole slice protects.
|
|
@@ -991,7 +987,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
991
987
|
const batchResult = await flushBatch(
|
|
992
988
|
options.db,
|
|
993
989
|
tableContexts as Record<string, TableContext>,
|
|
994
|
-
|
|
990
|
+
mutationUrls.batch,
|
|
995
991
|
maxMutationAttempts,
|
|
996
992
|
flushBatchSize,
|
|
997
993
|
table,
|
|
@@ -1200,7 +1196,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
1200
1196
|
...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
|
|
1201
1197
|
}));
|
|
1202
1198
|
|
|
1203
|
-
const url =
|
|
1199
|
+
const url = mutationUrls.authoritative;
|
|
1204
1200
|
let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
|
|
1205
1201
|
|
|
1206
1202
|
try {
|
|
@@ -1414,13 +1410,13 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
1414
1410
|
const contexts = filterContexts(tableContexts, undefined);
|
|
1415
1411
|
const tablesVisited = contexts.length;
|
|
1416
1412
|
|
|
1417
|
-
// Caller-owned PGlite: the meta table may not exist, so never touch the marker
|
|
1413
|
+
// Caller-owned PGlite: the meta table may not exist, so never touch the marker and always recover.
|
|
1418
1414
|
if (!bootOwnsMetaTable) {
|
|
1419
1415
|
await runtime.recoverSending();
|
|
1420
1416
|
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
1421
1417
|
}
|
|
1422
1418
|
|
|
1423
|
-
// Restore boot ignores the marker entirely
|
|
1419
|
+
// Restore boot ignores the marker entirely: unconditional recovery lifts any `sending` back to
|
|
1424
1420
|
// `pending`, quarantine parks every recovered non-terminal row, then the self-verifying clear settles
|
|
1425
1421
|
// the marker (a clean marker in the backup must never bypass quarantine — quarantine ran first).
|
|
1426
1422
|
if (restore) {
|
|
@@ -1437,7 +1433,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
1437
1433
|
return { skipped: true, required: false, tablesVisited: 0, rowsRecovered: 0 };
|
|
1438
1434
|
}
|
|
1439
1435
|
|
|
1440
|
-
// Marker absent (
|
|
1436
|
+
// Marker absent (not initialized): one conservative recovery pass, then initialize the marker
|
|
1441
1437
|
// (the pass just guaranteed no `sending` row remains, so an unconditional `false` is correct).
|
|
1442
1438
|
if (marker === null) {
|
|
1443
1439
|
await runtime.recoverSending();
|
|
@@ -1587,7 +1583,7 @@ async function readMutationDetailsForContexts(
|
|
|
1587
1583
|
nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
1588
1584
|
serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
1589
1585
|
updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as("updatedAtUs"),
|
|
1590
|
-
registryVersion: sql<string
|
|
1586
|
+
registryVersion: sql<string>`${journal.registryVersion}`.as("registryVersion"),
|
|
1591
1587
|
})
|
|
1592
1588
|
.from(journal)
|
|
1593
1589
|
.orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))
|
|
@@ -1634,7 +1630,7 @@ interface MutationRow extends Record<string, unknown> {
|
|
|
1634
1630
|
conflictReason: string | null;
|
|
1635
1631
|
nextRetryAtUs: string | null;
|
|
1636
1632
|
serverUpdatedAtUs: string | null;
|
|
1637
|
-
registryVersion: string
|
|
1633
|
+
registryVersion: string;
|
|
1638
1634
|
}
|
|
1639
1635
|
|
|
1640
1636
|
interface MutationDetailRow extends Record<string, unknown> {
|
|
@@ -1650,7 +1646,7 @@ interface MutationDetailRow extends Record<string, unknown> {
|
|
|
1650
1646
|
nextRetryAtUs: string | null;
|
|
1651
1647
|
serverUpdatedAtUs: string | null;
|
|
1652
1648
|
updatedAtUs: string;
|
|
1653
|
-
registryVersion: string
|
|
1649
|
+
registryVersion: string;
|
|
1654
1650
|
}
|
|
1655
1651
|
|
|
1656
1652
|
interface CurrentRecordStateRow extends Record<string, unknown> {
|
|
@@ -1821,10 +1817,10 @@ function buildTableContext<TRegistry extends SyncTableRegistry>(
|
|
|
1821
1817
|
: null;
|
|
1822
1818
|
|
|
1823
1819
|
// Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.
|
|
1824
|
-
// `field.column` is
|
|
1820
|
+
// `field.column` is the canonical drizzle property key (registry validation rejects a column-name
|
|
1821
|
+
// declaration — ADR-0012), so match on the property key alone.
|
|
1825
1822
|
const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>
|
|
1826
|
-
columns.find((candidate) => candidate.propertyKey === fieldColumn
|
|
1827
|
-
?.propertyKey;
|
|
1823
|
+
columns.find((candidate) => candidate.propertyKey === fieldColumn)?.propertyKey;
|
|
1828
1824
|
const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(
|
|
1829
1825
|
(field) => field.strategy === "nowMicroseconds",
|
|
1830
1826
|
);
|
|
@@ -1972,6 +1968,15 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
|
|
|
1972
1968
|
}
|
|
1973
1969
|
}
|
|
1974
1970
|
|
|
1971
|
+
// Conventional audit-timestamp fill — distinct from the governance-driven fill below, not redundant
|
|
1972
|
+
// with it. The `createdAtUs`/`updatedAtUs` columns are conventionally NOT NULL with a SQL-expression
|
|
1973
|
+
// default (`pgxsinkit_clock_us()`, ADR-0004) the client cannot evaluate: `materializeColumnDefault`
|
|
1974
|
+
// leaves an unmaterialisable SQL default undefined, and the overlay INSERT then writes an explicit NULL
|
|
1975
|
+
// (overriding the table DEFAULT), violating the NOT NULL. This stamps them BY NAME regardless of
|
|
1976
|
+
// governance, so a table carrying `created_at_us` WITHOUT declaring it a `nowMicroseconds` managed field
|
|
1977
|
+
// (e.g. the `projects` fixture, whose only managed field is `updated_at_us`) still gets a valid
|
|
1978
|
+
// optimistic timestamp. The governance-driven fill below stamps only DECLARED managed fields, so it
|
|
1979
|
+
// cannot cover an undeclared-but-present conventional column — the two paths are complementary.
|
|
1975
1980
|
if (hasProperty(context, "createdAtUs") && record["createdAtUs"] === undefined) {
|
|
1976
1981
|
record["createdAtUs"] = nowUs;
|
|
1977
1982
|
}
|
|
@@ -1980,9 +1985,10 @@ function createOptimisticRecordFromContext<TCreate, TRecord>(
|
|
|
1980
1985
|
record["updatedAtUs"] = nowUs;
|
|
1981
1986
|
}
|
|
1982
1987
|
|
|
1983
|
-
//
|
|
1984
|
-
//
|
|
1985
|
-
//
|
|
1988
|
+
// Governance-driven managed-timestamp fill: stamp every `nowMicroseconds` managed field the convention
|
|
1989
|
+
// above did not reach — a Server version column not named `updated_at_us` (ADR-0010), or any
|
|
1990
|
+
// custom-named nowMicroseconds field. Idempotent with the convention fill (a conventionally-named
|
|
1991
|
+
// managed field is already stamped, so the `undefined` guard skips the re-stamp).
|
|
1986
1992
|
for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {
|
|
1987
1993
|
if (record[propertyKey] === undefined) {
|
|
1988
1994
|
record[propertyKey] = nowUs;
|
|
@@ -2179,7 +2185,7 @@ async function insertMutationsBulk(
|
|
|
2179
2185
|
db: MutationDb,
|
|
2180
2186
|
context: TableContext,
|
|
2181
2187
|
rows: ReadonlyArray<PlannedMutationInsert>,
|
|
2182
|
-
registryVersion: string
|
|
2188
|
+
registryVersion: string,
|
|
2183
2189
|
unit?: WriteUnit,
|
|
2184
2190
|
) {
|
|
2185
2191
|
if (rows.length === 0) {
|
|
@@ -2343,7 +2349,7 @@ function buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): S
|
|
|
2343
2349
|
interface PendingBatchRow extends MutationRow {
|
|
2344
2350
|
tableKey: string;
|
|
2345
2351
|
enqueuedAtUs: string;
|
|
2346
|
-
/** The resolved Base server version (ADR-0015), or null
|
|
2352
|
+
/** The resolved Base server version (ADR-0015), or null for a create or blind write. */
|
|
2347
2353
|
baseServerVersion: string | null;
|
|
2348
2354
|
}
|
|
2349
2355
|
|
|
@@ -2543,7 +2549,7 @@ async function readUnitPendingRows(
|
|
|
2543
2549
|
async function flushBatch(
|
|
2544
2550
|
db: MutationDb,
|
|
2545
2551
|
tableContexts: Record<string, TableContext>,
|
|
2546
|
-
|
|
2552
|
+
batchMutationUrl: string,
|
|
2547
2553
|
maxAttempts: number,
|
|
2548
2554
|
batchSize: number,
|
|
2549
2555
|
tableFilter?: string,
|
|
@@ -2653,15 +2659,13 @@ async function flushBatch(
|
|
|
2653
2659
|
payload: row.envelopePayload,
|
|
2654
2660
|
clientTimestampUs: sentAtUs,
|
|
2655
2661
|
// ADR-0015: carry the resolved Base server version so the applier can detect a stale write.
|
|
2656
|
-
// Omitted for a create
|
|
2662
|
+
// Omitted for a create or blind write (null) — then no stale check runs.
|
|
2657
2663
|
...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),
|
|
2658
2664
|
};
|
|
2659
2665
|
});
|
|
2660
2666
|
|
|
2661
2667
|
let responseOk = false;
|
|
2662
2668
|
let acksByMutationId: Map<string, BatchMutationAck["acks"][number]> = new Map();
|
|
2663
|
-
const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);
|
|
2664
|
-
|
|
2665
2669
|
try {
|
|
2666
2670
|
// Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls
|
|
2667
2671
|
// `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
|
|
@@ -2929,19 +2933,33 @@ function resolveBatchFailureOutcome(
|
|
|
2929
2933
|
return { status: "failed", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };
|
|
2930
2934
|
}
|
|
2931
2935
|
|
|
2932
|
-
function
|
|
2933
|
-
|
|
2936
|
+
function invalidBatchWriteUrl(): Error {
|
|
2937
|
+
return new Error(
|
|
2938
|
+
'[pgxsinkit] batchWriteUrl must be "/api/mutations" or an absolute deployment URL ending in "/api/mutations"',
|
|
2939
|
+
);
|
|
2940
|
+
}
|
|
2941
|
+
|
|
2942
|
+
function resolveMutationUrls(batchWriteUrl: string): { batch: string; authoritative: string } {
|
|
2943
|
+
if (batchWriteUrl.trim() !== batchWriteUrl || batchWriteUrl.length === 0) {
|
|
2944
|
+
throw invalidBatchWriteUrl();
|
|
2945
|
+
}
|
|
2934
2946
|
|
|
2935
|
-
|
|
2936
|
-
|
|
2947
|
+
const isRelative = batchWriteUrl.startsWith("/") && !batchWriteUrl.startsWith("//");
|
|
2948
|
+
let parsed: URL;
|
|
2949
|
+
try {
|
|
2950
|
+
parsed = isRelative ? new URL(batchWriteUrl, "https://pgxsinkit.invalid") : new URL(batchWriteUrl);
|
|
2951
|
+
} catch {
|
|
2952
|
+
throw invalidBatchWriteUrl();
|
|
2937
2953
|
}
|
|
2938
2954
|
|
|
2939
|
-
|
|
2940
|
-
|
|
2955
|
+
const hasCanonicalPath = isRelative
|
|
2956
|
+
? parsed.pathname === "/api/mutations"
|
|
2957
|
+
: ["http:", "https:"].includes(parsed.protocol) && parsed.pathname.endsWith("/api/mutations");
|
|
2958
|
+
if (!hasCanonicalPath || parsed.search !== "" || parsed.hash !== "") {
|
|
2959
|
+
throw invalidBatchWriteUrl();
|
|
2960
|
+
}
|
|
2941
2961
|
|
|
2942
|
-
|
|
2943
|
-
function resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {
|
|
2944
|
-
return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;
|
|
2962
|
+
return { batch: batchWriteUrl, authoritative: `${batchWriteUrl}/unit` };
|
|
2945
2963
|
}
|
|
2946
2964
|
|
|
2947
2965
|
function stripManagedFields(
|
package/src/mutations-api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The registry-wide reactive mutation-status API (warm-
|
|
1
|
+
// The registry-wide reactive mutation-status API (the current warm-store observability contract,
|
|
2
2
|
// option 1). `client.mutations.*` lets a consumer render a global sync indicator or diagnostics screen with
|
|
3
3
|
// ONE subscription over the `pgxsinkit_all_mutations` view (schema.ts) instead of one live query per writable
|
|
4
4
|
// journal — the O(writable-table) fan-out the proposal set out to remove.
|
|
@@ -115,7 +115,7 @@ interface DetailRow extends Record<string, unknown> {
|
|
|
115
115
|
nextRetryAtUs: string | null;
|
|
116
116
|
serverUpdatedAtUs: string | null;
|
|
117
117
|
updatedAtUs: string;
|
|
118
|
-
registryVersion: string
|
|
118
|
+
registryVersion: string;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
/** The seams the factory needs — shared verbatim by both client modes (zero worker-protocol change). */
|
|
@@ -246,7 +246,7 @@ function buildDetailSql<TRegistry extends SyncTableRegistry>(
|
|
|
246
246
|
nextRetryAtUs: sql<string | null>`${view.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
247
247
|
serverUpdatedAtUs: sql<string | null>`${view.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
248
248
|
updatedAtUs: sql<string>`${view.updatedAtUs}::text`.as("updatedAtUs"),
|
|
249
|
-
registryVersion: sql<string
|
|
249
|
+
registryVersion: sql<string>`${view.registryVersion}`.as("registryVersion"),
|
|
250
250
|
})
|
|
251
251
|
.from(view)
|
|
252
252
|
.where(conditions.length > 0 ? and(...conditions) : undefined)
|