@pgxsinkit/client 0.2.7 → 0.5.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/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +11 -3
- package/dist/boot-report.d.ts +11 -8
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +39 -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 +96 -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/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +237 -113
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7037 -6665
- package/dist/index.js.map +46 -43
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +59 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +17 -25
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +84 -8
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- 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 +26 -7
- 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.d.ts +1 -1
- package/dist/testing.js +4 -3
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +27 -14
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +52 -19
- 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/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -9
- package/skills/core/SKILL.md +145 -63
- package/skills/operating/SKILL.md +221 -221
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +13 -12
- package/src/circuits/envelope-to-change.ts +211 -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 +191 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +643 -0
- package/src/debug.ts +1 -85
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +24 -28
- package/src/export-store.ts +17 -17
- package/src/index.ts +797 -544
- package/src/lazy-guard.ts +1 -1
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +76 -5
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +126 -29
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +56 -40
- package/src/sync/apply.ts +104 -156
- package/src/sync/copy.ts +116 -21
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +43 -2
- package/src/sync/subscription-state.ts +28 -10
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +4 -4
- package/src/worker/attach-sync-client.ts +150 -57
- package/src/worker/define-sync-worker.ts +325 -87
- package/src/worker/engine-control.ts +89 -0
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +10 -10
- package/src/worker/protocol.ts +38 -7
- 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
|
@@ -1,33 +1,32 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { drizzle, type
|
|
1
|
+
import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
|
|
2
|
+
import { drizzle, type PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* A Drizzle handle whose executor is an already-open
|
|
5
|
+
* A Drizzle handle whose executor is an already-open pgwasm connection *or* an open pgwasm
|
|
6
6
|
* `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML
|
|
7
7
|
* (ADR-0028 decision 4).
|
|
8
8
|
*
|
|
9
|
-
* The blocker the old convertibility report cited was "`drizzle-orm/pglite` wraps only a
|
|
9
|
+
* The blocker the old convertibility report cited was "`drizzle-orm/pglite` wraps only a pgwasm
|
|
10
10
|
* instance, not a Transaction". That is a *type* boundary, not a runtime one: drizzle's pglite session
|
|
11
11
|
* layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified
|
|
12
12
|
* against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the
|
|
13
13
|
* only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).
|
|
14
|
-
*
|
|
14
|
+
* pgwasm's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle
|
|
15
15
|
* built over a `Transaction` executes every statement **on that transaction** — participating in the
|
|
16
16
|
* engine's commit boundary rather than opening its own.
|
|
17
17
|
*
|
|
18
|
-
* The cast to `
|
|
18
|
+
* The cast to `pgwasm` is the narrowest honest one: at runtime the session only calls `.query`, which
|
|
19
19
|
* both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the
|
|
20
20
|
* expected single-expression cast for this seam.
|
|
21
21
|
*
|
|
22
22
|
* CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction
|
|
23
23
|
* boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync
|
|
24
|
-
* index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full
|
|
24
|
+
* index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full pgwasm,
|
|
25
25
|
* which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose
|
|
26
26
|
* or use it.
|
|
27
27
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.
|
|
28
|
+
* pgwasm.s driver takes the database as its first argument; a `Transaction` carries the `query` the
|
|
29
|
+
* session needs, hence the cast.
|
|
31
30
|
*/
|
|
32
31
|
|
|
33
32
|
// One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`
|
|
@@ -35,13 +34,13 @@ import { drizzle, type PgliteDatabase } from "drizzle-orm/pglite";
|
|
|
35
34
|
// commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while
|
|
36
35
|
// never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the
|
|
37
36
|
// WeakMap drops it once the commit's closure is collected).
|
|
38
|
-
const handles = new WeakMap<
|
|
37
|
+
const handles = new WeakMap<Pgwasm | Transaction, PgwasmDatabase<never>>();
|
|
39
38
|
|
|
40
|
-
/** A (memoized) Drizzle handle over an open
|
|
41
|
-
export function drizzleOverPg(pg:
|
|
39
|
+
/** A (memoized) Drizzle handle over an open pgwasm connection or transaction — engine-internal. */
|
|
40
|
+
export function drizzleOverPg(pg: Pgwasm | Transaction): PgwasmDatabase<never> {
|
|
42
41
|
let db = handles.get(pg);
|
|
43
42
|
if (!db) {
|
|
44
|
-
db = drizzle(
|
|
43
|
+
db = drizzle(pg as unknown as Pgwasm) as PgwasmDatabase<never>;
|
|
45
44
|
handles.set(pg, db);
|
|
46
45
|
}
|
|
47
46
|
return db;
|
package/src/sync/fold.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { SyncChange, SyncRow } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
import type { UpsertChangeMessage } from "./types";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
|
|
7
|
+
* Each PK appears in at most one of `deletes`/`upserts` — except a *re-created* PK
|
|
8
|
+
* (`[delete, … , upsert]`), which appears in both so the pre-existing row is cleared before the new
|
|
9
|
+
* one lands. The Sync applier therefore runs two bulk statements **in the order `deletes → upserts`**:
|
|
10
|
+
* that ordering is what makes a re-create drop local-only column state instead of inheriting it, and
|
|
11
|
+
* every other PK is touched by exactly one statement.
|
|
12
|
+
*/
|
|
13
|
+
export interface FoldedShapeBatch {
|
|
14
|
+
/** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
|
|
15
|
+
deletes: SyncChange[];
|
|
16
|
+
/** Full rows to upsert — net-`upsert` keys, plus each re-created key's new row. */
|
|
17
|
+
upserts: UpsertChangeMessage[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Clone a representative message, overriding its row value (headers like LSN are kept). */
|
|
21
|
+
function withValue(template: SyncChange, value: SyncRow): UpsertChangeMessage {
|
|
22
|
+
return { ...template, value, headers: { ...template.headers, operation: "upsert" } };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Collapse an ordered run of upserts to its net row.
|
|
27
|
+
*
|
|
28
|
+
* Every engine upsert carries the complete projected row, so this degenerates to "the last one
|
|
29
|
+
* wins" — the merge is kept rather than a bare `at(-1)` because it stays correct if a future engine
|
|
30
|
+
* ever narrows an upsert to its changed columns, and costs nothing at this batch size.
|
|
31
|
+
*/
|
|
32
|
+
function mergeValues(segment: SyncChange[]): SyncRow {
|
|
33
|
+
return Object.assign({}, ...segment.map((message) => message.value)) as SyncRow;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
|
|
38
|
+
* (ADR-0014 decision 1), so the read path can bulk-apply without the `INSERT … SELECT
|
|
39
|
+
* json_to_recordset(…)` same-PK join hazard (which uses **one arbitrary** matching row when the
|
|
40
|
+
* source holds duplicate PKs). Each PK's ops are replayed in stream order down to:
|
|
41
|
+
*
|
|
42
|
+
* - **trailing `delete`** ⇒ a single DELETE;
|
|
43
|
+
* - **upserts, no preceding delete** ⇒ a single UPSERT of the net row;
|
|
44
|
+
* - **re-created** (`[delete, … , upsert, …]`, no trailing delete) ⇒ DELETE **and** UPSERT.
|
|
45
|
+
*
|
|
46
|
+
* The clearing DELETE on a re-create is not redundant against an upsert. `ON CONFLICT DO UPDATE`
|
|
47
|
+
* refreshes only the columns the shape projects; a row that genuinely left and re-entered must not
|
|
48
|
+
* keep local-only column values from its previous life, so it is removed first.
|
|
49
|
+
*
|
|
50
|
+
* There is no `updates` bucket and no malformed-batch case, because there is no third verb: the
|
|
51
|
+
* engine emits `upsert | delete` and nothing else ({@link SyncOperation}). The old
|
|
52
|
+
* "update after delete ⇒ throw" guard checked for a stream state the vocabulary can no longer
|
|
53
|
+
* express.
|
|
54
|
+
*
|
|
55
|
+
* Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
|
|
56
|
+
* *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
|
|
57
|
+
*/
|
|
58
|
+
export function foldChangeBatch(messages: SyncChange[]): FoldedShapeBatch {
|
|
59
|
+
const groups = new Map<string, SyncChange[]>();
|
|
60
|
+
for (const message of messages) {
|
|
61
|
+
let group = groups.get(message.key);
|
|
62
|
+
if (!group) {
|
|
63
|
+
group = [];
|
|
64
|
+
groups.set(message.key, group);
|
|
65
|
+
}
|
|
66
|
+
group.push(message);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const folded: FoldedShapeBatch = { deletes: [], upserts: [] };
|
|
70
|
+
for (const ops of groups.values()) {
|
|
71
|
+
foldKey(ops, folded);
|
|
72
|
+
}
|
|
73
|
+
return folded;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function foldKey(ops: SyncChange[], folded: FoldedShapeBatch): void {
|
|
77
|
+
const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === "delete");
|
|
78
|
+
|
|
79
|
+
// A trailing delete is the net effect regardless of anything before it; emit one DELETE.
|
|
80
|
+
if (lastDeleteIndex === ops.length - 1) {
|
|
81
|
+
folded.deletes.push(ops[lastDeleteIndex]!);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The net is decided by the segment after the last delete (or the whole sequence if none), which
|
|
86
|
+
// is all upserts — a delete would have been the last delete.
|
|
87
|
+
const segment = ops.slice(lastDeleteIndex + 1);
|
|
88
|
+
|
|
89
|
+
if (lastDeleteIndex >= 0) {
|
|
90
|
+
// Re-created: clear the pre-existing row, then land the new one (DELETE before UPSERT).
|
|
91
|
+
folded.deletes.push(ops[lastDeleteIndex]!);
|
|
92
|
+
}
|
|
93
|
+
folded.upserts.push(withValue(segment[segment.length - 1]!, mergeValues(segment)));
|
|
94
|
+
}
|
|
@@ -2,6 +2,43 @@ import { index, jsonb, pgSchema, primaryKey, text } from "drizzle-orm/pg-core";
|
|
|
2
2
|
|
|
3
3
|
import type { ShapeSubscriptionState } from "./subscription-state";
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* The pgxsinkit-owned metadata schema (ADR-0009 decision 6) — where the subscription cursor and the
|
|
7
|
+
* sync-origin GUC live. Ours, not the sync substrate's, which is why it is not named after one.
|
|
8
|
+
*
|
|
9
|
+
* The sync engine defaults its `metadataSchema` to this and `createSyncClient` never overrides it, so
|
|
10
|
+
* paths outside the engine can address the same relations by this constant.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A bare, lowercase, unqualified SQL identifier: begins with a lowercase letter or underscore, then
|
|
16
|
+
* lowercase letters, digits, and underscores.
|
|
17
|
+
*/
|
|
18
|
+
const METADATA_SCHEMA_PATTERN = /^[a-z_][a-z0-9_]*$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Validate the metadata schema name at engine construction. The name is interpolated RAW into two
|
|
22
|
+
* positions a double-quoted identifier cannot cover:
|
|
23
|
+
* - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
|
|
24
|
+
* (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
|
|
25
|
+
* accept a quoted identifier the way a table/column position does, so the name cannot be safely
|
|
26
|
+
* quoted there.
|
|
27
|
+
* - the `CREATE SCHEMA <schema>` DDL identifier position.
|
|
28
|
+
* Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
|
|
29
|
+
* lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
|
|
30
|
+
*/
|
|
31
|
+
export function assertValidMetadataSchema(metadataSchema: string): void {
|
|
32
|
+
if (!METADATA_SCHEMA_PATTERN.test(metadataSchema)) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`Invalid metadataSchema ${JSON.stringify(metadataSchema)}: it must be a bare lowercase SQL ` +
|
|
35
|
+
`identifier matching ${String(METADATA_SCHEMA_PATTERN)}. The name is interpolated unquoted into ` +
|
|
36
|
+
`GUC (\`SET <schema>.syncing\`) and \`CREATE SCHEMA\` identifier positions where a quoted ` +
|
|
37
|
+
`identifier is not accepted, so uppercase and exotic names are rejected at construction.`,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
5
42
|
/**
|
|
6
43
|
* The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The
|
|
7
44
|
* metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables
|
|
@@ -21,7 +58,11 @@ import type { ShapeSubscriptionState } from "./subscription-state";
|
|
|
21
58
|
export interface MetadataTables {
|
|
22
59
|
/** `<schema>.subscriptions_metadata` — one row per subscription key. */
|
|
23
60
|
readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;
|
|
24
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023), whose mechanism
|
|
63
|
+
* ADR-0057 retired. Still provisioned by `migrateSubscriptionMetadataTables`; nothing reads or
|
|
64
|
+
* writes it on the native path.
|
|
65
|
+
*/
|
|
25
66
|
readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;
|
|
26
67
|
}
|
|
27
68
|
|
|
@@ -30,7 +71,7 @@ export interface MetadataTables {
|
|
|
30
71
|
* group's sync bookkeeping (cursor + tags) is scoped to the engine session by placing it in `pg_temp`
|
|
31
72
|
* relations that die with the engine — the cursor's lifetime is mechanically tied to the TEMP cluster
|
|
32
73
|
* whose rows it indexes. `pg_temp` is a per-session alias Postgres accepts in DML qualification (probed
|
|
33
|
-
* on real
|
|
74
|
+
* on real pgwasm), so the DML paths select these objects unchanged. Same relation NAMES as the durable
|
|
34
75
|
* variants, distinguished by schema alone (maintainer ruling).
|
|
35
76
|
*/
|
|
36
77
|
const SESSION_METADATA_SCHEMA = "pg_temp";
|
|
@@ -1,10 +1,9 @@
|
|
|
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
1
|
import { eq } from "drizzle-orm";
|
|
6
2
|
|
|
7
|
-
import { quoteIdentifier } from "@pgxsinkit/contracts";
|
|
3
|
+
import { quoteIdentifier, type PredicateValue } from "@pgxsinkit/contracts";
|
|
4
|
+
// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
|
|
5
|
+
// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
|
|
6
|
+
import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
|
|
8
7
|
|
|
9
8
|
import { renderCreateTableSql } from "../schema";
|
|
10
9
|
import { drizzleOverPg } from "./drizzle-executor";
|
|
@@ -19,11 +18,30 @@ export interface SubscriptionState {
|
|
|
19
18
|
|
|
20
19
|
export interface ShapeSubscriptionState {
|
|
21
20
|
handle: string;
|
|
22
|
-
|
|
21
|
+
/** Opaque, per-stream, lexicographically ordered. Never compared across streams. */
|
|
22
|
+
offset: string;
|
|
23
|
+
/**
|
|
24
|
+
* The registry shape this entry is a reader of.
|
|
25
|
+
*
|
|
26
|
+
* Persisted so a later subscribe can say what a stored entry WAS, not merely that it exists. The
|
|
27
|
+
* map key is a logical shape name the client mints (shape key plus scope), which is enough to match
|
|
28
|
+
* an entry against a fresh grant but carries no way back to the registry — and the reconcile at
|
|
29
|
+
* subscribe (ADR-0055 decision 6) needs exactly that: a scope the control plane no longer grants has
|
|
30
|
+
* to be resolved to its spec before its rows can be cleared.
|
|
31
|
+
*/
|
|
32
|
+
shapeKey: string;
|
|
33
|
+
/**
|
|
34
|
+
* Shared tier only: the scope values this reader's grant named, in the shape's declared column
|
|
35
|
+
* order. Absent for the private tier, whose subject arrives in the claims instead.
|
|
36
|
+
*
|
|
37
|
+
* `readonly` because a persisted tuple is a record of what was granted, never something to edit —
|
|
38
|
+
* which also lets a grant's own `readonly PredicateValue[]` be stored without a defensive copy.
|
|
39
|
+
*/
|
|
40
|
+
scope?: readonly PredicateValue[];
|
|
23
41
|
}
|
|
24
42
|
|
|
25
43
|
export interface GetSubscriptionStateOptions {
|
|
26
|
-
readonly pg:
|
|
44
|
+
readonly pg: Pgwasm | Transaction;
|
|
27
45
|
readonly metadataSchema: string;
|
|
28
46
|
readonly subscriptionKey: SubscriptionKey;
|
|
29
47
|
/**
|
|
@@ -75,7 +93,7 @@ export async function getSubscriptionState({
|
|
|
75
93
|
}
|
|
76
94
|
|
|
77
95
|
export interface UpdateSubscriptionStateOptions {
|
|
78
|
-
pg:
|
|
96
|
+
pg: Pgwasm | Transaction;
|
|
79
97
|
metadataSchema: string;
|
|
80
98
|
subscriptionKey: SubscriptionKey;
|
|
81
99
|
shapeMetadata: Record<string, ShapeSubscriptionState>;
|
|
@@ -110,7 +128,7 @@ export async function updateSubscriptionState({
|
|
|
110
128
|
}
|
|
111
129
|
|
|
112
130
|
export interface DeleteSubscriptionStateOptions {
|
|
113
|
-
pg:
|
|
131
|
+
pg: Pgwasm | Transaction;
|
|
114
132
|
metadataSchema: string;
|
|
115
133
|
subscriptionKey: SubscriptionKey;
|
|
116
134
|
}
|
|
@@ -128,7 +146,7 @@ export async function deleteSubscriptionState({ pg, metadataSchema, subscription
|
|
|
128
146
|
}
|
|
129
147
|
|
|
130
148
|
export interface MigrateSubscriptionMetadataTablesOptions {
|
|
131
|
-
pg:
|
|
149
|
+
pg: Pgwasm | Transaction;
|
|
132
150
|
metadataSchema: string;
|
|
133
151
|
}
|
|
134
152
|
|
package/src/sync/types.ts
CHANGED
|
@@ -1,153 +1,25 @@
|
|
|
1
1
|
// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
|
|
2
2
|
// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
//
|
|
4
|
+
// What remains here is only what the NATIVE path uses. The shape-stream option and message types this
|
|
5
|
+
// file used to re-export were `@electric-sql/client`'s, and nothing reads them any more: the transport
|
|
6
|
+
// is `@durable-streams/client` and the change contract is `@pgxsinkit/contracts`' `SyncChange`.
|
|
5
7
|
|
|
6
|
-
import type {
|
|
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";
|
|
8
|
+
import type { SyncChange } from "@pgxsinkit/contracts";
|
|
15
9
|
|
|
16
10
|
export type Lsn = bigint;
|
|
17
11
|
|
|
18
12
|
export type SubscriptionKey = string;
|
|
19
13
|
export type InitialInsertMethod = "insert" | "copy" | "json";
|
|
20
14
|
|
|
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
15
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
16
|
+
* A change the fold has established is the net UPSERT of a complete row.
|
|
17
|
+
*
|
|
18
|
+
* The narrowing is what the bulk paths rely on: `value` carries every projected column, so the rows
|
|
19
|
+
* can go out as one multi-row statement (or a COPY) with no per-row branch on which columns are
|
|
20
|
+
* present. Guaranteed by the engine, not merely hoped for — `row_to_json_cols` emits every column of
|
|
21
|
+
* the shape's `out_cols` on every upsert.
|
|
29
22
|
*/
|
|
30
|
-
export
|
|
31
|
-
|
|
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
|
-
/**
|
|
55
|
-
* ADR-0042: this group's sync bookkeeping (subscription cursor + tagged-subquery reason sets) is
|
|
56
|
-
* SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
|
|
57
|
-
* durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
|
|
58
|
-
* and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
|
|
59
|
-
* instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — a
|
|
60
|
-
* persistent group's storage is identical whether the bit is `false` or unset; it only scopes an
|
|
61
|
-
* ephemeral group's bookkeeping. One storage-scope bit; the engine never learns the retention model.
|
|
62
|
-
*/
|
|
63
|
-
sessionScoped?: boolean | undefined;
|
|
64
|
-
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
65
|
-
onInitialSync?: (() => void) | undefined;
|
|
66
|
-
/**
|
|
67
|
-
* Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003). When present, the group is on a
|
|
68
|
-
* PROVABLY-FRESH store (a claimed schemaless spare — the caller's `freshStore` hint), so the engine
|
|
69
|
-
* starts the shape streams and BUFFERS their catch-up into the memory inbox immediately — WITHOUT the
|
|
70
|
-
* two DB touches the sequential path takes first (`initMetadataTables`, `getSubscriptionState`) — and
|
|
71
|
-
* gates every commit (the first write to PGlite) until this promise resolves. The owner resolves it
|
|
72
|
-
* once the local store is ready (schema exec + journal recovery + store-version reconcile complete), so
|
|
73
|
-
* the network catch-up overlaps those local phases instead of running strictly after them. Absent → the
|
|
74
|
-
* exact sequential path (warm stores, and every non-overlap caller). Because a fresh store has no prior
|
|
75
|
-
* subscription state, the overlap treats the group as a new subscription (`subState === null`), which the
|
|
76
|
-
* `freshStore` gate guarantees.
|
|
77
|
-
*/
|
|
78
|
-
dbReady?: Promise<void> | undefined;
|
|
79
|
-
/** Stream-level (network / fetch) error from Electric, forwarded to `MultiShapeStream.subscribe`. */
|
|
80
|
-
onError?: ((error: FetchError | Error) => void) | undefined;
|
|
81
|
-
/**
|
|
82
|
-
* Commit-level error surfacing (ADR-0009 decision 5). Fired when a sync commit transaction
|
|
83
|
-
* still fails after `maxCommitRetries` jittered-backoff attempts. The engine then holds its
|
|
84
|
-
* buffer and committed frontier (never advancing `isUpToDate` on an unapplied commit) so the
|
|
85
|
-
* read cache cannot silently diverge; recovery is a later commit or a restart/refetch.
|
|
86
|
-
*/
|
|
87
|
-
onSyncError?: ((error: Error) => void) | undefined;
|
|
88
|
-
/**
|
|
89
|
-
* Fired whenever the stream delivers a batch — i.e. a fetch just succeeded (ADR-0013 Phase 3).
|
|
90
|
-
* The runtime uses this as the read path's "alive again" signal to clear an `auth-needed` status
|
|
91
|
-
* once sync resumes after re-authentication.
|
|
92
|
-
*/
|
|
93
|
-
onSyncActivity?: (() => void) | undefined;
|
|
94
|
-
/** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
|
|
95
|
-
maxCommitRetries?: number | undefined;
|
|
96
|
-
/**
|
|
97
|
-
* Backoff before re-attempting a failed commit, as a function of the attempt number. Defaults to
|
|
98
|
-
* the runtime's jittered backoff (`computeRetryDelayMs`). A test seam — pass `() => 0` for an
|
|
99
|
-
* immediate retry instead of sleeping the real backoff.
|
|
100
|
-
*/
|
|
101
|
-
commitRetryDelayMs?: ((attempt: number) => number) | undefined;
|
|
102
|
-
/**
|
|
103
|
-
* Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
|
|
104
|
-
* batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
|
|
105
|
-
* (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
|
|
106
|
-
* boot without report instrumentation.
|
|
107
|
-
*/
|
|
108
|
-
bootStamp?: GroupBootStamp | undefined;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export interface SyncShapesToTablesResult {
|
|
112
|
-
unsubscribe: () => void;
|
|
113
|
-
readonly isUpToDate: boolean;
|
|
114
|
-
streams: Record<string, ShapeStreamInterface<Row<unknown>>>;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Single-shape options (ADR-0029 D6): thin sugar over the group form, taking the same entry-based
|
|
119
|
-
* fields plus a `shapeKey`. Every table-scoped fact is derived from `(registry, tableKey)`.
|
|
120
|
-
*/
|
|
121
|
-
export interface SyncShapeToTableOptions {
|
|
122
|
-
shape: ShapeStreamOptions<Row<unknown>>;
|
|
123
|
-
registry: SyncTableRegistry;
|
|
124
|
-
tableKey: string;
|
|
125
|
-
shapeKey: string | null;
|
|
126
|
-
/** ADR-0042: SESSION-scope this shape's cursor + tags (ephemeral retention); see {@link SyncShapesToTablesOptions.sessionScoped}. */
|
|
127
|
-
sessionScoped?: boolean | undefined;
|
|
128
|
-
initialInsertMethod?: InitialInsertMethod | undefined;
|
|
129
|
-
onInitialSync?: (() => void) | undefined;
|
|
130
|
-
onError?: ((error: FetchError | Error) => void) | undefined;
|
|
131
|
-
/** Commit-level error surfacing (ADR-0009 decision 5); see {@link SyncShapesToTablesOptions.onSyncError}. */
|
|
132
|
-
onSyncError?: ((error: Error) => void) | undefined;
|
|
133
|
-
/** Hard cap on commit-transaction attempts before going degraded. Defaults to {@link DEFAULT_MAX_COMMIT_RETRIES}. */
|
|
134
|
-
maxCommitRetries?: number | undefined;
|
|
135
|
-
/** Backoff before re-attempting a failed commit; see {@link SyncShapesToTablesOptions.commitRetryDelayMs}. */
|
|
136
|
-
commitRetryDelayMs?: ((attempt: number) => number) | undefined;
|
|
137
|
-
onMustRefetch?: ((db: PgliteDatabase) => Promise<void>) | undefined;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export interface SyncShapeToTableResult {
|
|
141
|
-
unsubscribe: () => void;
|
|
142
|
-
readonly isUpToDate: boolean;
|
|
143
|
-
stream: ShapeStreamInterface<Row<unknown>>;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
export interface ElectricSyncOptions {
|
|
147
|
-
debug?: boolean;
|
|
148
|
-
metadataSchema?: string;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export type InsertChangeMessage = ChangeMessage<Row<unknown>> & {
|
|
152
|
-
headers: { operation: "insert" };
|
|
23
|
+
export type UpsertChangeMessage = SyncChange & {
|
|
24
|
+
headers: { operation: "upsert" };
|
|
153
25
|
};
|
package/src/testing.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).
|
|
2
2
|
//
|
|
3
3
|
// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a
|
|
4
|
-
// memory store: `createSyncClient`/`
|
|
4
|
+
// memory store: `createSyncClient`/`createPgwasmClient` take a plain `storePath` whose backend is derived
|
|
5
5
|
// (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory
|
|
6
6
|
// stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export
|
|
7
7
|
// machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so
|
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
// The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
|
|
12
12
|
// marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
|
|
13
13
|
//
|
|
14
|
-
// createSyncClient({ ...memoryStoreForTests("my-test"), registry,
|
|
15
|
-
// createSyncClient({ ...testStoreAcknowledgment(),
|
|
14
|
+
// createSyncClient({ ...memoryStoreForTests("my-test"), registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
|
|
15
|
+
// createSyncClient({ ...testStoreAcknowledgment(), pgwasmInstance, registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl })
|
|
16
16
|
|
|
17
17
|
import { TEST_STORE_BACKEND } from "./store-path";
|
|
18
18
|
|
|
@@ -42,7 +42,7 @@ export function memoryStoreForTests(storePath: string): MemoryStoreForTests {
|
|
|
42
42
|
/**
|
|
43
43
|
* Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
|
|
44
44
|
* (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
|
|
45
|
-
*
|
|
45
|
+
* pgwasm via `pgwasmInstance` / `precreatedPgwasm`. Spread it alongside that option.
|
|
46
46
|
*
|
|
47
47
|
* Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
|
|
48
48
|
* store voids the retention + journal durability guarantees.
|