@pgxsinkit/client 0.1.49 → 0.1.51
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/boot-report.d.ts +76 -0
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/index.d.ts +56 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1106 -312
- package/dist/index.js.map +19 -18
- package/dist/local-store.d.ts +58 -0
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +340 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +36 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts +82 -0
- package/dist/mutations-api.d.ts.map +1 -0
- package/dist/schema.d.ts +80 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +6 -0
- package/dist/shape-sync.d.ts.map +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/metadata-tables.d.ts +16 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +10 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/tags.d.ts +16 -4
- package/dist/sync/tags.d.ts.map +1 -1
- package/dist/sync/types.d.ts +12 -0
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +44 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +1 -1
- package/skills/operating/SKILL.md +1 -1
- package/src/boot-report.ts +108 -0
- package/src/index.ts +555 -136
- package/src/local-store.ts +150 -3
- package/src/local-tables.ts +49 -1
- package/src/mutation.ts +256 -15
- package/src/mutations-api.ts +310 -0
- package/src/schema.ts +428 -197
- package/src/shape-sync.ts +11 -0
- package/src/sync/index.ts +14 -1
- package/src/sync/metadata-tables.ts +41 -0
- package/src/sync/subscription-state.ts +29 -4
- package/src/sync/tags.ts +34 -9
- package/src/sync/types.ts +12 -0
- package/src/worker/attach-sync-client.ts +114 -5
- package/src/worker/define-sync-worker.ts +65 -4
- package/src/worker/protocol.ts +38 -1
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
// The registry-wide reactive mutation-status API (warm-persisted-store-startup slice 4 / proposal §5,
|
|
2
|
+
// option 1). `client.mutations.*` lets a consumer render a global sync indicator or diagnostics screen with
|
|
3
|
+
// ONE subscription over the `pgxsinkit_all_mutations` view (schema.ts) instead of one live query per writable
|
|
4
|
+
// journal — the O(writable-table) fan-out the proposal set out to remove.
|
|
5
|
+
//
|
|
6
|
+
// It is a FACTORY over the two seams BOTH client modes already share — `subscribeLiveRows` (in-process over
|
|
7
|
+
// `pglite.live`; worker-attached over the bridge) and a one-shot `query` (in-process `pglite.query`;
|
|
8
|
+
// worker-attached the `rawQuery` RPC) — so the worker bridge needs ZERO protocol change. Every runtime query
|
|
9
|
+
// is Drizzle-built over `getAllMutationsView` (tier ①); consumers never touch generated journal relation
|
|
10
|
+
// names.
|
|
11
|
+
|
|
12
|
+
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
|
13
|
+
import { drizzle } from "drizzle-orm/pglite";
|
|
14
|
+
|
|
15
|
+
import type { MutationSummary, SyncTableName, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
16
|
+
|
|
17
|
+
import { getAllMutationsView } from "./local-tables";
|
|
18
|
+
import type { MutationDetail, MutationKind } from "./mutation";
|
|
19
|
+
import type { MutationStatus } from "./mutation-state";
|
|
20
|
+
|
|
21
|
+
// Re-export the detail shape under the summary-API name. The list/subscribe detail rows ARE
|
|
22
|
+
// {@link MutationDetail} (it already carries `tableName` + the parsed `entityKey`), reused verbatim.
|
|
23
|
+
export type { MutationDetail } from "./mutation";
|
|
24
|
+
export type MutationSummaryDetail = MutationDetail;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Build-only Drizzle (compiles to SQL via `.toSQL()`; never executes) — same mock seam mutation.ts uses.
|
|
28
|
+
* Lazily constructed: some unit suites mock `drizzle-orm/pglite`, so `drizzle.mock` is unavailable at module
|
|
29
|
+
* load; a lazy builder is only reached when a real query is actually authored (never in those mocked boots).
|
|
30
|
+
*/
|
|
31
|
+
let queryBuilderInstance: ReturnType<typeof drizzle.mock> | undefined;
|
|
32
|
+
function queryBuilder(): ReturnType<typeof drizzle.mock> {
|
|
33
|
+
return (queryBuilderInstance ??= drizzle.mock());
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Optional filters for {@link MutationsApi.list} / {@link MutationsApi.subscribe}. */
|
|
37
|
+
export interface MutationListOptions<TRegistry extends SyncTableRegistry> {
|
|
38
|
+
/** Restrict to one registry table key (the `table_key` column). */
|
|
39
|
+
table?: SyncTableName<TRegistry>;
|
|
40
|
+
/**
|
|
41
|
+
* Restrict to one entity — matched on the serialized `entity_key_json` (`JSON.stringify(entityKey)`),
|
|
42
|
+
* byte-for-byte against the enqueue-time serialization. For a COMPOSITE key, pass the properties in the
|
|
43
|
+
* same order pgxsinkit serialized them (a key taken from a returned {@link MutationSummaryDetail} or the
|
|
44
|
+
* write API round-trips correctly; a hand-built object with a different property order silently matches
|
|
45
|
+
* nothing).
|
|
46
|
+
*/
|
|
47
|
+
entityKey?: Record<string, string>;
|
|
48
|
+
/** Restrict to a set of journal statuses. */
|
|
49
|
+
statuses?: readonly MutationStatus[];
|
|
50
|
+
/** Cap the returned rows (applied after the `enqueued_at_us` ordering). */
|
|
51
|
+
limit?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A handle to a live summary subscription: the initial summary plus an idempotent unsubscribe. */
|
|
55
|
+
export interface MutationSummarySubscription {
|
|
56
|
+
initial: MutationSummary;
|
|
57
|
+
unsubscribe: () => void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A handle to a live detail subscription: the initial ordered rows plus an idempotent unsubscribe. */
|
|
61
|
+
export interface MutationListSubscription {
|
|
62
|
+
initial: MutationSummaryDetail[];
|
|
63
|
+
unsubscribe: () => void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The registry-wide reactive mutation-status surface (`client.mutations`), identical on the in-process and
|
|
68
|
+
* worker-attached client. Consumers NEVER touch the generated journal relation names — everything routes
|
|
69
|
+
* through the `pgxsinkit_all_mutations` view.
|
|
70
|
+
*
|
|
71
|
+
* The `summary` is cheap enough to mount PERMANENTLY (one fingerprinted registration regardless of subscriber
|
|
72
|
+
* count — ADR-0040 dedup gives one shared rerun per journal write, not N). Full `list`/`subscribe` detail
|
|
73
|
+
* subscriptions should stay route- or feature-scoped.
|
|
74
|
+
*/
|
|
75
|
+
export interface MutationsApi<TRegistry extends SyncTableRegistry> {
|
|
76
|
+
/** One-shot per-status counts across every writable journal (absent statuses = 0). */
|
|
77
|
+
summary(): Promise<MutationSummary>;
|
|
78
|
+
/**
|
|
79
|
+
* Live per-status counts: `listener` fires on every change, the initial summary is on the returned handle
|
|
80
|
+
* (matching `subscribeLiveRows`' initial-via-return / changes-via-callback split). One registration
|
|
81
|
+
* regardless of subscriber count. Cheap to mount permanently.
|
|
82
|
+
*/
|
|
83
|
+
subscribeSummary(listener: (summary: MutationSummary) => void): Promise<MutationSummarySubscription>;
|
|
84
|
+
/** One-shot normalized detail rows, filtered by {@link MutationListOptions}, ordered newest-first by `enqueued_at_us`. */
|
|
85
|
+
list(options?: MutationListOptions<TRegistry>): Promise<MutationSummaryDetail[]>;
|
|
86
|
+
/**
|
|
87
|
+
* Live normalized detail rows (same filters/ordering as {@link list}). Route/feature-scoped: a detail
|
|
88
|
+
* subscription reruns the union SELECT on each relevant write — cheap for a scoped view, but prefer the
|
|
89
|
+
* summary for anything mounted app-wide.
|
|
90
|
+
*/
|
|
91
|
+
subscribe(
|
|
92
|
+
options: MutationListOptions<TRegistry>,
|
|
93
|
+
listener: (rows: MutationSummaryDetail[]) => void,
|
|
94
|
+
): Promise<MutationListSubscription>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The row shape the raw seams return for the summary aggregate (unmapped, keyed by output column name). */
|
|
98
|
+
interface SummaryRow extends Record<string, unknown> {
|
|
99
|
+
status: string;
|
|
100
|
+
count: number | string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The row shape the raw seams return for a detail query (unmapped, keyed by the select's aliases). */
|
|
104
|
+
interface DetailRow extends Record<string, unknown> {
|
|
105
|
+
tableName: string;
|
|
106
|
+
entityKeyJson: string;
|
|
107
|
+
mutationId: string;
|
|
108
|
+
mutationSeq: number | string;
|
|
109
|
+
mutationKind: MutationKind;
|
|
110
|
+
status: MutationStatus;
|
|
111
|
+
attemptCount: number | string;
|
|
112
|
+
lastHttpStatus: number | null;
|
|
113
|
+
lastError: string | null;
|
|
114
|
+
conflictReason: string | null;
|
|
115
|
+
nextRetryAtUs: string | null;
|
|
116
|
+
serverUpdatedAtUs: string | null;
|
|
117
|
+
updatedAtUs: string;
|
|
118
|
+
registryVersion: string | null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The seams the factory needs — shared verbatim by both client modes (zero worker-protocol change). */
|
|
122
|
+
export interface MutationsApiDeps<TRegistry extends SyncTableRegistry> {
|
|
123
|
+
registry: TRegistry;
|
|
124
|
+
subscribeLiveRows: <TRow extends Record<string, unknown>>(
|
|
125
|
+
input: { sql: string; params: readonly unknown[] },
|
|
126
|
+
onRows: (rows: TRow[]) => void,
|
|
127
|
+
) => Promise<{ initialRows: TRow[]; unsubscribe: () => void }>;
|
|
128
|
+
/** One-shot query seam (in-process `pglite.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */
|
|
129
|
+
query: (sql: string, params?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const STATUS_TO_SUMMARY_KEY: Record<MutationStatus, keyof MutationSummary> = {
|
|
133
|
+
pending: "pendingCount",
|
|
134
|
+
sending: "sendingCount",
|
|
135
|
+
acked: "ackedCount",
|
|
136
|
+
failed: "failedCount",
|
|
137
|
+
quarantined: "quarantinedCount",
|
|
138
|
+
conflicted: "conflictedCount",
|
|
139
|
+
rejected: "rejectedCount",
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
function emptySummary(): MutationSummary {
|
|
143
|
+
return {
|
|
144
|
+
pendingCount: 0,
|
|
145
|
+
sendingCount: 0,
|
|
146
|
+
ackedCount: 0,
|
|
147
|
+
failedCount: 0,
|
|
148
|
+
rejectedCount: 0,
|
|
149
|
+
conflictedCount: 0,
|
|
150
|
+
quarantinedCount: 0,
|
|
151
|
+
unsettledCount: 0,
|
|
152
|
+
settledCount: 0,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Fold `{status, count}` aggregate rows into the summary shape (absent statuses = 0; derive the totals). */
|
|
157
|
+
function foldSummary(rows: readonly SummaryRow[]): MutationSummary {
|
|
158
|
+
const summary = emptySummary();
|
|
159
|
+
for (const row of rows) {
|
|
160
|
+
const key = STATUS_TO_SUMMARY_KEY[row.status as MutationStatus];
|
|
161
|
+
if (key) {
|
|
162
|
+
summary[key] = Number(row.count);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// See MutationSummary's JSDoc (FIX 3): `conflicted` AND `quarantined` are journal-terminal but user-UNSETTLED
|
|
166
|
+
// (overlay kept, entity blocked, `destroy()` refuses them, reconciliation counts them owed), so both join
|
|
167
|
+
// pending/sending/failed. `settledCount` is the truly-done complement — `acked` + `rejected` only.
|
|
168
|
+
summary.unsettledCount =
|
|
169
|
+
summary.pendingCount +
|
|
170
|
+
summary.sendingCount +
|
|
171
|
+
summary.failedCount +
|
|
172
|
+
summary.conflictedCount +
|
|
173
|
+
summary.quarantinedCount;
|
|
174
|
+
summary.settledCount = summary.ackedCount + summary.rejectedCount;
|
|
175
|
+
return summary;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function mapDetailRow(row: DetailRow): MutationSummaryDetail {
|
|
179
|
+
return {
|
|
180
|
+
tableName: row.tableName,
|
|
181
|
+
entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,
|
|
182
|
+
mutationId: row.mutationId,
|
|
183
|
+
mutationSeq: Number(row.mutationSeq),
|
|
184
|
+
mutationKind: row.mutationKind,
|
|
185
|
+
status: row.status,
|
|
186
|
+
attemptCount: Number(row.attemptCount),
|
|
187
|
+
lastHttpStatus: row.lastHttpStatus,
|
|
188
|
+
lastError: row.lastError,
|
|
189
|
+
conflictReason: row.conflictReason,
|
|
190
|
+
nextRetryAtUs: row.nextRetryAtUs,
|
|
191
|
+
serverUpdatedAtUs: row.serverUpdatedAtUs,
|
|
192
|
+
updatedAtUs: row.updatedAtUs,
|
|
193
|
+
registryVersion: row.registryVersion,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Does the registry declare ≥1 writable table (a journal to union → the view is emitted)? */
|
|
198
|
+
function hasWritableTable(registry: SyncTableRegistry): boolean {
|
|
199
|
+
return Object.values(registry).some((entry) => entry.mode !== "readonly" && entry.clientProjection?.journalTable);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The `SELECT status, count(*) … GROUP BY status` aggregate over the view (tier ①). */
|
|
203
|
+
function buildSummarySql(registry: SyncTableRegistry): { sql: string; params: unknown[] } {
|
|
204
|
+
const view = getAllMutationsView(registry);
|
|
205
|
+
return queryBuilder()
|
|
206
|
+
.select({ status: view.status, count: sql<number>`count(*)::int`.as("count") })
|
|
207
|
+
.from(view)
|
|
208
|
+
.groupBy(view.status)
|
|
209
|
+
.toSQL();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The filtered detail SELECT over the view (tier ①). Every column is aliased to its camelCase key (the raw
|
|
214
|
+
* seams return rows UNMAPPED), mirroring `readMutationDetailsForContexts`, plus the `table_key`. Ordered
|
|
215
|
+
* newest-first by `enqueued_at_us` — the per-journal `mutation_seq` is NOT globally ordered, so it is never
|
|
216
|
+
* used across tables.
|
|
217
|
+
*/
|
|
218
|
+
function buildDetailSql<TRegistry extends SyncTableRegistry>(
|
|
219
|
+
registry: TRegistry,
|
|
220
|
+
options: MutationListOptions<TRegistry> | undefined,
|
|
221
|
+
): { sql: string; params: unknown[] } {
|
|
222
|
+
const view = getAllMutationsView(registry);
|
|
223
|
+
const conditions = [];
|
|
224
|
+
if (options?.table != null) {
|
|
225
|
+
conditions.push(eq(view.tableKey, options.table));
|
|
226
|
+
}
|
|
227
|
+
if (options?.entityKey != null) {
|
|
228
|
+
conditions.push(eq(view.entityKeyJson, JSON.stringify(options.entityKey)));
|
|
229
|
+
}
|
|
230
|
+
if (options?.statuses != null && options.statuses.length > 0) {
|
|
231
|
+
conditions.push(inArray(view.status, options.statuses as string[]));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const base = queryBuilder()
|
|
235
|
+
.select({
|
|
236
|
+
tableName: sql<string>`${view.tableKey}`.as("tableName"),
|
|
237
|
+
entityKeyJson: sql<string>`${view.entityKeyJson}`.as("entityKeyJson"),
|
|
238
|
+
mutationId: sql<string>`${view.mutationId}`.as("mutationId"),
|
|
239
|
+
mutationSeq: sql<number>`${view.mutationSeq}`.as("mutationSeq"),
|
|
240
|
+
mutationKind: sql<MutationKind>`${view.mutationKind}`.as("mutationKind"),
|
|
241
|
+
status: sql<MutationStatus>`${view.status}`.as("status"),
|
|
242
|
+
attemptCount: sql<number>`${view.attemptCount}`.as("attemptCount"),
|
|
243
|
+
lastHttpStatus: sql<number | null>`${view.lastHttpStatus}`.as("lastHttpStatus"),
|
|
244
|
+
lastError: sql<string | null>`${view.lastError}`.as("lastError"),
|
|
245
|
+
conflictReason: sql<string | null>`${view.conflictReason}`.as("conflictReason"),
|
|
246
|
+
nextRetryAtUs: sql<string | null>`${view.nextRetryAtUs}::text`.as("nextRetryAtUs"),
|
|
247
|
+
serverUpdatedAtUs: sql<string | null>`${view.serverUpdatedAtUs}::text`.as("serverUpdatedAtUs"),
|
|
248
|
+
updatedAtUs: sql<string>`${view.updatedAtUs}::text`.as("updatedAtUs"),
|
|
249
|
+
registryVersion: sql<string | null>`${view.registryVersion}`.as("registryVersion"),
|
|
250
|
+
})
|
|
251
|
+
.from(view)
|
|
252
|
+
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
|
253
|
+
// `mutation_id` tiebreak: mutations enqueued in the same microsecond (e.g. a multi-table batch) must not
|
|
254
|
+
// shuffle relative order between live-query reruns.
|
|
255
|
+
.orderBy(desc(view.enqueuedAtUs), desc(view.mutationId));
|
|
256
|
+
|
|
257
|
+
return (options?.limit != null ? base.limit(options.limit) : base).toSQL();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Build the `client.mutations` API over the shared seams. Implemented ONCE — both client modes pass their own
|
|
262
|
+
* `subscribeLiveRows` + one-shot `query`, so semantics are identical and the worker bridge is untouched. A
|
|
263
|
+
* registry with NO writable table emits no view, so the API short-circuits to empty shapes WITHOUT touching
|
|
264
|
+
* the (absent) view — derived from the registry, never a runtime probe.
|
|
265
|
+
*/
|
|
266
|
+
export function createMutationsApi<TRegistry extends SyncTableRegistry>(
|
|
267
|
+
deps: MutationsApiDeps<TRegistry>,
|
|
268
|
+
): MutationsApi<TRegistry> {
|
|
269
|
+
const { registry, subscribeLiveRows, query } = deps;
|
|
270
|
+
const writable = hasWritableTable(registry);
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
summary: async () => {
|
|
274
|
+
if (!writable) {
|
|
275
|
+
return emptySummary();
|
|
276
|
+
}
|
|
277
|
+
const built = buildSummarySql(registry);
|
|
278
|
+
const { rows } = await query(built.sql, built.params);
|
|
279
|
+
return foldSummary(rows as SummaryRow[]);
|
|
280
|
+
},
|
|
281
|
+
subscribeSummary: async (listener) => {
|
|
282
|
+
if (!writable) {
|
|
283
|
+
return { initial: emptySummary(), unsubscribe: () => {} };
|
|
284
|
+
}
|
|
285
|
+
const built = buildSummarySql(registry);
|
|
286
|
+
const subscription = await subscribeLiveRows<SummaryRow>({ sql: built.sql, params: built.params }, (rows) =>
|
|
287
|
+
listener(foldSummary(rows)),
|
|
288
|
+
);
|
|
289
|
+
return { initial: foldSummary(subscription.initialRows), unsubscribe: subscription.unsubscribe };
|
|
290
|
+
},
|
|
291
|
+
list: async (options) => {
|
|
292
|
+
if (!writable) {
|
|
293
|
+
return [];
|
|
294
|
+
}
|
|
295
|
+
const built = buildDetailSql(registry, options);
|
|
296
|
+
const { rows } = await query(built.sql, built.params);
|
|
297
|
+
return (rows as DetailRow[]).map(mapDetailRow);
|
|
298
|
+
},
|
|
299
|
+
subscribe: async (options, listener) => {
|
|
300
|
+
if (!writable) {
|
|
301
|
+
return { initial: [], unsubscribe: () => {} };
|
|
302
|
+
}
|
|
303
|
+
const built = buildDetailSql(registry, options);
|
|
304
|
+
const subscription = await subscribeLiveRows<DetailRow>({ sql: built.sql, params: built.params }, (rows) =>
|
|
305
|
+
listener(rows.map(mapDetailRow)),
|
|
306
|
+
);
|
|
307
|
+
return { initial: subscription.initialRows.map(mapDetailRow), unsubscribe: subscription.unsubscribe };
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|