@pgxsinkit/client 0.1.32 → 0.1.36
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 +11 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +118 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +260 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +15 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1076 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
import type { ColumnBuilderBase } from "drizzle-orm";
|
|
2
|
+
import { getColumns } from "drizzle-orm";
|
|
3
|
+
import {
|
|
4
|
+
bigint,
|
|
5
|
+
boolean,
|
|
6
|
+
customType,
|
|
7
|
+
getTableConfig,
|
|
8
|
+
integer,
|
|
9
|
+
pgSchema,
|
|
10
|
+
pgTable,
|
|
11
|
+
pgView,
|
|
12
|
+
text,
|
|
13
|
+
uuid,
|
|
14
|
+
varchar,
|
|
15
|
+
type AnyPgTable,
|
|
16
|
+
type PgColumn,
|
|
17
|
+
type PgTableWithColumns,
|
|
18
|
+
type PgViewWithSelection,
|
|
19
|
+
} from "drizzle-orm/pg-core";
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
deriveSyncColumnTypes,
|
|
23
|
+
getLocalSyncedTablePrimaryKeyColumns,
|
|
24
|
+
getSyncRegistrySchema,
|
|
25
|
+
type SyncColumnType,
|
|
26
|
+
type SyncTableEntry,
|
|
27
|
+
type SyncTableRegistry,
|
|
28
|
+
} from "@pgxsinkit/contracts";
|
|
29
|
+
|
|
30
|
+
import { LOCAL_META_TABLE } from "./schema";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table
|
|
34
|
+
* overlay (`<t>_overlay`), journal (`<t>_mutations`), sync-state view (`<t>_sync_state`), the projected
|
|
35
|
+
* synced read cache, and the `pgxsinkit_local_meta` key/value table. The schema generator
|
|
36
|
+
* (`schema.ts`) remains the one authority for the DDL — these objects exist so the mutation runtime,
|
|
37
|
+
* consumers, and tests can AUTHOR queries against those relations as tier-① Drizzle objects
|
|
38
|
+
* (rename-safe, type-checked) instead of hand-written SQL strings.
|
|
39
|
+
*
|
|
40
|
+
* They are query-authoring objects only — never feed them to drizzle-kit generation; the generated
|
|
41
|
+
* DDL in `schema.ts` is the source of truth for the physical shape, and `local-tables.test`-level
|
|
42
|
+
* coverage (the existing overlay/journal suites run against generator-provisioned stores) is what
|
|
43
|
+
* keeps the two aligned.
|
|
44
|
+
*
|
|
45
|
+
* Every object is schema-QUALIFIED with the registry's own local schema (via `getSyncRegistrySchema`).
|
|
46
|
+
* `entry.table` / `entry.localTable` are already qualified the same way (`defineSyncTable` builds them
|
|
47
|
+
* with the caller's schema, and `attachSyncRegistrySchema` throws unless they match the registry schema),
|
|
48
|
+
* so for the synced read cache the factory just tracks a `clientProjection.syncedTable` rename. The
|
|
49
|
+
* factories earn their keep where no equally-qualified entry handle exists: `entry.view` is built
|
|
50
|
+
* schema-UNqualified (a bare `pgView`), so a store in a non-public schema must author the read model
|
|
51
|
+
* through `getReadModelView`; and the overlay / journal / sync-state relations have NO entry handle at all
|
|
52
|
+
* — these factories are the only Drizzle objects for them. Each factory MEMOIZES its result per
|
|
53
|
+
* `(registry, tableKey)` (the `pgxsinkit_local_meta` table per local schema), so repeated calls hand back
|
|
54
|
+
* the same object identity.
|
|
55
|
+
*
|
|
56
|
+
* Typing tracks the registry the caller holds: with a concretely-typed registry (built by
|
|
57
|
+
* `defineSyncRegistry`) the synced/overlay/read-model objects carry the entry's real per-column types, so
|
|
58
|
+
* `.select({ x: overlay.col })`, `$inferInsert`, and `.values()` all typecheck by property key; with a
|
|
59
|
+
* bare `SyncTableRegistry` they degrade to an open index-signature shape reached by bracket access.
|
|
60
|
+
* `JournalTable` / `SyncStateView` are ALWAYS conservatively indexed for their entity/PK columns (the PK
|
|
61
|
+
* name set is not recoverable at the type level — see those types).
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Microsecond/bigint columns the mutation runtime handles as **strings** (the JSON-safe form it has
|
|
66
|
+
* always used): passthrough both ways, `bigint` in DDL position. Reads through the raw `MutationDb`
|
|
67
|
+
* seam bypass drizzle result mapping anyway; this keeps `.values()`/`.set()` accepting the runtime's
|
|
68
|
+
* string values without a lossy JS-number hop.
|
|
69
|
+
*/
|
|
70
|
+
const bigintText = customType<{ data: string; driverData: string }>({
|
|
71
|
+
dataType() {
|
|
72
|
+
return "bigint";
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
function buildJournalFixedColumns() {
|
|
77
|
+
return {
|
|
78
|
+
mutationId: uuid("mutation_id").primaryKey(),
|
|
79
|
+
entityKeyJson: text("entity_key_json").notNull(),
|
|
80
|
+
mutationSeq: integer("mutation_seq").notNull(),
|
|
81
|
+
mutationKind: varchar("mutation_kind", { length: 24 }).notNull(),
|
|
82
|
+
status: varchar("status", { length: 24 }).notNull(),
|
|
83
|
+
registryVersion: text("registry_version"),
|
|
84
|
+
baseServerVersion: bigintText("base_server_version"),
|
|
85
|
+
writeUnit: text("write_unit"),
|
|
86
|
+
writeMode: varchar("write_mode", { length: 24 }),
|
|
87
|
+
payloadJson: text("payload_json").notNull(),
|
|
88
|
+
attemptCount: integer("attempt_count").notNull().default(0),
|
|
89
|
+
lastError: text("last_error"),
|
|
90
|
+
lastHttpStatus: integer("last_http_status"),
|
|
91
|
+
conflictReason: text("conflict_reason"),
|
|
92
|
+
serverUpdatedAtUs: bigintText("server_updated_at_us"),
|
|
93
|
+
enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
|
|
94
|
+
nextRetryAtUs: bigintText("next_retry_at_us"),
|
|
95
|
+
sentAtUs: bigintText("sent_at_us"),
|
|
96
|
+
ackedAtUs: bigintText("acked_at_us"),
|
|
97
|
+
updatedAtUs: bigintText("updated_at_us").notNull(),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function buildOverlayFixedColumns() {
|
|
102
|
+
return {
|
|
103
|
+
overlayKind: varchar("overlay_kind", { length: 24 }).notNull(),
|
|
104
|
+
localUpdatedAtUs: bigintText("local_updated_at_us").notNull(),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.
|
|
110
|
+
* Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so
|
|
111
|
+
* `local_updated_at_us` is a `mode: "bigint"` int8 (PGlite returns it as a string at runtime) rather than
|
|
112
|
+
* the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same
|
|
113
|
+
* way the generator names them (`view["overlay_kind"]`).
|
|
114
|
+
*/
|
|
115
|
+
function buildReadModelFixedColumns() {
|
|
116
|
+
return {
|
|
117
|
+
overlay_kind: varchar("overlay_kind", { length: 24 }).notNull(),
|
|
118
|
+
local_updated_at_us: bigint("local_updated_at_us", { mode: "bigint" }).notNull(),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function buildSyncStateFixedColumns() {
|
|
123
|
+
return {
|
|
124
|
+
observedServerVersion: bigint("observed_server_version", { mode: "bigint" }),
|
|
125
|
+
ackedServerVersion: bigint("acked_server_version", { mode: "bigint" }),
|
|
126
|
+
pendingCount: bigint("pending_count", { mode: "number" }).notNull(),
|
|
127
|
+
hasAckedUnobservedWrite: boolean("has_acked_unobserved_write").notNull(),
|
|
128
|
+
localDeletePending: boolean("local_delete_pending").notNull(),
|
|
129
|
+
conflictState: text("conflict_state"),
|
|
130
|
+
quarantinedCount: bigint("quarantined_count", { mode: "number" }).notNull(),
|
|
131
|
+
quarantineState: text("quarantine_state"),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Phantom shape tables: never created, never queried — they exist only so the derived relation types
|
|
136
|
+
// carry strong typing on the FIXED column keys. The per-entry ENTITY columns are layered on top from
|
|
137
|
+
// the concrete registry entry (see the `*<TEntry>` types below), so a caller whose registry is
|
|
138
|
+
// concretely typed reaches real, projected `PgColumn`s by property key; only a caller holding a bare
|
|
139
|
+
// `SyncTableRegistry` falls back to the open index-signature form these shapes' generic default gives.
|
|
140
|
+
const journalShape = pgTable("_pgxsinkit_journal_shape", buildJournalFixedColumns());
|
|
141
|
+
const overlayShape = pgTable("_pgxsinkit_overlay_shape", buildOverlayFixedColumns());
|
|
142
|
+
const syncStateShape = pgView("_pgxsinkit_sync_state_shape", buildSyncStateFixedColumns()).existing();
|
|
143
|
+
const readModelShape = pgView("_pgxsinkit_read_model_shape", buildReadModelFixedColumns()).existing();
|
|
144
|
+
const localMetaShape = pgTable(LOCAL_META_TABLE, {
|
|
145
|
+
key: text("key").primaryKey(),
|
|
146
|
+
value: text("value").notNull(),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,
|
|
151
|
+
* exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete
|
|
152
|
+
* entry (a registry built by `defineSyncRegistry`) this carries the real, typed columns; when it is a
|
|
153
|
+
* bare `SyncTableEntry` (a generic `SyncTableRegistry`) it degrades to `AnyPgTable`, which pushes every
|
|
154
|
+
* derived type below onto the open `Record<string, PgColumn>` index-signature fallback.
|
|
155
|
+
*/
|
|
156
|
+
type EntryLocalTable<TEntry> =
|
|
157
|
+
TEntry extends SyncTableEntry<AnyPgTable, infer TLocal extends AnyPgTable> ? TLocal : AnyPgTable;
|
|
158
|
+
|
|
159
|
+
/** The entry's projected columns keyed by drizzle property key (or the open `PgColumns` fallback). */
|
|
160
|
+
type EntryColumns<TEntry> = EntryLocalTable<TEntry>["_"]["columns"];
|
|
161
|
+
type OverlayFixedColumns = (typeof overlayShape)["_"]["columns"];
|
|
162
|
+
type ReadModelFixedColumns = (typeof readModelShape)["_"]["selectedFields"];
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The `<t>_overlay` optimistic-intent table: the entry's PROJECTED columns (same builders the generator
|
|
166
|
+
* and `entry.localTable` carry) merged with the two fixed overlay columns. The entity columns read
|
|
167
|
+
* back through real drizzle result mapping, so their types mirror the projected table exactly (a
|
|
168
|
+
* `mode: "bigint"` column is `bigint`, etc.). The two overlay columns are `bigintText` passthrough
|
|
169
|
+
* (`local_updated_at_us` reads as a string). `TEntry` defaults to a bare entry, giving the open
|
|
170
|
+
* index-signature form the mutation runtime (generic over any registry) needs.
|
|
171
|
+
*/
|
|
172
|
+
export type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{
|
|
173
|
+
name: string;
|
|
174
|
+
schema: string | undefined;
|
|
175
|
+
columns: EntryColumns<TEntry> & OverlayFixedColumns;
|
|
176
|
+
dialect: "pg";
|
|
177
|
+
}>;
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The `<t>_read_model` overlay-merged read view (ADR-0004): the entry's PROJECTED columns under their
|
|
181
|
+
* property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read
|
|
182
|
+
* through a live query, so `local_updated_at_us` is an int8 `mode: "bigint"` column.
|
|
183
|
+
*/
|
|
184
|
+
export type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<
|
|
185
|
+
string,
|
|
186
|
+
true,
|
|
187
|
+
EntryColumns<TEntry> & ReadModelFixedColumns
|
|
188
|
+
>;
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).
|
|
192
|
+
* Type-level note: the phantom relation name here is the original `tableName` (inherited from
|
|
193
|
+
* `ProjectedLocalTable`), but the runtime object `getSyncedLocalTable` returns honours a
|
|
194
|
+
* `clientProjection.syncedTable` rename — so the rendered SQL uses the runtime name, not this type's name.
|
|
195
|
+
*/
|
|
196
|
+
export type SyncedLocalTable<TEntry = SyncTableEntry> = EntryLocalTable<TEntry>;
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The `<t>_mutations` journal: fixed runtime columns + the entry's PK columns (index-signature access).
|
|
200
|
+
* Kept conservatively indexed: the journal carries ONLY the PK columns, keyed by DB COLUMN NAME and
|
|
201
|
+
* type-erased to `text`, but neither the PK column-name set nor the "PK only" subset is recoverable at
|
|
202
|
+
* the type level from `SyncTableEntry` (its `primaryKey.columns` is an un-narrowed `string[]`), so an
|
|
203
|
+
* honest per-entry type is not representable without a footgun (claiming non-PK columns that do not
|
|
204
|
+
* exist on the journal at runtime). PK/entity columns therefore ride the index signature.
|
|
205
|
+
*/
|
|
206
|
+
export type JournalTable = typeof journalShape & { [columnName: string]: PgColumn };
|
|
207
|
+
/**
|
|
208
|
+
* The `<t>_sync_state` convergence view (ADR-0011): fixed state columns + the entry's PK columns.
|
|
209
|
+
* Conservatively indexed for the same reason as {@link JournalTable} — it projects only the PK columns
|
|
210
|
+
* (a subset not recoverable at the type level), so the PK columns ride the index signature.
|
|
211
|
+
*/
|
|
212
|
+
export type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };
|
|
213
|
+
/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */
|
|
214
|
+
export type LocalMetaTable = typeof localMetaShape;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)
|
|
218
|
+
* renders **bare** regardless of the registry's local schema: its whole cluster is emitted as `TEMP`
|
|
219
|
+
* with unqualified object names that resolve via `pg_temp`/search_path, exactly as
|
|
220
|
+
* `generateLocalSchemaSql` renders it (a `pgSchema(localSchema).table(...)` reference would target a
|
|
221
|
+
* durable schema the temp table does not live in — the latent qualification bug ADR-0029 records).
|
|
222
|
+
*/
|
|
223
|
+
function makeTable(
|
|
224
|
+
localSchema: string,
|
|
225
|
+
name: string,
|
|
226
|
+
columns: Record<string, ColumnBuilderBase>,
|
|
227
|
+
ephemeral = false,
|
|
228
|
+
): AnyPgTable {
|
|
229
|
+
return localSchema === "public" || ephemeral ? pgTable(name, columns) : pgSchema(localSchema).table(name, columns);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function isEphemeral(entry: SyncTableEntry<AnyPgTable>): boolean {
|
|
233
|
+
return entry.retention === "ephemeral";
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function resolveSyncedTableName(entry: SyncTableEntry<AnyPgTable>): string {
|
|
237
|
+
return entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The entry's projected column BUILDERS keyed by property key, re-created from the retained
|
|
242
|
+
* `makeColumns` factory (registry.ts keeps it for exactly this kind of reuse) with
|
|
243
|
+
* `clientProjection.omitColumns` applied — the same projection the generator's synced/overlay DDL
|
|
244
|
+
* carries.
|
|
245
|
+
*/
|
|
246
|
+
function projectedColumnBuilders(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {
|
|
247
|
+
const makeColumns = entry.makeColumns;
|
|
248
|
+
if (!makeColumns) {
|
|
249
|
+
throw new Error(
|
|
250
|
+
`local table objects for ${tableKey} need the entry's makeColumns factory (built by defineSyncTable); ` +
|
|
251
|
+
`hand-assembled entries cannot derive overlay/journal objects`,
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
const omitted = new Set(entry.clientProjection?.omitColumns ?? []);
|
|
255
|
+
return Object.fromEntries(Object.entries(makeColumns()).filter(([key]) => !omitted.has(key))) as Record<
|
|
256
|
+
string,
|
|
257
|
+
ColumnBuilderBase
|
|
258
|
+
>;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Property-key ↔ column-name pairs for the entry's PK, resolved via the built local table. */
|
|
262
|
+
function pkColumnPairs(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {
|
|
263
|
+
const localColumns = getColumns(entry.localTable) as Record<string, PgColumn>;
|
|
264
|
+
return entry.primaryKey.columns.map((columnName) => {
|
|
265
|
+
const pair = Object.entries(localColumns).find(([, column]) => column.name === columnName);
|
|
266
|
+
if (!pair) {
|
|
267
|
+
throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
|
|
268
|
+
}
|
|
269
|
+
return { propertyKey: pair[0], columnName };
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
interface EntryLocalTables {
|
|
274
|
+
synced?: AnyPgTable;
|
|
275
|
+
overlay?: OverlayTable;
|
|
276
|
+
journal?: JournalTable;
|
|
277
|
+
syncState?: SyncStateView;
|
|
278
|
+
readModel?: ReadModelView;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();
|
|
282
|
+
const localMetaCache = new Map<string, LocalMetaTable>();
|
|
283
|
+
|
|
284
|
+
function cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {
|
|
285
|
+
let byKey = localTablesCache.get(registry);
|
|
286
|
+
if (!byKey) {
|
|
287
|
+
byKey = new Map();
|
|
288
|
+
localTablesCache.set(registry, byKey);
|
|
289
|
+
}
|
|
290
|
+
let slot = byKey.get(tableKey);
|
|
291
|
+
if (!slot) {
|
|
292
|
+
slot = {};
|
|
293
|
+
byKey.set(tableKey, slot);
|
|
294
|
+
}
|
|
295
|
+
return slot;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function requireEntry(registry: SyncTableRegistry, tableKey: string): SyncTableEntry<AnyPgTable> {
|
|
299
|
+
const entry = registry[tableKey];
|
|
300
|
+
if (!entry) {
|
|
301
|
+
throw new Error(`Unknown sync table: ${tableKey}`);
|
|
302
|
+
}
|
|
303
|
+
return entry;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function requireWritable(entry: SyncTableEntry<AnyPgTable>, tableKey: string, relation: string) {
|
|
307
|
+
if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {
|
|
308
|
+
throw new Error(`${relation} exists only for a writable table; ${tableKey} has no overlay/journal projection`);
|
|
309
|
+
}
|
|
310
|
+
return entry.clientProjection as { overlayTable: string; journalTable: string; syncedTable?: string };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* The projected SYNCED read-cache table as a runtime Drizzle object, under the resolved local name
|
|
315
|
+
* (`clientProjection.syncedTable` override honoured) and the registry's local schema — the exact
|
|
316
|
+
* relation the generator's `CREATE TABLE` provisions. Prefer `entry.localTable` where its name
|
|
317
|
+
* already matches; this object exists for the runtime/tests that must track the projection rename.
|
|
318
|
+
* Carries the entry's real projected columns under a concretely-typed registry, `AnyPgTable` under a
|
|
319
|
+
* bare `SyncTableRegistry` (see {@link SyncedLocalTable}).
|
|
320
|
+
*/
|
|
321
|
+
export function getSyncedLocalTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(
|
|
322
|
+
registry: TRegistry,
|
|
323
|
+
tableKey: TKey,
|
|
324
|
+
): SyncedLocalTable<TRegistry[TKey]> {
|
|
325
|
+
const slot = cacheFor(registry, tableKey);
|
|
326
|
+
if (slot.synced) {
|
|
327
|
+
return slot.synced as SyncedLocalTable<TRegistry[TKey]>;
|
|
328
|
+
}
|
|
329
|
+
const entry = requireEntry(registry, tableKey);
|
|
330
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
331
|
+
const table = makeTable(
|
|
332
|
+
localSchema,
|
|
333
|
+
resolveSyncedTableName(entry),
|
|
334
|
+
projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>,
|
|
335
|
+
isEphemeral(entry),
|
|
336
|
+
);
|
|
337
|
+
slot.synced = table;
|
|
338
|
+
return table as SyncedLocalTable<TRegistry[TKey]>;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The `<t>_overlay` optimistic-intent table as a runtime Drizzle object (writable tables only — throws
|
|
343
|
+
* for a readonly entry, which has no overlay/journal projection). Its entity columns are typed exactly
|
|
344
|
+
* as {@link OverlayTable} describes — real per-column types under a concretely-typed registry, the open
|
|
345
|
+
* index-signature fallback under a bare `SyncTableRegistry` — plus the two fixed overlay columns.
|
|
346
|
+
*/
|
|
347
|
+
export function getOverlayTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(
|
|
348
|
+
registry: TRegistry,
|
|
349
|
+
tableKey: TKey,
|
|
350
|
+
): OverlayTable<TRegistry[TKey]> {
|
|
351
|
+
const slot = cacheFor(registry, tableKey);
|
|
352
|
+
if (slot.overlay) {
|
|
353
|
+
return slot.overlay as OverlayTable<TRegistry[TKey]>;
|
|
354
|
+
}
|
|
355
|
+
const entry = requireEntry(registry, tableKey);
|
|
356
|
+
const projection = requireWritable(entry, tableKey, "the overlay table");
|
|
357
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
358
|
+
const table = makeTable(
|
|
359
|
+
localSchema,
|
|
360
|
+
projection.overlayTable,
|
|
361
|
+
{
|
|
362
|
+
...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),
|
|
363
|
+
...buildOverlayFixedColumns(),
|
|
364
|
+
},
|
|
365
|
+
isEphemeral(entry),
|
|
366
|
+
) as OverlayTable;
|
|
367
|
+
slot.overlay = table;
|
|
368
|
+
return table as OverlayTable<TRegistry[TKey]>;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The `<t>_mutations` journal table as a runtime Drizzle object (writable tables only). The fixed runtime
|
|
373
|
+
* columns are typed; the PK/entity columns ride the index signature and are reached by DB column NAME
|
|
374
|
+
* (`journal["id"]`), because per-entry typing is not representable — see {@link JournalTable}.
|
|
375
|
+
*/
|
|
376
|
+
export function getJournalTable<TRegistry extends SyncTableRegistry>(
|
|
377
|
+
registry: TRegistry,
|
|
378
|
+
tableKey: string & keyof TRegistry,
|
|
379
|
+
): JournalTable {
|
|
380
|
+
const slot = cacheFor(registry, tableKey);
|
|
381
|
+
if (slot.journal) {
|
|
382
|
+
return slot.journal;
|
|
383
|
+
}
|
|
384
|
+
const entry = requireEntry(registry, tableKey);
|
|
385
|
+
const projection = requireWritable(entry, tableKey, "the journal table");
|
|
386
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
387
|
+
const pkBuilders = Object.fromEntries(
|
|
388
|
+
pkColumnPairs(entry, tableKey).map(({ columnName }) => [columnName, text(columnName).notNull()]),
|
|
389
|
+
);
|
|
390
|
+
const table = makeTable(
|
|
391
|
+
localSchema,
|
|
392
|
+
projection.journalTable,
|
|
393
|
+
{
|
|
394
|
+
...pkBuilders,
|
|
395
|
+
...buildJournalFixedColumns(),
|
|
396
|
+
},
|
|
397
|
+
isEphemeral(entry),
|
|
398
|
+
) as JournalTable;
|
|
399
|
+
slot.journal = table;
|
|
400
|
+
return table;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* The `<t>_sync_state` convergence view (ADR-0011) as a runtime Drizzle object (writable tables only) —
|
|
405
|
+
* PK columns under the entry's own property keys plus the fixed state columns, mirroring
|
|
406
|
+
* `buildSyncStateView`'s projection. The fixed state columns are typed; the PK columns ride the index
|
|
407
|
+
* signature (not recoverable at the type level — see {@link SyncStateView}) and are reached by their
|
|
408
|
+
* drizzle PROPERTY key (`view["authorId"]`), unlike the journal, which keys its PK columns by DB column
|
|
409
|
+
* name.
|
|
410
|
+
*/
|
|
411
|
+
export function getSyncStateView<TRegistry extends SyncTableRegistry>(
|
|
412
|
+
registry: TRegistry,
|
|
413
|
+
tableKey: string & keyof TRegistry,
|
|
414
|
+
): SyncStateView {
|
|
415
|
+
const slot = cacheFor(registry, tableKey);
|
|
416
|
+
if (slot.syncState) {
|
|
417
|
+
return slot.syncState;
|
|
418
|
+
}
|
|
419
|
+
const entry = requireEntry(registry, tableKey);
|
|
420
|
+
requireWritable(entry, tableKey, "the sync-state view");
|
|
421
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
422
|
+
const viewName = `${resolveSyncedTableName(entry)}_sync_state`;
|
|
423
|
+
const builders = projectedColumnBuilders(entry, tableKey);
|
|
424
|
+
const pkBuilders = Object.fromEntries(
|
|
425
|
+
pkColumnPairs(entry, tableKey).map(({ propertyKey }) => {
|
|
426
|
+
const builder = builders[propertyKey];
|
|
427
|
+
if (!builder) {
|
|
428
|
+
throw new Error(`Primary key property ${propertyKey} was not found on table ${tableKey}`);
|
|
429
|
+
}
|
|
430
|
+
return [propertyKey, builder];
|
|
431
|
+
}),
|
|
432
|
+
) as Record<string, ColumnBuilderBase>;
|
|
433
|
+
const columns = {
|
|
434
|
+
...(pkBuilders as Record<string, ColumnBuilderBase>),
|
|
435
|
+
...buildSyncStateFixedColumns(),
|
|
436
|
+
};
|
|
437
|
+
const view = (
|
|
438
|
+
localSchema === "public" || isEphemeral(entry)
|
|
439
|
+
? pgView(viewName, columns).existing()
|
|
440
|
+
: pgSchema(localSchema).view(viewName, columns).existing()
|
|
441
|
+
) as SyncStateView;
|
|
442
|
+
slot.syncState = view;
|
|
443
|
+
return view;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* The `<t>_read_model` overlay-merged read view (ADR-0004) as a runtime Drizzle object: every projected
|
|
448
|
+
* synced column under the entry's own property key plus the two overlay columns (`overlay_kind`,
|
|
449
|
+
* `local_updated_at_us`), mirroring the generator's `CREATE VIEW`. The entry's own `entry.view` is
|
|
450
|
+
* schema-UNQUALIFIED (`defineSyncTable` builds it with a bare `pgView`), so a consumer whose local store
|
|
451
|
+
* lives in a non-public schema must author against this qualified object instead of `entry.view`.
|
|
452
|
+
*/
|
|
453
|
+
export function getReadModelView<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(
|
|
454
|
+
registry: TRegistry,
|
|
455
|
+
tableKey: TKey,
|
|
456
|
+
): ReadModelView<TRegistry[TKey]> {
|
|
457
|
+
const slot = cacheFor(registry, tableKey);
|
|
458
|
+
if (slot.readModel) {
|
|
459
|
+
return slot.readModel as ReadModelView<TRegistry[TKey]>;
|
|
460
|
+
}
|
|
461
|
+
const entry = requireEntry(registry, tableKey);
|
|
462
|
+
requireWritable(entry, tableKey, "the read-model view");
|
|
463
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
464
|
+
const viewName = `${resolveSyncedTableName(entry)}_read_model`;
|
|
465
|
+
const columns = {
|
|
466
|
+
...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),
|
|
467
|
+
...buildReadModelFixedColumns(),
|
|
468
|
+
};
|
|
469
|
+
const view = (
|
|
470
|
+
localSchema === "public" || isEphemeral(entry)
|
|
471
|
+
? pgView(viewName, columns).existing()
|
|
472
|
+
: pgSchema(localSchema).view(viewName, columns).existing()
|
|
473
|
+
) as ReadModelView;
|
|
474
|
+
slot.readModel = view;
|
|
475
|
+
return view as ReadModelView<TRegistry[TKey]>;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* The read-path applier's resolved per-shape target (ADR-0029 D1/D2). Every table-scoped fact the
|
|
480
|
+
* appliers need is derived once from the registry entry — the real projected synced table object, its
|
|
481
|
+
* columns indexed by DB column name, the primary-key column names, and the model-derived column types —
|
|
482
|
+
* so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).
|
|
483
|
+
* Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed
|
|
484
|
+
* by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.
|
|
485
|
+
*/
|
|
486
|
+
export interface ApplyTarget {
|
|
487
|
+
/** The real projected synced local table (`getSyncedLocalTable`) — bare for ephemeral lifecycles. */
|
|
488
|
+
table: AnyPgTable;
|
|
489
|
+
/** DB column name → its Drizzle `PgColumn` (for `eq`/conflict-target/COPY clauses). */
|
|
490
|
+
columnByName: Record<string, PgColumn>;
|
|
491
|
+
/** DB column name → its Drizzle property key (to key `.values()`/`.set()` from a name-keyed row). */
|
|
492
|
+
propertyKeyByName: Record<string, string>;
|
|
493
|
+
/** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
|
|
494
|
+
primaryKey: string[];
|
|
495
|
+
/** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
|
|
496
|
+
columnTypes: SyncColumnType[];
|
|
497
|
+
/**
|
|
498
|
+
* Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,
|
|
499
|
+
* params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied
|
|
500
|
+
* at execution. Empty at resolution; populated lazily by the applier.
|
|
501
|
+
*/
|
|
502
|
+
insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape
|
|
507
|
+
* at subscribe time — never per message. The single source is the registry item: identity via
|
|
508
|
+
* `getSyncedLocalTable`, PKs via `getLocalSyncedTablePrimaryKeyColumns`, types via `deriveSyncColumnTypes`.
|
|
509
|
+
*/
|
|
510
|
+
export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(
|
|
511
|
+
registry: TRegistry,
|
|
512
|
+
tableKey: TKey,
|
|
513
|
+
): ApplyTarget {
|
|
514
|
+
const entry = requireEntry(registry, tableKey);
|
|
515
|
+
const table = getSyncedLocalTable(registry, tableKey);
|
|
516
|
+
const columns = getColumns(table as AnyPgTable) as Record<string, PgColumn>;
|
|
517
|
+
const columnByName: Record<string, PgColumn> = {};
|
|
518
|
+
const propertyKeyByName: Record<string, string> = {};
|
|
519
|
+
for (const [propertyKey, column] of Object.entries(columns)) {
|
|
520
|
+
columnByName[column.name] = column;
|
|
521
|
+
propertyKeyByName[column.name] = propertyKey;
|
|
522
|
+
}
|
|
523
|
+
return {
|
|
524
|
+
table: table as AnyPgTable,
|
|
525
|
+
columnByName,
|
|
526
|
+
propertyKeyByName,
|
|
527
|
+
primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
|
|
528
|
+
columnTypes: deriveSyncColumnTypes(entry),
|
|
529
|
+
insertRenderCache: new Map(),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */
|
|
534
|
+
export function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {
|
|
535
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
536
|
+
const cached = localMetaCache.get(localSchema);
|
|
537
|
+
if (cached) {
|
|
538
|
+
return cached;
|
|
539
|
+
}
|
|
540
|
+
const table = makeTable(localSchema, LOCAL_META_TABLE, {
|
|
541
|
+
key: text("key").primaryKey(),
|
|
542
|
+
value: text("value").notNull(),
|
|
543
|
+
}) as LocalMetaTable;
|
|
544
|
+
localMetaCache.set(localSchema, table);
|
|
545
|
+
return table;
|
|
546
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The mutation-journal state machine (ADR-0005, extended by ADR-0006).
|
|
3
|
+
*
|
|
4
|
+
* The runtime is large; previously the legal status transitions were implicit,
|
|
5
|
+
* scattered across SQL writes. This is the one named place that defines them, so the
|
|
6
|
+
* rules are testable and a future change extends a single table. ADR-0006 splits the
|
|
7
|
+
* old single `failed` into transient (retryable `failed`) and permanent (`quarantined`).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type MutationStatus = "pending" | "sending" | "acked" | "failed" | "quarantined" | "conflicted" | "rejected";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Legal transitions. `acked` is terminal at the journal level — it is cleared by
|
|
14
|
+
* reconciliation once the synced echo reaches the acknowledged server timestamp, not
|
|
15
|
+
* by another status transition. `quarantined` is terminal too: the server will never
|
|
16
|
+
* accept the mutation as-is, so it is surfaced (callback + diagnostics), never retried.
|
|
17
|
+
* `conflicted` (ADR-0015) is likewise terminal but a *different* outcome: the write was
|
|
18
|
+
* well-formed but **stale** (an external write interleaved) and the table's `reject-if-stale`
|
|
19
|
+
* policy declined it. The optimistic Overlay is KEPT (the user's edit is not lost) and the
|
|
20
|
+
* conflict is surfaced via `onConflict`; resolution is an ordinary NEW mutation, and `discard`
|
|
21
|
+
* clears the overlay + this entry. It is never retried as-is (the base would still be stale).
|
|
22
|
+
* `rejected` (ADR-0022) is terminal as well, and the inverse of `conflicted` on disposition: the
|
|
23
|
+
* authoritative endpoint declined the whole pessimistic write-**unit** for a business reason (a
|
|
24
|
+
* capacity/quota/uniqueness rule the client could not evaluate locally), so the optimistic Overlay
|
|
25
|
+
* is **auto-discarded** for every member of the unit and the typed reason is surfaced via `onReject`.
|
|
26
|
+
* Never retried (the server's answer is authoritative).
|
|
27
|
+
*
|
|
28
|
+
* - `pending -> sending` a flush claims the row and posts it.
|
|
29
|
+
* - `sending -> acked` the server acknowledged the mutation.
|
|
30
|
+
* - `sending -> failed` transient transport/server error (network, 5xx, …).
|
|
31
|
+
* - `sending -> quarantined` structural 4xx rejection the server will never accept.
|
|
32
|
+
* - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).
|
|
33
|
+
* - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).
|
|
34
|
+
* - `sending -> pending` recoverSending re-queues an in-flight row on startup.
|
|
35
|
+
* - `failed -> pending` retryFailed re-queues a failed row.
|
|
36
|
+
* - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying.
|
|
37
|
+
*/
|
|
38
|
+
export const MUTATION_TRANSITIONS = {
|
|
39
|
+
pending: ["sending"],
|
|
40
|
+
sending: ["acked", "failed", "quarantined", "conflicted", "rejected", "pending"],
|
|
41
|
+
failed: ["pending", "quarantined"],
|
|
42
|
+
quarantined: [],
|
|
43
|
+
conflicted: [],
|
|
44
|
+
rejected: [],
|
|
45
|
+
acked: [],
|
|
46
|
+
} as const satisfies Record<MutationStatus, readonly MutationStatus[]>;
|
|
47
|
+
|
|
48
|
+
export function isValidMutationTransition(from: MutationStatus, to: MutationStatus): boolean {
|
|
49
|
+
return (MUTATION_TRANSITIONS[from] as readonly MutationStatus[]).includes(to);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function assertValidMutationTransition(from: MutationStatus, to: MutationStatus): void {
|
|
53
|
+
if (!isValidMutationTransition(from, to)) {
|
|
54
|
+
throw new Error(`Illegal mutation-journal transition: ${from} -> ${to}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The hard cap on send attempts (ADR-0005 congestion policy). A mutation that has
|
|
60
|
+
* failed this many times — even with transient-looking errors — is given up on and
|
|
61
|
+
* quarantined, so a permanently-unreachable server never produces an unbounded retry
|
|
62
|
+
* loop. The consumer can raise/lower it via `createSyncClient({ maxMutationAttempts })`.
|
|
63
|
+
*/
|
|
64
|
+
export const DEFAULT_MAX_MUTATION_ATTEMPTS = 10;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 4xx statuses that are nonetheless transient: auth (the runtime refreshes the token and
|
|
68
|
+
* retries), request-timeout, too-early, and rate-limit. Everything else in the 4xx range
|
|
69
|
+
* is treated as a structural rejection the server will never accept as-is.
|
|
70
|
+
*/
|
|
71
|
+
const TRANSIENT_CLIENT_ERROR_STATUSES: ReadonlySet<number> = new Set([401, 403, 408, 425, 429]);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Classify a flush failure into its durable journal state (ADR-0006 decision 4):
|
|
75
|
+
* - `quarantined` (terminal): a structural 4xx rejection — retrying is pointless, so it
|
|
76
|
+
* is surfaced rather than retry-looped (the silent-data-loss case the runtime *can*
|
|
77
|
+
* catch at send time).
|
|
78
|
+
* - `failed` (retryable): network/transport (no status), any 5xx, or a transient 4xx.
|
|
79
|
+
*/
|
|
80
|
+
export function classifyFailureStatus(httpStatus: number | null | undefined): "failed" | "quarantined" {
|
|
81
|
+
if (httpStatus == null) {
|
|
82
|
+
return "failed";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (httpStatus >= 400 && httpStatus < 500 && !TRANSIENT_CLIENT_ERROR_STATUSES.has(httpStatus)) {
|
|
86
|
+
return "quarantined";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return "failed";
|
|
90
|
+
}
|