@pgxsinkit/client 0.1.32 → 0.1.40

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.
Files changed (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,135 @@
1
+ // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
+ // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
+ import type { Offset } from "@electric-sql/client";
4
+ import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
+ import { eq } from "drizzle-orm";
6
+
7
+ import { quoteIdentifier } from "@pgxsinkit/contracts";
8
+
9
+ import { renderCreateTableSql } from "../schema";
10
+ import { drizzleOverPg } from "./drizzle-executor";
11
+ import { getMetadataTables } from "./metadata-tables";
12
+ import { type Lsn, type SubscriptionKey } from "./types";
13
+
14
+ export interface SubscriptionState {
15
+ key: SubscriptionKey;
16
+ shape_metadata: Record<string, ShapeSubscriptionState>;
17
+ last_lsn: Lsn;
18
+ }
19
+
20
+ export interface ShapeSubscriptionState {
21
+ handle: string;
22
+ offset: Offset;
23
+ }
24
+
25
+ export interface GetSubscriptionStateOptions {
26
+ readonly pg: PGliteInterface | Transaction;
27
+ readonly metadataSchema: string;
28
+ readonly subscriptionKey: SubscriptionKey;
29
+ }
30
+
31
+ export async function getSubscriptionState({
32
+ pg,
33
+ metadataSchema,
34
+ subscriptionKey,
35
+ }: GetSubscriptionStateOptions): Promise<SubscriptionState | null> {
36
+ const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
37
+ const rows = await drizzleOverPg(pg)
38
+ .select()
39
+ .from(subscriptionsMetadata)
40
+ .where(eq(subscriptionsMetadata.key, subscriptionKey));
41
+
42
+ if (rows.length === 0) {
43
+ return null;
44
+ }
45
+ if (rows.length > 1) {
46
+ throw new Error(`Multiple subscriptions found for key: ${subscriptionKey}`);
47
+ }
48
+
49
+ const row = rows[0];
50
+ if (!row) {
51
+ throw new Error(`Subscription row missing for key: ${subscriptionKey}`);
52
+ }
53
+ if (typeof row.key !== "string") {
54
+ throw new Error(`Invalid key type: ${typeof row.key}`);
55
+ }
56
+ if (!row.shape_metadata || typeof row.shape_metadata !== "object") {
57
+ throw new Error("Invalid shape_metadata payload");
58
+ }
59
+ if (typeof row.last_lsn !== "string") {
60
+ throw new Error(`Invalid last_lsn type: ${typeof row.last_lsn}`);
61
+ }
62
+
63
+ return {
64
+ key: row.key,
65
+ shape_metadata: row.shape_metadata,
66
+ last_lsn: BigInt(row.last_lsn),
67
+ };
68
+ }
69
+
70
+ export interface UpdateSubscriptionStateOptions {
71
+ pg: PGliteInterface | Transaction;
72
+ metadataSchema: string;
73
+ subscriptionKey: SubscriptionKey;
74
+ shapeMetadata: Record<string, ShapeSubscriptionState>;
75
+ lastLsn: Lsn;
76
+ debug?: boolean;
77
+ }
78
+
79
+ export async function updateSubscriptionState({
80
+ pg,
81
+ metadataSchema,
82
+ subscriptionKey,
83
+ shapeMetadata,
84
+ lastLsn,
85
+ debug,
86
+ }: UpdateSubscriptionStateOptions) {
87
+ if (debug) {
88
+ console.log("updating subscription state", subscriptionKey, shapeMetadata, lastLsn);
89
+ }
90
+
91
+ const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
92
+ const lastLsnText = lastLsn.toString();
93
+ await drizzleOverPg(pg)
94
+ .insert(subscriptionsMetadata)
95
+ .values({ key: subscriptionKey, shape_metadata: shapeMetadata, last_lsn: lastLsnText })
96
+ .onConflictDoUpdate({
97
+ target: subscriptionsMetadata.key,
98
+ set: { shape_metadata: shapeMetadata, last_lsn: lastLsnText },
99
+ });
100
+ }
101
+
102
+ export interface DeleteSubscriptionStateOptions {
103
+ pg: PGliteInterface | Transaction;
104
+ metadataSchema: string;
105
+ subscriptionKey: SubscriptionKey;
106
+ }
107
+
108
+ export async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions) {
109
+ const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
110
+ await drizzleOverPg(pg).delete(subscriptionsMetadata).where(eq(subscriptionsMetadata.key, subscriptionKey));
111
+ }
112
+
113
+ export interface MigrateSubscriptionMetadataTablesOptions {
114
+ pg: PGliteInterface | Transaction;
115
+ metadataSchema: string;
116
+ }
117
+
118
+ export async function migrateSubscriptionMetadataTables({
119
+ pg,
120
+ metadataSchema,
121
+ }: MigrateSubscriptionMetadataTablesOptions) {
122
+ // ADR-0029 D3: the metadata relations are RENDERED from the `metadata-tables.ts` pgTables through the
123
+ // in-house schema renderer (`renderCreateTableSql`), so the pgTable is the single source and the old
124
+ // DDL/pgTable drift can no longer exist. The CREATE SCHEMA + `SET` GUC default remain tier-③-by-nature
125
+ // (schema identifier assembled at construction; the GUC has no tier-①/② form). Executed together as
126
+ // one batch, exactly as before — same relations, same IF NOT EXISTS idempotence, same GUC default.
127
+ const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);
128
+ const statements = [
129
+ `SET ${metadataSchema}.syncing = false;`,
130
+ `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)};`,
131
+ ...renderCreateTableSql(subscriptionsMetadata),
132
+ ...renderCreateTableSql(shapeRowTags),
133
+ ];
134
+ await pg.exec(statements.join("\n"));
135
+ }
@@ -0,0 +1,365 @@
1
+ import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
+ import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
3
+ import { and, eq, inArray, like, sql } from "drizzle-orm";
4
+ import { getTableConfig } from "drizzle-orm/pg-core";
5
+
6
+ import { quoteIdentifier, quoteSqlLiteral } from "@pgxsinkit/contracts";
7
+
8
+ import type { ApplyTarget } from "../local-tables";
9
+ import { applyBulkDeletesToTable } from "./apply";
10
+ import { drizzleOverPg } from "./drizzle-executor";
11
+ import { getMetadataTables } from "./metadata-tables";
12
+
13
+ /**
14
+ * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
15
+ * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)
16
+ * streams two extra things the plain change path ignores:
17
+ *
18
+ * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per
19
+ * grant/membership), plus `removed_tags` on an update;
20
+ * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — "the tag whose component at
21
+ * index `pos` equals `value` is withdrawn", i.e. that grant was revoked.
22
+ *
23
+ * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`
24
+ * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one
25
+ * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an
26
+ * Electric change.
27
+ *
28
+ * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:
29
+ * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.
30
+ */
31
+
32
+ /**
33
+ * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.
34
+ * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so
35
+ * the desync path (which is outside the engine) can key the tag store by this same constant.
36
+ */
37
+ export const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
38
+
39
+ /**
40
+ * A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then
41
+ * lowercase letters, digits, and underscores.
42
+ */
43
+ const METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;
44
+
45
+ /**
46
+ * Validate the metadata schema name at engine construction. The name is interpolated RAW into two
47
+ * positions a double-quoted identifier cannot cover:
48
+ * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
49
+ * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
50
+ * accept a quoted identifier the way a table/column position does, so the name cannot be safely
51
+ * quoted there.
52
+ * - the `CREATE SCHEMA <schema>` DDL identifier position.
53
+ * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
54
+ * lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
55
+ */
56
+ export function assertValidMetadataSchema(metadataSchema: string): void {
57
+ if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {
58
+ throw new Error(
59
+ `Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +
60
+ `identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +
61
+ `GUC (\`SET <schema>.syncing\`) and \`CREATE SCHEMA\` identifier positions where a quoted ` +
62
+ `identifier is not accepted, so uppercase and exotic names are rejected at construction.`,
63
+ );
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config
69
+ * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by
70
+ * `migrateSubscriptionMetadataTables`, which renders that same pgTable.
71
+ */
72
+ export function shapeRowTagsTableName(metadataSchema: string): string {
73
+ const config = getTableConfig(getMetadataTables(metadataSchema).shapeRowTags);
74
+ return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
75
+ }
76
+
77
+ /** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
78
+ export function shapeTableId(schema: string | undefined, table: string): string {
79
+ return `${schema ?? "public"}.${table}`;
80
+ }
81
+
82
+ /**
83
+ * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
84
+ * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
85
+ * caller/test that builds the local schema without booting the sync engine that creates the store). The
86
+ * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
87
+ * guarded.
88
+ */
89
+ export function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {
90
+ const table = shapeRowTagsTableName(metadataSchema);
91
+ return `DO $$ BEGIN
92
+ IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
93
+ DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
94
+ END IF;
95
+ END $$;`;
96
+ }
97
+
98
+ /**
99
+ * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
100
+ * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
101
+ * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
102
+ */
103
+ export function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string {
104
+ const obj: Record<string, unknown> = {};
105
+ for (const column of [...primaryKey].sort()) {
106
+ obj[column] = value[column];
107
+ }
108
+ return JSON.stringify(obj, (_key, v: unknown) => (typeof v === "bigint" ? v.toString() : v));
109
+ }
110
+
111
+ /**
112
+ * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
113
+ * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
114
+ * two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
115
+ * `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
116
+ *
117
+ * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
118
+ * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
119
+ */
120
+ export function splitTagComponents(tag: string): string[] {
121
+ const parts: string[] = [];
122
+ let current = "";
123
+ for (let i = 0; i < tag.length; i++) {
124
+ const char = tag[i]!;
125
+ if (char === "\\" && i + 1 < tag.length) {
126
+ current += tag[i + 1];
127
+ i += 1;
128
+ continue;
129
+ }
130
+ if (char === "/") {
131
+ parts.push(current);
132
+ current = "";
133
+ continue;
134
+ }
135
+ current += char;
136
+ }
137
+ parts.push(current);
138
+ return parts;
139
+ }
140
+
141
+ /**
142
+ * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
143
+ * of the shape's tag structure (one position per subquery condition that references it), so the event
144
+ * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
145
+ * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
146
+ * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
147
+ * matches nothing.
148
+ */
149
+ export function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean {
150
+ if (patterns.length === 0) return false;
151
+ const parts = splitTagComponents(tag);
152
+ return patterns.some((pattern) => parts[pattern.pos] === pattern.value);
153
+ }
154
+
155
+ interface TagSyncOptions {
156
+ pg: PGliteInterface | Transaction;
157
+ metadataSchema: string;
158
+ shapeTable: string;
159
+ messages: ChangeMessage<Row<unknown>>[];
160
+ primaryKey: string[];
161
+ }
162
+
163
+ /**
164
+ * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
165
+ * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
166
+ * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
167
+ * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
168
+ * eviction in the same commit, so an add-then-remove within one batch resolves correctly.
169
+ */
170
+ export async function applyShapeTagSync({
171
+ pg,
172
+ metadataSchema,
173
+ shapeTable,
174
+ messages,
175
+ primaryKey,
176
+ }: TagSyncOptions): Promise<void> {
177
+ const { shapeRowTags } = getMetadataTables(metadataSchema);
178
+ const db = drizzleOverPg(pg);
179
+
180
+ for (const message of messages) {
181
+ const data = message.value;
182
+ const pkJson = serializeRowPk(data, primaryKey);
183
+
184
+ if (message.headers.operation === "delete") {
185
+ await db
186
+ .delete(shapeRowTags)
187
+ .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));
188
+ continue;
189
+ }
190
+
191
+ const tags = message.headers.tags;
192
+ if (tags !== undefined) {
193
+ // `tags` is the authoritative current reason-set → replace.
194
+ await db
195
+ .delete(shapeRowTags)
196
+ .where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));
197
+ if (tags.length > 0) {
198
+ await db
199
+ .insert(shapeRowTags)
200
+ .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))
201
+ .onConflictDoNothing();
202
+ }
203
+ continue;
204
+ }
205
+
206
+ const removedTags = message.headers.removed_tags;
207
+ if (removedTags && removedTags.length > 0) {
208
+ await db
209
+ .delete(shapeRowTags)
210
+ .where(
211
+ and(
212
+ eq(shapeRowTags.shape_table, shapeTable),
213
+ eq(shapeRowTags.pk_json, pkJson),
214
+ inArray(shapeRowTags.tag, removedTags),
215
+ ),
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
223
+ * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
224
+ * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
225
+ * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
226
+ * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
227
+ * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
228
+ * A row with no `tags` (a non-subquery shape) is a no-op.
229
+ */
230
+ export async function addShapeRowTags({
231
+ pg,
232
+ metadataSchema,
233
+ shapeTable,
234
+ messages,
235
+ primaryKey,
236
+ }: TagSyncOptions): Promise<void> {
237
+ const { shapeRowTags } = getMetadataTables(metadataSchema);
238
+ const db = drizzleOverPg(pg);
239
+
240
+ for (const message of messages) {
241
+ const tags = message.headers.tags;
242
+ if (!tags || tags.length === 0) continue;
243
+
244
+ const data = message.value;
245
+ const pkJson = serializeRowPk(data, primaryKey);
246
+ await db
247
+ .insert(shapeRowTags)
248
+ .values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))
249
+ .onConflictDoNothing();
250
+ }
251
+ }
252
+
253
+ interface MoveOutOptions {
254
+ pg: PGliteInterface | Transaction;
255
+ metadataSchema: string;
256
+ shapeTable: string;
257
+ /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
258
+ target: ApplyTarget;
259
+ /** One entry per buffered `move-out` event, each its own pattern set. */
260
+ patternSets: MovePattern[][];
261
+ debug: boolean;
262
+ }
263
+
264
+ /**
265
+ * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
266
+ * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
267
+ * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
268
+ * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
269
+ */
270
+ export async function applyShapeMoveOut({
271
+ pg,
272
+ metadataSchema,
273
+ shapeTable,
274
+ target,
275
+ patternSets,
276
+ debug,
277
+ }: MoveOutOptions): Promise<number> {
278
+ const { shapeRowTags } = getMetadataTables(metadataSchema);
279
+ const db = drizzleOverPg(pg);
280
+ const evictedPkJsons = new Set<string>();
281
+
282
+ for (const patterns of patternSets) {
283
+ if (patterns.length === 0) continue;
284
+
285
+ // Candidate tags: those containing every pattern value as a substring — a cheap superset of a real
286
+ // positional match, confirmed in JS so composite/positional tags are handled correctly. Each
287
+ // `like(tag, "%value%")` reproduces the former `tag LIKE '%' || $n || '%'` exactly: a param bound to
288
+ // the concatenated pattern string, so any LIKE metacharacters in the value keep the same semantics.
289
+ const candidateRows = await db
290
+ .select({ pk_json: shapeRowTags.pk_json, tag: shapeRowTags.tag })
291
+ .from(shapeRowTags)
292
+ .where(
293
+ and(
294
+ eq(shapeRowTags.shape_table, shapeTable),
295
+ ...patterns.map((pattern) => like(shapeRowTags.tag, `%${pattern.value}%`)),
296
+ ),
297
+ );
298
+ const matched = candidateRows.filter((row) => tagMatchesPatterns(row.tag, patterns));
299
+ if (matched.length === 0) continue;
300
+
301
+ // Withdraw the moved-out tag from each matching row (one set-based delete of the (pk, tag) pairs).
302
+ // Tier ② (ADR-0028): a set-based delete joined against a JSON recordset has no tier-① builder form —
303
+ // the shape-tag table object is interpolated and the pair list is a bound `::json` param; the
304
+ // alias-qualified `t.*` / `x.*` identifiers are raw only because the `USING`/recordset-join grammar
305
+ // requires them.
306
+ const pairs = matched.map((row) => ({ pk_json: row.pk_json, tag: row.tag }));
307
+ await db.execute(
308
+ sql`DELETE FROM ${shapeRowTags} AS t USING json_to_recordset(${JSON.stringify(pairs)}::json) AS x(pk_json text, tag text)
309
+ WHERE t.shape_table = ${shapeTable} AND t.pk_json = x.pk_json AND t.tag = x.tag`,
310
+ );
311
+
312
+ // A row is evicted only if it has no tag left.
313
+ const affected = [...new Set(matched.map((row) => row.pk_json))];
314
+ // Tier ② (ADR-0028): bind the affected pk_json list as ONE array param via `= ANY(${param}::text[])`
315
+ // — drizzle has no ANY(array-param) builder, and `sql.param` binds the whole array as a single
316
+ // placeholder (removing the per-element bound-param ceiling `inArray` emits: one placeholder per PK,
317
+ // a ~65k-param wire cap on a huge move-out). The explicit `::text[]` cast pins the param type for the
318
+ // driver's extended-protocol type resolution. The `eq(shape_table)` conjunct and `selectDistinct`
319
+ // shape are preserved.
320
+ const remaining = await db
321
+ .selectDistinct({ pk_json: shapeRowTags.pk_json })
322
+ .from(shapeRowTags)
323
+ .where(
324
+ and(
325
+ eq(shapeRowTags.shape_table, shapeTable),
326
+ sql`${shapeRowTags.pk_json} = ANY(${sql.param(affected)}::text[])`,
327
+ ),
328
+ );
329
+ const stillTagged = new Set(remaining.map((row) => row.pk_json));
330
+ for (const pkJson of affected) {
331
+ if (!stillTagged.has(pkJson)) evictedPkJsons.add(pkJson);
332
+ }
333
+ }
334
+
335
+ if (evictedPkJsons.size === 0) return 0;
336
+
337
+ // Evict via the bulk-delete path so the reconcile trigger fires and the read model converges.
338
+ const messages = [...evictedPkJsons].map((pkJson) => ({
339
+ key: pkJson,
340
+ value: JSON.parse(pkJson) as Row<unknown>,
341
+ headers: { operation: "delete" as const },
342
+ }));
343
+ await applyBulkDeletesToTable({
344
+ pg,
345
+ target,
346
+ messages,
347
+ debug,
348
+ });
349
+
350
+ return evictedPkJsons.size;
351
+ }
352
+
353
+ /** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
354
+ export async function clearShapeTags({
355
+ pg,
356
+ metadataSchema,
357
+ shapeTable,
358
+ }: {
359
+ pg: PGliteInterface | Transaction;
360
+ metadataSchema: string;
361
+ shapeTable: string;
362
+ }): Promise<void> {
363
+ const { shapeRowTags } = getMetadataTables(metadataSchema);
364
+ await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));
365
+ }
@@ -0,0 +1,141 @@
1
+ // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
+ // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
+ import type { ChangeMessage, FetchError, Row, ShapeStreamInterface, ShapeStreamOptions } from "@electric-sql/client";
4
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
5
+
6
+ import type { SyncTableRegistry } from "@pgxsinkit/contracts";
7
+
8
+ import type { GroupBootStamp } from "../boot-report";
9
+
10
+ // Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types
11
+ // via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without
12
+ // the root workspace needing a direct dependency on the Electric client packages.
13
+ export type { Row, ShapeStreamOptions } from "@electric-sql/client";
14
+ export type { MultiShapeMessages } from "@electric-sql/experimental";
15
+
16
+ export type Lsn = bigint;
17
+
18
+ export type SubscriptionKey = string;
19
+ export type InitialInsertMethod = "insert" | "copy" | "json";
20
+
21
+ /** Default hard cap on commit-transaction attempts before the engine goes degraded (ADR-0009). */
22
+ export const DEFAULT_MAX_COMMIT_RETRIES = 5;
23
+
24
+ /**
25
+ * Per-shape options for the group form (ADR-0029 D1). Every table-scoped fact — local table identity,
26
+ * projection, primary keys, apply strategy, column types — is derived by the engine from the
27
+ * group-level `registry` and this shape's `tableKey`; none is passed here. Only the Electric shape
28
+ * stream, an optional per-shape backfill override, and the must-refetch hook remain.
29
+ */
30
+ export interface ShapeToTableOptions {
31
+ shape: ShapeStreamOptions<Row<unknown>>;
32
+ /** The registry table key this shape applies into — the engine's sole per-table spec (ADR-0029 D1). */
33
+ tableKey: string;
34
+ /**
35
+ * Must-refetch override: replaces the default `TRUNCATE` cache wipe (ADR-0029 D4). Receives a Drizzle
36
+ * handle bound to the commit transaction (`drizzleOverPg(tx)`), so a scoped clear authors tier-①
37
+ * (`db.delete(table).where(…)`).
38
+ */
39
+ onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
40
+ /**
41
+ * Per-shape initial-backfill apply strategy override (ADR-0009 decisions 2 + 3). In a consistency
42
+ * group each shape resolves its own apply path, so one shape's backfill never forces the rest onto
43
+ * plain `INSERT`. When set it wins over the registry-classified strategy; otherwise the strategy is
44
+ * derived from the entry and mapped, else the group-level default applies.
45
+ */
46
+ initialInsertMethod?: InitialInsertMethod | undefined;
47
+ }
48
+
49
+ export interface SyncShapesToTablesOptions {
50
+ key: string | null;
51
+ /** The engine's per-table spec source (ADR-0029 D1): every shape's `tableKey` resolves against it. */
52
+ registry: SyncTableRegistry;
53
+ shapes: Record<string, ShapeToTableOptions>;
54
+ initialInsertMethod?: InitialInsertMethod | undefined;
55
+ onInitialSync?: (() => void) | undefined;
56
+ /**
57
+ * Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a
58
+ * PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine
59
+ * starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the
60
+ * two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and
61
+ * gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it
62
+ * once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so
63
+ * the network catch-up overlaps those local phases instead of running strictly after them. Absent → the
64
+ * exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior
65
+ * subscription state, the overlap treats the group as a new subscription (`subState === null`), which the
66
+ * `freshStore` gate guarantees.
67
+ */
68
+ dbReady?: Promise<void> | undefined;
69
+ /** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */
70
+ onError?: ((error: FetchError | Error) => void) | undefined;
71
+ /**
72
+ * Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction
73
+ * still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its
74
+ * buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the
75
+ * read cache cannot silently diverge; recovery is a later commit or a restart/refetch.
76
+ */
77
+ onSyncError?: ((error: Error) => void) | undefined;
78
+ /**
79
+ * Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).
80
+ * The runtime uses this as the read path's "alive again" signal to clear an `auth-needed` status
81
+ * once sync resumes after re-authentication.
82
+ */
83
+ onSyncActivity?: (() => void) | undefined;
84
+ /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
85
+ maxCommitRetries?: number | undefined;
86
+ /**
87
+ * Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to
88
+ * the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an
89
+ * immediate retry instead of sleeping the real backoff.
90
+ */
91
+ commitRetryDelayMs?: ((attempt: number) => number) | undefined;
92
+ /**
93
+ * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
94
+ * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
95
+ * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
96
+ * boot without report instrumentation.
97
+ */
98
+ bootStamp?: GroupBootStamp | undefined;
99
+ }
100
+
101
+ export interface SyncShapesToTablesResult {
102
+ unsubscribe: () => void;
103
+ readonly isUpToDate: boolean;
104
+ streams: Record<string, ShapeStreamInterface<Row<unknown>>>;
105
+ }
106
+
107
+ /**
108
+ * Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based
109
+ * fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.
110
+ */
111
+ export interface SyncShapeToTableOptions {
112
+ shape: ShapeStreamOptions<Row<unknown>>;
113
+ registry: SyncTableRegistry;
114
+ tableKey: string;
115
+ shapeKey: string | null;
116
+ initialInsertMethod?: InitialInsertMethod | undefined;
117
+ onInitialSync?: (() => void) | undefined;
118
+ onError?: ((error: FetchError | Error) => void) | undefined;
119
+ /** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */
120
+ onSyncError?: ((error: Error) => void) | undefined;
121
+ /** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
122
+ maxCommitRetries?: number | undefined;
123
+ /** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */
124
+ commitRetryDelayMs?: ((attempt: number) => number) | undefined;
125
+ onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
126
+ }
127
+
128
+ export interface SyncShapeToTableResult {
129
+ unsubscribe: () => void;
130
+ readonly isUpToDate: boolean;
131
+ stream: ShapeStreamInterface<Row<unknown>>;
132
+ }
133
+
134
+ export interface ElectricSyncOptions {
135
+ debug?: boolean;
136
+ metadataSchema?: string;
137
+ }
138
+
139
+ export type InsertChangeMessage = ChangeMessage<Row<unknown>> & {
140
+ headers: { operation: "insert" };
141
+ };