@pgxsinkit/client 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/boot-report.d.ts +5 -2
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +35 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +90 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.d.ts.map +1 -1
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +47 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6258 -6443
- package/dist/index.js.map +26 -26
- package/dist/local-tables.d.ts +1 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +13 -21
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +8 -8
- package/dist/sync/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +21 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +2 -2
- package/dist/worker/attach-sync-client.d.ts +3 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/package.json +4 -5
- package/skills/core/SKILL.md +72 -55
- package/skills/operating/SKILL.md +120 -120
- package/src/boot-report.ts +4 -3
- package/src/circuits/envelope-to-change.ts +102 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +165 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +641 -0
- package/src/debug.ts +1 -85
- package/src/export-dump.ts +3 -2
- package/src/index.ts +290 -273
- package/src/lazy-guard.ts +1 -1
- package/src/local-tables.ts +9 -2
- package/src/schema.ts +2 -11
- package/src/sync/apply.ts +72 -110
- package/src/sync/copy.ts +15 -15
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +42 -1
- package/src/sync/subscription-state.ts +21 -3
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +8 -1
- package/src/worker/define-sync-worker.ts +122 -13
- package/src/worker/engine-control.ts +89 -0
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
package/src/sync/tags.ts
DELETED
|
@@ -1,390 +0,0 @@
|
|
|
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, getSessionMetadataTables, pickMetadataTables } 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
|
-
/**
|
|
78
|
-
* The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session
|
|
79
|
-
* `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind
|
|
80
|
-
* {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.
|
|
81
|
-
*/
|
|
82
|
-
export function shapeRowTagsSessionTableName(): string {
|
|
83
|
-
const config = getTableConfig(getSessionMetadataTables().shapeRowTags);
|
|
84
|
-
return `${quoteIdentifier(config.schema ?? "public")}.${quoteIdentifier(config.name)}`;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
|
|
88
|
-
export function shapeTableId(schema: string | undefined, table: string): string {
|
|
89
|
-
return `${schema ?? "public"}.${table}`;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
|
|
94
|
-
* does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
|
|
95
|
-
* caller/test that builds the local schema without booting the sync engine that creates the store). The
|
|
96
|
-
* engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
|
|
97
|
-
* guarded.
|
|
98
|
-
*/
|
|
99
|
-
export function buildClearShapeTagsSql(shapeTable: string, metadataSchema: string = DEFAULT_METADATA_SCHEMA): string {
|
|
100
|
-
// ADR-0042: SCOPE-BLIND — clear the shape's tags from BOTH the durable and the session (`pg_temp`) tag
|
|
101
|
-
// store, each guarded independently by `to_regclass` (a desync/discard may run on a persistent table whose
|
|
102
|
-
// session store never existed, or standalone before any engine boot). `to_regclass('pg_temp.shape_row_tags')`
|
|
103
|
-
// resolves the session table via the per-session `pg_temp` alias (probed on real PGlite).
|
|
104
|
-
const clearOne = (table: string) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
|
|
105
|
-
DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
|
|
106
|
-
END IF;`;
|
|
107
|
-
return `DO $$ BEGIN
|
|
108
|
-
${clearOne(shapeRowTagsTableName(metadataSchema))}
|
|
109
|
-
${clearOne(shapeRowTagsSessionTableName())}
|
|
110
|
-
END $$;`;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
|
|
115
|
-
* value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
|
|
116
|
-
* rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
|
|
117
|
-
*/
|
|
118
|
-
export function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string {
|
|
119
|
-
const obj: Record<string, unknown> = {};
|
|
120
|
-
for (const column of [...primaryKey].sort()) {
|
|
121
|
-
obj[column] = value[column];
|
|
122
|
-
}
|
|
123
|
-
return JSON.stringify(obj, (_key, v: unknown) => (typeof v === "bigint" ? v.toString() : v));
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
|
|
128
|
-
* is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
|
|
129
|
-
* two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
|
|
130
|
-
* `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
|
|
131
|
-
*
|
|
132
|
-
* (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
|
|
133
|
-
* ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
|
|
134
|
-
*/
|
|
135
|
-
export function splitTagComponents(tag: string): string[] {
|
|
136
|
-
const parts: string[] = [];
|
|
137
|
-
let current = "";
|
|
138
|
-
for (let i = 0; i < tag.length; i++) {
|
|
139
|
-
const char = tag[i]!;
|
|
140
|
-
if (char === "\\" && i + 1 < tag.length) {
|
|
141
|
-
current += tag[i + 1];
|
|
142
|
-
i += 1;
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (char === "/") {
|
|
146
|
-
parts.push(current);
|
|
147
|
-
current = "";
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
current += char;
|
|
151
|
-
}
|
|
152
|
-
parts.push(current);
|
|
153
|
-
return parts;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
|
|
158
|
-
* of the shape's tag structure (one position per subquery condition that references it), so the event
|
|
159
|
-
* enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
|
|
160
|
-
* is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
|
|
161
|
-
* empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
|
|
162
|
-
* matches nothing.
|
|
163
|
-
*/
|
|
164
|
-
export function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean {
|
|
165
|
-
if (patterns.length === 0) return false;
|
|
166
|
-
const parts = splitTagComponents(tag);
|
|
167
|
-
return patterns.some((pattern) => parts[pattern.pos] === pattern.value);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
interface TagSyncOptions {
|
|
171
|
-
pg: PGliteInterface | Transaction;
|
|
172
|
-
metadataSchema: string;
|
|
173
|
-
shapeTable: string;
|
|
174
|
-
messages: ChangeMessage<Row<unknown>>[];
|
|
175
|
-
primaryKey: string[];
|
|
176
|
-
/** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */
|
|
177
|
-
sessionScoped?: boolean;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
|
|
182
|
-
* change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
|
|
183
|
-
* row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
|
|
184
|
-
* shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
|
|
185
|
-
* eviction in the same commit, so an add-then-remove within one batch resolves correctly.
|
|
186
|
-
*/
|
|
187
|
-
export async function applyShapeTagSync({
|
|
188
|
-
pg,
|
|
189
|
-
metadataSchema,
|
|
190
|
-
shapeTable,
|
|
191
|
-
messages,
|
|
192
|
-
primaryKey,
|
|
193
|
-
sessionScoped = false,
|
|
194
|
-
}: TagSyncOptions): Promise<void> {
|
|
195
|
-
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
196
|
-
const db = drizzleOverPg(pg);
|
|
197
|
-
|
|
198
|
-
for (const message of messages) {
|
|
199
|
-
const data = message.value;
|
|
200
|
-
const pkJson = serializeRowPk(data, primaryKey);
|
|
201
|
-
|
|
202
|
-
if (message.headers.operation === "delete") {
|
|
203
|
-
await db
|
|
204
|
-
.delete(shapeRowTags)
|
|
205
|
-
.where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));
|
|
206
|
-
continue;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const tags = message.headers.tags;
|
|
210
|
-
if (tags !== undefined) {
|
|
211
|
-
// `tags` is the authoritative current reason-set → replace.
|
|
212
|
-
await db
|
|
213
|
-
.delete(shapeRowTags)
|
|
214
|
-
.where(and(eq(shapeRowTags.shape_table, shapeTable), eq(shapeRowTags.pk_json, pkJson)));
|
|
215
|
-
if (tags.length > 0) {
|
|
216
|
-
await db
|
|
217
|
-
.insert(shapeRowTags)
|
|
218
|
-
.values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))
|
|
219
|
-
.onConflictDoNothing();
|
|
220
|
-
}
|
|
221
|
-
continue;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
const removedTags = message.headers.removed_tags;
|
|
225
|
-
if (removedTags && removedTags.length > 0) {
|
|
226
|
-
await db
|
|
227
|
-
.delete(shapeRowTags)
|
|
228
|
-
.where(
|
|
229
|
-
and(
|
|
230
|
-
eq(shapeRowTags.shape_table, shapeTable),
|
|
231
|
-
eq(shapeRowTags.pk_json, pkJson),
|
|
232
|
-
inArray(shapeRowTags.tag, removedTags),
|
|
233
|
-
),
|
|
234
|
-
);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
|
|
241
|
-
* A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
|
|
242
|
-
* authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
|
|
243
|
-
* not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
|
|
244
|
-
* Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
|
|
245
|
-
* eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
|
|
246
|
-
* A row with no `tags` (a non-subquery shape) is a no-op.
|
|
247
|
-
*/
|
|
248
|
-
export async function addShapeRowTags({
|
|
249
|
-
pg,
|
|
250
|
-
metadataSchema,
|
|
251
|
-
shapeTable,
|
|
252
|
-
messages,
|
|
253
|
-
primaryKey,
|
|
254
|
-
sessionScoped = false,
|
|
255
|
-
}: TagSyncOptions): Promise<void> {
|
|
256
|
-
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
257
|
-
const db = drizzleOverPg(pg);
|
|
258
|
-
|
|
259
|
-
for (const message of messages) {
|
|
260
|
-
const tags = message.headers.tags;
|
|
261
|
-
if (!tags || tags.length === 0) continue;
|
|
262
|
-
|
|
263
|
-
const data = message.value;
|
|
264
|
-
const pkJson = serializeRowPk(data, primaryKey);
|
|
265
|
-
await db
|
|
266
|
-
.insert(shapeRowTags)
|
|
267
|
-
.values(tags.map((tag) => ({ shape_table: shapeTable, pk_json: pkJson, tag })))
|
|
268
|
-
.onConflictDoNothing();
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
interface MoveOutOptions {
|
|
273
|
-
pg: PGliteInterface | Transaction;
|
|
274
|
-
metadataSchema: string;
|
|
275
|
-
shapeTable: string;
|
|
276
|
-
/** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
|
|
277
|
-
target: ApplyTarget;
|
|
278
|
-
/** One entry per buffered `move-out` event, each its own pattern set. */
|
|
279
|
-
patternSets: MovePattern[][];
|
|
280
|
-
debug: boolean;
|
|
281
|
-
/** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */
|
|
282
|
-
sessionScoped?: boolean;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/**
|
|
286
|
-
* Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
|
|
287
|
-
* carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
|
|
288
|
-
* survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
|
|
289
|
-
* trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
|
|
290
|
-
*/
|
|
291
|
-
export async function applyShapeMoveOut({
|
|
292
|
-
pg,
|
|
293
|
-
metadataSchema,
|
|
294
|
-
shapeTable,
|
|
295
|
-
target,
|
|
296
|
-
patternSets,
|
|
297
|
-
debug,
|
|
298
|
-
sessionScoped = false,
|
|
299
|
-
}: MoveOutOptions): Promise<number> {
|
|
300
|
-
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
301
|
-
const db = drizzleOverPg(pg);
|
|
302
|
-
const evictedPkJsons = new Set<string>();
|
|
303
|
-
|
|
304
|
-
for (const patterns of patternSets) {
|
|
305
|
-
if (patterns.length === 0) continue;
|
|
306
|
-
|
|
307
|
-
// Candidate tags: those containing every pattern value as a substring — a cheap superset of a real
|
|
308
|
-
// positional match, confirmed in JS so composite/positional tags are handled correctly. Each
|
|
309
|
-
// `like(tag, "%value%")` reproduces the former `tag LIKE '%' || $n || '%'` exactly: a param bound to
|
|
310
|
-
// the concatenated pattern string, so any LIKE metacharacters in the value keep the same semantics.
|
|
311
|
-
const candidateRows = await db
|
|
312
|
-
.select({ pk_json: shapeRowTags.pk_json, tag: shapeRowTags.tag })
|
|
313
|
-
.from(shapeRowTags)
|
|
314
|
-
.where(
|
|
315
|
-
and(
|
|
316
|
-
eq(shapeRowTags.shape_table, shapeTable),
|
|
317
|
-
...patterns.map((pattern) => like(shapeRowTags.tag, `%${pattern.value}%`)),
|
|
318
|
-
),
|
|
319
|
-
);
|
|
320
|
-
const matched = candidateRows.filter((row) => tagMatchesPatterns(row.tag, patterns));
|
|
321
|
-
if (matched.length === 0) continue;
|
|
322
|
-
|
|
323
|
-
// Withdraw the moved-out tag from each matching row (one set-based delete of the (pk, tag) pairs).
|
|
324
|
-
// Tier ② (ADR-0028): a set-based delete joined against a JSON recordset has no tier-① builder form —
|
|
325
|
-
// the shape-tag table object is interpolated and the pair list is a bound `::json` param; the
|
|
326
|
-
// alias-qualified `t.*` / `x.*` identifiers are raw only because the `USING`/recordset-join grammar
|
|
327
|
-
// requires them.
|
|
328
|
-
const pairs = matched.map((row) => ({ pk_json: row.pk_json, tag: row.tag }));
|
|
329
|
-
await db.execute(
|
|
330
|
-
sql`DELETE FROM ${shapeRowTags} AS t USING json_to_recordset(${JSON.stringify(pairs)}::json) AS x(pk_json text, tag text)
|
|
331
|
-
WHERE t.shape_table = ${shapeTable} AND t.pk_json = x.pk_json AND t.tag = x.tag`,
|
|
332
|
-
);
|
|
333
|
-
|
|
334
|
-
// A row is evicted only if it has no tag left.
|
|
335
|
-
const affected = [...new Set(matched.map((row) => row.pk_json))];
|
|
336
|
-
// Tier ② (ADR-0028): bind the affected pk_json list as ONE array param via `= ANY(${param}::text[])`
|
|
337
|
-
// — drizzle has no ANY(array-param) builder, and `sql.param` binds the whole array as a single
|
|
338
|
-
// placeholder (removing the per-element bound-param ceiling `inArray` emits: one placeholder per PK,
|
|
339
|
-
// a ~65k-param wire cap on a huge move-out). The explicit `::text[]` cast pins the param type for the
|
|
340
|
-
// driver's extended-protocol type resolution. The `eq(shape_table)` conjunct and `selectDistinct`
|
|
341
|
-
// shape are preserved.
|
|
342
|
-
const remaining = await db
|
|
343
|
-
.selectDistinct({ pk_json: shapeRowTags.pk_json })
|
|
344
|
-
.from(shapeRowTags)
|
|
345
|
-
.where(
|
|
346
|
-
and(
|
|
347
|
-
eq(shapeRowTags.shape_table, shapeTable),
|
|
348
|
-
sql`${shapeRowTags.pk_json} = ANY(${sql.param(affected)}::text[])`,
|
|
349
|
-
),
|
|
350
|
-
);
|
|
351
|
-
const stillTagged = new Set(remaining.map((row) => row.pk_json));
|
|
352
|
-
for (const pkJson of affected) {
|
|
353
|
-
if (!stillTagged.has(pkJson)) evictedPkJsons.add(pkJson);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
if (evictedPkJsons.size === 0) return 0;
|
|
358
|
-
|
|
359
|
-
// Evict via the bulk-delete path so the reconcile trigger fires and the read model converges.
|
|
360
|
-
const messages = [...evictedPkJsons].map((pkJson) => ({
|
|
361
|
-
key: pkJson,
|
|
362
|
-
value: JSON.parse(pkJson) as Row<unknown>,
|
|
363
|
-
headers: { operation: "delete" as const },
|
|
364
|
-
}));
|
|
365
|
-
await applyBulkDeletesToTable({
|
|
366
|
-
pg,
|
|
367
|
-
target,
|
|
368
|
-
messages,
|
|
369
|
-
debug,
|
|
370
|
-
});
|
|
371
|
-
|
|
372
|
-
return evictedPkJsons.size;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
/** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
|
|
376
|
-
export async function clearShapeTags({
|
|
377
|
-
pg,
|
|
378
|
-
metadataSchema,
|
|
379
|
-
shapeTable,
|
|
380
|
-
sessionScoped = false,
|
|
381
|
-
}: {
|
|
382
|
-
pg: PGliteInterface | Transaction;
|
|
383
|
-
metadataSchema: string;
|
|
384
|
-
shapeTable: string;
|
|
385
|
-
/** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */
|
|
386
|
-
sessionScoped?: boolean;
|
|
387
|
-
}): Promise<void> {
|
|
388
|
-
const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
|
|
389
|
-
await drizzleOverPg(pg).delete(shapeRowTags).where(eq(shapeRowTags.shape_table, shapeTable));
|
|
390
|
-
}
|
package/src/sync-auth.ts
DELETED
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
|
|
2
|
-
|
|
3
|
-
/** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
|
|
4
|
-
type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
|
|
8
|
-
* write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
|
|
9
|
-
* freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
|
|
10
|
-
* expires.
|
|
11
|
-
*
|
|
12
|
-
* `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
|
|
13
|
-
* Electric resolves header-value functions on every request *and every retry*
|
|
14
|
-
* (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
|
|
15
|
-
* presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
|
|
16
|
-
*
|
|
17
|
-
* The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
|
|
18
|
-
* request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
|
|
19
|
-
* single-flight, so an N-shape consistency group does not trigger N refreshes.
|
|
20
|
-
*/
|
|
21
|
-
/**
|
|
22
|
-
* Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
|
|
23
|
-
* caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
|
|
24
|
-
* `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
|
|
25
|
-
* agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
|
|
26
|
-
* whenever *either* a token provider or static headers are present, so a credential-only consumer
|
|
27
|
-
* (no per-request token) still sends its headers.
|
|
28
|
-
*/
|
|
29
|
-
export function buildShapeHeaders(input: {
|
|
30
|
-
getAuthToken?: () => Promise<string | undefined>;
|
|
31
|
-
requestHeaders?: Record<string, string>;
|
|
32
|
-
}): ExternalHeadersRecord {
|
|
33
|
-
const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };
|
|
34
|
-
const getAuthToken = input.getAuthToken;
|
|
35
|
-
if (getAuthToken) {
|
|
36
|
-
// Resolved per request: a fresh token each time, never one captured at boot. An absent token
|
|
37
|
-
// yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.
|
|
38
|
-
headers["Authorization"] = async () => {
|
|
39
|
-
const token = await getAuthToken();
|
|
40
|
-
return token ? `Bearer ${token}` : "";
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
return headers;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
|
|
47
|
-
export function buildAuthShapeHeaders(
|
|
48
|
-
getAuthToken: () => Promise<string | undefined>,
|
|
49
|
-
requestHeaders?: Record<string, string>,
|
|
50
|
-
): ExternalHeadersRecord {
|
|
51
|
-
return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** HTTP statuses that mean "the credential is the problem" — re-auth, never give up (ADR-0013). */
|
|
55
|
-
const AUTH_ERROR_STATUSES = new Set([401, 403]);
|
|
56
|
-
|
|
57
|
-
/** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */
|
|
58
|
-
function readErrorStatus(error: unknown): number | undefined {
|
|
59
|
-
if (typeof error !== "object" || error === null || !("status" in error)) {
|
|
60
|
-
return undefined;
|
|
61
|
-
}
|
|
62
|
-
const status = (error as { status: unknown }).status;
|
|
63
|
-
return typeof status === "number" ? status : undefined;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read
|
|
68
|
-
* the documented `status` field rather than `instanceof FetchError`: the experimental and client
|
|
69
|
-
* packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one
|
|
70
|
-
* copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and
|
|
71
|
-
* carries no false positives — a plain network/`Error` has no numeric `status`.
|
|
72
|
-
*/
|
|
73
|
-
function isAuthError(error: unknown): boolean {
|
|
74
|
-
const status = readErrorStatus(error);
|
|
75
|
-
return status !== undefined && AUTH_ERROR_STATUSES.has(status);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,
|
|
80
|
-
* a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)
|
|
81
|
-
* is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)
|
|
82
|
-
*/
|
|
83
|
-
function isRetryableStreamError(error: unknown): boolean {
|
|
84
|
-
const status = readErrorStatus(error);
|
|
85
|
-
if (status === undefined) {
|
|
86
|
-
return true; // network/transport error — retry with Electric's backoff
|
|
87
|
-
}
|
|
88
|
-
return status >= 500 || status === 429;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
|
|
93
|
-
* request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
|
|
94
|
-
* read-path identity (ADR-0013) and read-stream error surfacing (#4):
|
|
95
|
-
*
|
|
96
|
-
* - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
|
|
97
|
-
* re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
|
|
98
|
-
* Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
|
|
99
|
-
* session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
|
|
100
|
-
* makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
|
|
101
|
-
* - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
|
|
102
|
-
* of silently believing the read path is live), then retry transient faults ({@link
|
|
103
|
-
* isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
|
|
104
|
-
* later successful fetch (`onSyncActivity`) clears the degraded status back to live.
|
|
105
|
-
*/
|
|
106
|
-
export function createShapeErrorHandler(
|
|
107
|
-
options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},
|
|
108
|
-
): ShapeStreamErrorHandler {
|
|
109
|
-
return (error: Error) => {
|
|
110
|
-
if (isAuthError(error)) {
|
|
111
|
-
options.onAuthError?.();
|
|
112
|
-
return {}; // retry → re-resolves the async Authorization header for a fresh token
|
|
113
|
-
}
|
|
114
|
-
options.onReadStreamError?.(error);
|
|
115
|
-
return isRetryableStreamError(error) ? {} : undefined;
|
|
116
|
-
};
|
|
117
|
-
}
|