@pgxsinkit/client 0.1.32 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +118 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +260 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +15 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1076 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { PGliteInterface } from "@electric-sql/pglite";
|
|
2
|
+
import { type ElectricSyncOptions, type SyncShapesToTablesOptions, type SyncShapesToTablesResult, type SyncShapeToTableOptions, type SyncShapeToTableResult } from "./types";
|
|
3
|
+
export * from "./types";
|
|
4
|
+
/**
|
|
5
|
+
* Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine
|
|
6
|
+
* is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it
|
|
7
|
+
* actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`
|
|
8
|
+
* / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the
|
|
9
|
+
* local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit
|
|
10
|
+
* `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked
|
|
11
|
+
* explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).
|
|
12
|
+
*/
|
|
13
|
+
export declare function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions): Promise<{
|
|
14
|
+
namespace: {
|
|
15
|
+
initMetadataTables: () => Promise<void>;
|
|
16
|
+
syncShapesToTables: ({ key, registry, shapes, initialInsertMethod, onInitialSync, onError, onSyncError, onSyncActivity, dbReady, maxCommitRetries, commitRetryDelayMs, }: SyncShapesToTablesOptions) => Promise<SyncShapesToTablesResult>;
|
|
17
|
+
syncShapeToTable: (options: SyncShapeToTableOptions) => Promise<SyncShapeToTableResult>;
|
|
18
|
+
deleteSubscription: (key: string) => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
close: () => Promise<void>;
|
|
21
|
+
}>;
|
|
22
|
+
/**
|
|
23
|
+
* The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,
|
|
24
|
+
* plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type
|
|
25
|
+
* follows the object.
|
|
26
|
+
*/
|
|
27
|
+
export type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;
|
|
28
|
+
export type SyncNamespaceObj = SyncEngine["namespace"];
|
|
29
|
+
export type PGliteWithSync = PGliteInterface & {
|
|
30
|
+
sync: SyncNamespaceObj;
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sync/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AA0C5D,OAAO,EAEL,KAAK,mBAAmB,EAIxB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC5B,MAAM,SAAS,CAAC;AAEjB,cAAc,SAAS,CAAC;AAgDxB;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,mBAAmB;;kCA+BxD,OAAO,CAAC,IAAI,CAAC;kLAyBzC,yBAAyB,KAAG,OAAO,CAAC,wBAAwB,CAAC;oCA2zBvB,uBAAuB,KAAG,OAAO,CAAC,sBAAsB,CAAC;kCAqC3D,MAAM;;;GA0B9C;AAED;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC,CAAC;AACtE,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAEvD,MAAM,MAAM,cAAc,GAAG,eAAe,GAAG;IAC7C,IAAI,EAAE,gBAAgB,CAAC;CACxB,CAAC"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { pgSchema } from "drizzle-orm/pg-core";
|
|
2
|
+
import type { ShapeSubscriptionState } from "./subscription-state";
|
|
3
|
+
/**
|
|
4
|
+
* The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The
|
|
5
|
+
* metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables
|
|
6
|
+
* are built per schema string and memoized.
|
|
7
|
+
*
|
|
8
|
+
* ADR-0029 D3: these pgTables are the SINGLE SOURCE for the relations. `migrateSubscriptionMetadataTables`
|
|
9
|
+
* (subscription-state.ts) renders their `CREATE TABLE`/`CREATE INDEX` DDL FROM these definitions via the
|
|
10
|
+
* in-house `renderCreateTableSql` (schema.ts), and the DML paths query them directly — so the DDL and the
|
|
11
|
+
* pgTable can no longer diverge, and the former drift guard in `tests/unit/sync-drizzle-executor.test.ts`
|
|
12
|
+
* is now a plain provisioning round-trip.
|
|
13
|
+
*
|
|
14
|
+
* Property keys are deliberately snake_case to mirror the row shapes the callers already consume
|
|
15
|
+
* (`shape_metadata`, `last_lsn`, `pk_json`, …), so a `select()` returns rows in the existing shape with
|
|
16
|
+
* no alias mapping.
|
|
17
|
+
*/
|
|
18
|
+
export interface MetadataTables {
|
|
19
|
+
/** `<schema>.subscriptions_metadata` — one row per subscription key. */
|
|
20
|
+
readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;
|
|
21
|
+
/** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */
|
|
22
|
+
readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;
|
|
23
|
+
}
|
|
24
|
+
declare function buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>): import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
25
|
+
name: "subscriptions_metadata";
|
|
26
|
+
schema: string;
|
|
27
|
+
columns: {
|
|
28
|
+
key: import("drizzle-orm/pg-core").PgBuildColumn<"subscriptions_metadata", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
29
|
+
name: string;
|
|
30
|
+
tableName: "subscriptions_metadata";
|
|
31
|
+
dataType: "string";
|
|
32
|
+
data: string;
|
|
33
|
+
driverParam: string;
|
|
34
|
+
notNull: true;
|
|
35
|
+
hasDefault: false;
|
|
36
|
+
isPrimaryKey: false;
|
|
37
|
+
isAutoincrement: false;
|
|
38
|
+
hasRuntimeDefault: false;
|
|
39
|
+
enumValues: undefined;
|
|
40
|
+
identity: undefined;
|
|
41
|
+
generated: undefined;
|
|
42
|
+
}>;
|
|
43
|
+
shape_metadata: import("drizzle-orm/pg-core").PgBuildColumn<"subscriptions_metadata", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").Set$Type<import("drizzle-orm/pg-core").PgJsonbBuilder, Record<string, ShapeSubscriptionState>>>, {
|
|
44
|
+
name: string;
|
|
45
|
+
tableName: "subscriptions_metadata";
|
|
46
|
+
dataType: "object json";
|
|
47
|
+
data: Record<string, ShapeSubscriptionState>;
|
|
48
|
+
driverParam: unknown;
|
|
49
|
+
notNull: true;
|
|
50
|
+
hasDefault: false;
|
|
51
|
+
isPrimaryKey: false;
|
|
52
|
+
isAutoincrement: false;
|
|
53
|
+
hasRuntimeDefault: false;
|
|
54
|
+
enumValues: undefined;
|
|
55
|
+
identity: undefined;
|
|
56
|
+
generated: undefined;
|
|
57
|
+
}>;
|
|
58
|
+
last_lsn: import("drizzle-orm/pg-core").PgBuildColumn<"subscriptions_metadata", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
59
|
+
name: string;
|
|
60
|
+
tableName: "subscriptions_metadata";
|
|
61
|
+
dataType: "string";
|
|
62
|
+
data: string;
|
|
63
|
+
driverParam: string;
|
|
64
|
+
notNull: true;
|
|
65
|
+
hasDefault: false;
|
|
66
|
+
isPrimaryKey: false;
|
|
67
|
+
isAutoincrement: false;
|
|
68
|
+
hasRuntimeDefault: false;
|
|
69
|
+
enumValues: undefined;
|
|
70
|
+
identity: undefined;
|
|
71
|
+
generated: undefined;
|
|
72
|
+
}>;
|
|
73
|
+
};
|
|
74
|
+
dialect: 'pg';
|
|
75
|
+
}>;
|
|
76
|
+
declare function buildShapeRowTags(schema: ReturnType<typeof pgSchema>): import("drizzle-orm/pg-core").PgTableWithColumns<{
|
|
77
|
+
name: "shape_row_tags";
|
|
78
|
+
schema: string;
|
|
79
|
+
columns: {
|
|
80
|
+
shape_table: import("drizzle-orm/pg-core").PgBuildColumn<"shape_row_tags", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
81
|
+
name: string;
|
|
82
|
+
tableName: "shape_row_tags";
|
|
83
|
+
dataType: "string";
|
|
84
|
+
data: string;
|
|
85
|
+
driverParam: string;
|
|
86
|
+
notNull: true;
|
|
87
|
+
hasDefault: false;
|
|
88
|
+
isPrimaryKey: false;
|
|
89
|
+
isAutoincrement: false;
|
|
90
|
+
hasRuntimeDefault: false;
|
|
91
|
+
enumValues: undefined;
|
|
92
|
+
identity: undefined;
|
|
93
|
+
generated: undefined;
|
|
94
|
+
}>;
|
|
95
|
+
pk_json: import("drizzle-orm/pg-core").PgBuildColumn<"shape_row_tags", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
96
|
+
name: string;
|
|
97
|
+
tableName: "shape_row_tags";
|
|
98
|
+
dataType: "string";
|
|
99
|
+
data: string;
|
|
100
|
+
driverParam: string;
|
|
101
|
+
notNull: true;
|
|
102
|
+
hasDefault: false;
|
|
103
|
+
isPrimaryKey: false;
|
|
104
|
+
isAutoincrement: false;
|
|
105
|
+
hasRuntimeDefault: false;
|
|
106
|
+
enumValues: undefined;
|
|
107
|
+
identity: undefined;
|
|
108
|
+
generated: undefined;
|
|
109
|
+
}>;
|
|
110
|
+
tag: import("drizzle-orm/pg-core").PgBuildColumn<"shape_row_tags", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
|
|
111
|
+
name: string;
|
|
112
|
+
tableName: "shape_row_tags";
|
|
113
|
+
dataType: "string";
|
|
114
|
+
data: string;
|
|
115
|
+
driverParam: string;
|
|
116
|
+
notNull: true;
|
|
117
|
+
hasDefault: false;
|
|
118
|
+
isPrimaryKey: false;
|
|
119
|
+
isAutoincrement: false;
|
|
120
|
+
hasRuntimeDefault: false;
|
|
121
|
+
enumValues: undefined;
|
|
122
|
+
identity: undefined;
|
|
123
|
+
generated: undefined;
|
|
124
|
+
}>;
|
|
125
|
+
};
|
|
126
|
+
dialect: 'pg';
|
|
127
|
+
}>;
|
|
128
|
+
/** The (memoized) metadata-store `pgTable`s for a given metadata schema name. */
|
|
129
|
+
export declare function getMetadataTables(metadataSchema: string): MetadataTables;
|
|
130
|
+
export {};
|
|
131
|
+
//# sourceMappingURL=metadata-tables.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metadata-tables.d.ts","sourceRoot":"","sources":["../../src/sync/metadata-tables.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAoB,MAAM,qBAAqB,CAAC;AAE/E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAEnE;;;;;;;;;;;;;;GAcG;AAEH,MAAM,WAAW,cAAc;IAC7B,wEAAwE;IACxE,QAAQ,CAAC,qBAAqB,EAAE,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAAC;IAC9E,mFAAmF;IACnF,QAAQ,CAAC,YAAY,EAAE,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC;CAC7D;AAED,iBAAS,0BAA0B,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAQtE;AAED,iBAAS,iBAAiB,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAa7D;AAID,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,cAAc,EAAE,MAAM,GAAG,cAAc,CAWxE"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How long a hold must PERSIST before the first nudge round fires. A cross-shape transaction's halves
|
|
3
|
+
* arrive milliseconds apart even on a healthy stack, so every grouped commit passes through a
|
|
4
|
+
* transient "held" instant — nudging on it immediately ABORTS the sibling's long-poll that was about
|
|
5
|
+
* to deliver the other half, turning a millisecond hold into an abort/refetch disruption loop
|
|
6
|
+
* (regression caught by the sync-e2e integration lane on local Electric). A hold that outlives this
|
|
7
|
+
* grace is the real thing: a quiet sibling parked in a multi-second poll. On Electric Cloud this adds
|
|
8
|
+
* ~1s to a path that saves ~40s; on local stacks it means the nudge simply never fires.
|
|
9
|
+
*/
|
|
10
|
+
export declare const NUDGE_HOLD_GRACE_MS = 1000;
|
|
11
|
+
/**
|
|
12
|
+
* Max nudge rounds before a dead / genuinely-still-polling sibling degrades back to the old behavior
|
|
13
|
+
* (wait out its live long-poll) instead of being nudged forever — so a stuck sibling never becomes a
|
|
14
|
+
* refresh storm.
|
|
15
|
+
*/
|
|
16
|
+
export declare const NUDGE_MAX_ROUNDS = 3;
|
|
17
|
+
/**
|
|
18
|
+
* Polling step while waiting for a nudge round's forced catch-ups to advance the group frontier. The
|
|
19
|
+
* `forceDisconnectAndRefresh()` promise settles BEFORE the refreshed catch-up response lands (field
|
|
20
|
+
* measurement: round 2 fired ~750ms into round 1's still-in-flight requests when the wait keyed off that
|
|
21
|
+
* promise alone), so the watchdog instead polls the frontier at this step, up to
|
|
22
|
+
* {@link NUDGE_ROUND_WAIT_MS} per round, breaking out the moment the target is reached.
|
|
23
|
+
*/
|
|
24
|
+
export declare const NUDGE_ROUND_GRACE_MS = 100;
|
|
25
|
+
/**
|
|
26
|
+
* Max wait per nudge round for the forced catch-ups to return and advance the frontier. A nudged
|
|
27
|
+
* catch-up measures ~0.9–1.4s through a warm deployed edge proxy but >3.5s against a cold one — and
|
|
28
|
+
* a next round's refresh ABORTS a still-in-flight round (the abort-and-reconnect is the mechanism),
|
|
29
|
+
* so an early re-nudge throws away an almost-done response. The wait therefore covers the cold-edge
|
|
30
|
+
* tail; worst case to exhaustion stays NUDGE_MAX_ROUNDS × this ≈ 12s, still far under a ~41s hold.
|
|
31
|
+
*/
|
|
32
|
+
export declare const NUDGE_ROUND_WAIT_MS = 4000;
|
|
33
|
+
/**
|
|
34
|
+
* Wrap a `fetchClient` so a pending one-shot nudge token defeats the CDN on the nudged sibling's catch-up.
|
|
35
|
+
*
|
|
36
|
+
* A nudge's `forceDisconnectAndRefresh` issues a NON-live catch-up (Electric sets `canLongPoll: false`),
|
|
37
|
+
* which is CDN-cacheable — a HIT would return the SAME stale watermark that made the sibling lag, defeating
|
|
38
|
+
* the nudge. So the watchdog drops a per-shape token into `nudgeBusters` just before it nudges; this wrapper
|
|
39
|
+
* consumes that token on the sibling's next NON-live request, appending `cache-buster=<token>` to force a
|
|
40
|
+
* CDN miss. It is one-shot (the token is deleted on use) and skips LIVE (`live=true`) long-polls — the token
|
|
41
|
+
* is meant for the catch-up that follows the aborted poll, not the poll itself, which is left to be retained
|
|
42
|
+
* for that catch-up. An already-present `cache-buster` param is overwritten. When no token is pending this is
|
|
43
|
+
* a straight passthrough, so the off-path pays only this closure.
|
|
44
|
+
*
|
|
45
|
+
* Exported for unit testing; composed in the engine as the OUTER wrapper around `instrumentShapeFetch`, so
|
|
46
|
+
* the buster stamps the URL BEFORE instrumentation logs it (the debug rail then shows `BUSTED`).
|
|
47
|
+
*/
|
|
48
|
+
export declare function withNudgeBuster(fetchClient: typeof fetch, nudgeBusters: Map<string, string>, shapeName: string): typeof fetch;
|
|
49
|
+
//# sourceMappingURL=nudge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nudge.d.ts","sourceRoot":"","sources":["../../src/sync/nudge.ts"],"names":[],"mappings":"AAeA;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,OAAQ,CAAC;AAEzC;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAExC;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,OAAQ,CAAC;AAYzC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,OAAO,KAAK,EACzB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EACjC,SAAS,EAAE,MAAM,GAChB,OAAO,KAAK,CA6Bd"}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
|
|
2
|
+
import type { InsertChangeMessage, Lsn } from "./types";
|
|
3
|
+
/**
|
|
4
|
+
* The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's
|
|
5
|
+
* Electric subscription and the Sync applier. It buffers each shape's change messages keyed by
|
|
6
|
+
* LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the
|
|
7
|
+
* applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014
|
|
8
|
+
* per-PK fold that will live here) property-testable against an ordered per-row apply oracle.
|
|
9
|
+
*
|
|
10
|
+
* One inbox owns all shapes in a consistency group; the group commits atomically at the lowest
|
|
11
|
+
* complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays
|
|
12
|
+
* with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).
|
|
13
|
+
*
|
|
14
|
+
* COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live
|
|
15
|
+
* here and they are deliberately NOT the same number:
|
|
16
|
+
*
|
|
17
|
+
* - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below
|
|
18
|
+
* it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor
|
|
19
|
+
* (below) but above its raw frontier is still buffered, never dropped.
|
|
20
|
+
* - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see
|
|
21
|
+
* {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in
|
|
22
|
+
* {@link lowestCompleteLsn}; it never gates ingestion.
|
|
23
|
+
*
|
|
24
|
+
* Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable
|
|
25
|
+
* (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its
|
|
26
|
+
* `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up
|
|
27
|
+
* can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the
|
|
28
|
+
* group min-frontier below changes already delivered on the busy shape, holding them buffered until the
|
|
29
|
+
* quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The
|
|
30
|
+
* alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at
|
|
31
|
+
* catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose
|
|
32
|
+
* cached catch-up omitted it is still ingested and committed rather than dropped.
|
|
33
|
+
*/
|
|
34
|
+
export declare class ShapeInbox {
|
|
35
|
+
private readonly changes;
|
|
36
|
+
private readonly completeLsns;
|
|
37
|
+
private readonly moveOuts;
|
|
38
|
+
private readonly moveIns;
|
|
39
|
+
private readonly epochs;
|
|
40
|
+
private readonly snapshotAccepted;
|
|
41
|
+
private readonly upToDateSeen;
|
|
42
|
+
private readonly lastUpToDateLsn;
|
|
43
|
+
private readonly commitFloors;
|
|
44
|
+
private aligned;
|
|
45
|
+
private lastAlignedFloor;
|
|
46
|
+
constructor(shapeNames: Iterable<string>);
|
|
47
|
+
/**
|
|
48
|
+
* Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from
|
|
49
|
+
* registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The
|
|
50
|
+
* commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver
|
|
51
|
+
* them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.
|
|
52
|
+
*/
|
|
53
|
+
acceptsSnapshotRowsFor(shapeName: string): boolean;
|
|
54
|
+
/** The complete-LSN frontier for one shape (the already-seen dedup threshold). */
|
|
55
|
+
completeLsnFor(shapeName: string): Lsn;
|
|
56
|
+
/**
|
|
57
|
+
* The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it
|
|
58
|
+
* back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so
|
|
59
|
+
* the reset's own truncate+rebuild path owns that shape's post-reset state.
|
|
60
|
+
*/
|
|
61
|
+
epochFor(shapeName: string): number;
|
|
62
|
+
/**
|
|
63
|
+
* Buffer a change message. A message at or below the shape's current complete frontier is
|
|
64
|
+
* already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.
|
|
65
|
+
*/
|
|
66
|
+
ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void;
|
|
67
|
+
/** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */
|
|
68
|
+
commitFloorFor(shapeName: string): Lsn;
|
|
69
|
+
/**
|
|
70
|
+
* A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —
|
|
71
|
+
* the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity
|
|
72
|
+
* {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),
|
|
73
|
+
* and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.
|
|
74
|
+
*/
|
|
75
|
+
effectiveLsnFor(shapeName: string): Lsn;
|
|
76
|
+
/**
|
|
77
|
+
* Whether this shape has reported `up-to-date` at least once since registration / its last
|
|
78
|
+
* {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:
|
|
79
|
+
* a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.
|
|
80
|
+
*/
|
|
81
|
+
hasReportedUpToDate(shapeName: string): boolean;
|
|
82
|
+
/** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */
|
|
83
|
+
alignedFloor(): Lsn;
|
|
84
|
+
/**
|
|
85
|
+
* Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the
|
|
86
|
+
* one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.
|
|
87
|
+
*
|
|
88
|
+
* Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on
|
|
89
|
+
* that transition); `false` on every other call.
|
|
90
|
+
*/
|
|
91
|
+
ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean;
|
|
92
|
+
/** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */
|
|
93
|
+
ingestMoveOut(shapeName: string, patterns: MovePattern[]): void;
|
|
94
|
+
/** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */
|
|
95
|
+
drainMoveOuts(shapeName: string): MovePattern[][];
|
|
96
|
+
/**
|
|
97
|
+
* Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs
|
|
98
|
+
* with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)
|
|
99
|
+
* only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the
|
|
100
|
+
* revocations buffered rather than silently losing them.
|
|
101
|
+
*/
|
|
102
|
+
peekMoveOuts(shapeName: string): MovePattern[][];
|
|
103
|
+
/**
|
|
104
|
+
* Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit
|
|
105
|
+
* that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the
|
|
106
|
+
* peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)
|
|
107
|
+
* buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a
|
|
108
|
+
* {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so
|
|
109
|
+
* this no-ops rather than splicing the post-reset replacement.
|
|
110
|
+
*/
|
|
111
|
+
ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void;
|
|
112
|
+
/** Whether any shape has a buffered `move-out` awaiting a commit. */
|
|
113
|
+
hasPendingMoveOuts(): boolean;
|
|
114
|
+
/** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */
|
|
115
|
+
ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void;
|
|
116
|
+
/** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */
|
|
117
|
+
drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
|
|
118
|
+
/** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */
|
|
119
|
+
peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[];
|
|
120
|
+
/**
|
|
121
|
+
* Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see
|
|
122
|
+
* {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a
|
|
123
|
+
* mid-commit {@link resetShape}), so the post-reset replacement rows survive.
|
|
124
|
+
*/
|
|
125
|
+
ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void;
|
|
126
|
+
/** Whether any shape has a buffered `move-in` awaiting a commit. */
|
|
127
|
+
hasPendingMoveIns(): boolean;
|
|
128
|
+
/** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */
|
|
129
|
+
resetShape(shapeName: string): void;
|
|
130
|
+
/**
|
|
131
|
+
* The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's
|
|
132
|
+
* effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup
|
|
133
|
+
* frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global
|
|
134
|
+
* head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy
|
|
135
|
+
* shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'
|
|
136
|
+
* first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw
|
|
137
|
+
* {@link completeLsns}), so a late sub-floor change is still ingested and then committed.
|
|
138
|
+
*/
|
|
139
|
+
lowestCompleteLsn(): Lsn;
|
|
140
|
+
/**
|
|
141
|
+
* Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit
|
|
142
|
+
* loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed
|
|
143
|
+
* target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change
|
|
144
|
+
* below the floor while the group frontier already sits at (or above) it, so no new frontier advance
|
|
145
|
+
* would otherwise trigger a commit for it.
|
|
146
|
+
*/
|
|
147
|
+
hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean;
|
|
148
|
+
/**
|
|
149
|
+
* Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN
|
|
150
|
+
* order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs
|
|
151
|
+
* with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks
|
|
152
|
+
* (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)
|
|
153
|
+
* holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.
|
|
154
|
+
*/
|
|
155
|
+
peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
|
|
156
|
+
/**
|
|
157
|
+
* Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a
|
|
158
|
+
* matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured
|
|
159
|
+
* at peek time; a shape whose epoch has since changed is **skipped entirely**.
|
|
160
|
+
*
|
|
161
|
+
* The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only
|
|
162
|
+
* advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit
|
|
163
|
+
* {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at
|
|
164
|
+
* LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop
|
|
165
|
+
* the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.
|
|
166
|
+
*/
|
|
167
|
+
ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void;
|
|
168
|
+
/** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */
|
|
169
|
+
snapshotEpochs(): Map<string, number>;
|
|
170
|
+
/**
|
|
171
|
+
* Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order
|
|
172
|
+
* ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty
|
|
173
|
+
* array where nothing drained).
|
|
174
|
+
*/
|
|
175
|
+
drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]>;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).
|
|
179
|
+
* Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a
|
|
180
|
+
* *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk
|
|
181
|
+
* apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs
|
|
182
|
+
* three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is
|
|
183
|
+
* what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest
|
|
184
|
+
* of the order is irrelevant within the atomic commit.
|
|
185
|
+
*/
|
|
186
|
+
export interface FoldedShapeBatch {
|
|
187
|
+
/** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */
|
|
188
|
+
deletes: ChangeMessage<Row<unknown>>[];
|
|
189
|
+
/** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */
|
|
190
|
+
inserts: InsertChangeMessage[];
|
|
191
|
+
/** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */
|
|
192
|
+
updates: ChangeMessage<Row<unknown>>[];
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key
|
|
196
|
+
* (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …
|
|
197
|
+
* SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when
|
|
198
|
+
* the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:
|
|
199
|
+
*
|
|
200
|
+
* - **trailing `delete`** ⇒ a single DELETE;
|
|
201
|
+
* - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
|
|
202
|
+
* (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);
|
|
203
|
+
* - **only `update`s** ⇒ a single UPDATE with merged values;
|
|
204
|
+
* - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
|
|
205
|
+
* pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
|
|
206
|
+
* would collide with the row the dropped delete was meant to remove);
|
|
207
|
+
* - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream
|
|
208
|
+
* (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently
|
|
209
|
+
* dropping it.
|
|
210
|
+
*
|
|
211
|
+
* Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle
|
|
212
|
+
* *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.
|
|
213
|
+
*/
|
|
214
|
+
export declare function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch;
|
|
215
|
+
//# sourceMappingURL=shape-inbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shape-inbox.d.ts","sourceRoot":"","sources":["../../src/sync/shape-inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,SAAS,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GAAG,OAAO,CASnD;IAED;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAgBnE;IAED;;;;;;;;;;OAUG;IACH,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAY/D;IAED,sGAAsG;IACtG,cAAc,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAEpC;IAED;;;;OAIG;IACH,SAAS,CAAC,SAAS,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAKpE;CACF;AAID;;;;;;;;GAQG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;IACvC,mGAAmG;IACnG,OAAO,EAAE,mBAAmB,EAAE,CAAC;IAC/B,mGAAmG;IACnG,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;CACxC;AAgBD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAgBzF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Offset } from "@electric-sql/client";
|
|
2
|
+
import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
|
|
3
|
+
import { type Lsn, type SubscriptionKey } from "./types";
|
|
4
|
+
export interface SubscriptionState {
|
|
5
|
+
key: SubscriptionKey;
|
|
6
|
+
shape_metadata: Record<string, ShapeSubscriptionState>;
|
|
7
|
+
last_lsn: Lsn;
|
|
8
|
+
}
|
|
9
|
+
export interface ShapeSubscriptionState {
|
|
10
|
+
handle: string;
|
|
11
|
+
offset: Offset;
|
|
12
|
+
}
|
|
13
|
+
export interface GetSubscriptionStateOptions {
|
|
14
|
+
readonly pg: PGliteInterface | Transaction;
|
|
15
|
+
readonly metadataSchema: string;
|
|
16
|
+
readonly subscriptionKey: SubscriptionKey;
|
|
17
|
+
}
|
|
18
|
+
export declare function getSubscriptionState({ pg, metadataSchema, subscriptionKey, }: GetSubscriptionStateOptions): Promise<SubscriptionState | null>;
|
|
19
|
+
export interface UpdateSubscriptionStateOptions {
|
|
20
|
+
pg: PGliteInterface | Transaction;
|
|
21
|
+
metadataSchema: string;
|
|
22
|
+
subscriptionKey: SubscriptionKey;
|
|
23
|
+
shapeMetadata: Record<string, ShapeSubscriptionState>;
|
|
24
|
+
lastLsn: Lsn;
|
|
25
|
+
debug?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export declare function updateSubscriptionState({ pg, metadataSchema, subscriptionKey, shapeMetadata, lastLsn, debug, }: UpdateSubscriptionStateOptions): Promise<void>;
|
|
28
|
+
export interface DeleteSubscriptionStateOptions {
|
|
29
|
+
pg: PGliteInterface | Transaction;
|
|
30
|
+
metadataSchema: string;
|
|
31
|
+
subscriptionKey: SubscriptionKey;
|
|
32
|
+
}
|
|
33
|
+
export declare function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }: DeleteSubscriptionStateOptions): Promise<void>;
|
|
34
|
+
export interface MigrateSubscriptionMetadataTablesOptions {
|
|
35
|
+
pg: PGliteInterface | Transaction;
|
|
36
|
+
metadataSchema: string;
|
|
37
|
+
}
|
|
38
|
+
export declare function migrateSubscriptionMetadataTables({ pg, metadataSchema, }: MigrateSubscriptionMetadataTablesOptions): Promise<void>;
|
|
39
|
+
//# sourceMappingURL=subscription-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subscription-state.d.ts","sourceRoot":"","sources":["../../src/sync/subscription-state.ts"],"names":[],"mapp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AAM,CAAC;IACvB,eAAe,EAAE,eAAe,CAAC;CAClC;AAED,wBAAsB,uBAAuB,CAAC,EAAE,EAAE,EAAE,cAAc,EAAE,eAAe,EAAE,EAAE,8BAA8B,iBAGpH;AAED,MAAM,WAAW,wCAAwC;IACvD,EAAE,EAAE,eAAe,GAAG,WAAW,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,wBAAsB,iCAAiC,CAAC,EACtD,EAAE,EACF,cAAc,GACf,EAAE,wCAAwC,iBAc1C"}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
|
|
2
|
+
import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
|
|
3
|
+
import type { ApplyTarget } from "../local-tables";
|
|
4
|
+
/**
|
|
5
|
+
* Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
|
|
6
|
+
* (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)
|
|
7
|
+
* streams two extra things the plain change path ignores:
|
|
8
|
+
*
|
|
9
|
+
* - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per
|
|
10
|
+
* grant/membership), plus `removed_tags` on an update;
|
|
11
|
+
* - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — "the tag whose component at
|
|
12
|
+
* index `pos` equals `value` is withdrawn", i.e. that grant was revoked.
|
|
13
|
+
*
|
|
14
|
+
* A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`
|
|
15
|
+
* today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one
|
|
16
|
+
* metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an
|
|
17
|
+
* Electric change.
|
|
18
|
+
*
|
|
19
|
+
* Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:
|
|
20
|
+
* `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.
|
|
24
|
+
* The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so
|
|
25
|
+
* the desync path (which is outside the engine) can key the tag store by this same constant.
|
|
26
|
+
*/
|
|
27
|
+
export declare const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
|
|
28
|
+
/**
|
|
29
|
+
* Validate the metadata schema name at engine construction. The name is interpolated RAW into two
|
|
30
|
+
* positions a double-quoted identifier cannot cover:
|
|
31
|
+
* - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
|
|
32
|
+
* (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
|
|
33
|
+
* accept a quoted identifier the way a table/column position does, so the name cannot be safely
|
|
34
|
+
* quoted there.
|
|
35
|
+
* - the `CREATE SCHEMA <schema>` DDL identifier position.
|
|
36
|
+
* Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
|
|
37
|
+
* lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
|
|
38
|
+
*/
|
|
39
|
+
export declare function assertValidMetadataSchema(metadataSchema: string): void;
|
|
40
|
+
/**
|
|
41
|
+
* The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config
|
|
42
|
+
* (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by
|
|
43
|
+
* `migrateSubscriptionMetadataTables`, which renders that same pgTable.
|
|
44
|
+
*/
|
|
45
|
+
export declare function shapeRowTagsTableName(metadataSchema: string): string;
|
|
46
|
+
/** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
|
|
47
|
+
export declare function shapeTableId(schema: string | undefined, table: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
|
|
50
|
+
* does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
|
|
51
|
+
* caller/test that builds the local schema without booting the sync engine that creates the store). The
|
|
52
|
+
* engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
|
|
53
|
+
* guarded.
|
|
54
|
+
*/
|
|
55
|
+
export declare function buildClearShapeTagsSql(shapeTable: string, metadataSchema?: string): string;
|
|
56
|
+
/**
|
|
57
|
+
* Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
|
|
58
|
+
* value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
|
|
59
|
+
* rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
|
|
60
|
+
*/
|
|
61
|
+
export declare function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string;
|
|
62
|
+
/**
|
|
63
|
+
* Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
|
|
64
|
+
* is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
|
|
65
|
+
* two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
|
|
66
|
+
* `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
|
|
67
|
+
*
|
|
68
|
+
* (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
|
|
69
|
+
* ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
|
|
70
|
+
*/
|
|
71
|
+
export declare function splitTagComponents(tag: string): string[];
|
|
72
|
+
/**
|
|
73
|
+
* Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
|
|
74
|
+
* of the shape's tag structure (one position per subquery condition that references it), so the event
|
|
75
|
+
* enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
|
|
76
|
+
* is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
|
|
77
|
+
* empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
|
|
78
|
+
* matches nothing.
|
|
79
|
+
*/
|
|
80
|
+
export declare function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean;
|
|
81
|
+
interface TagSyncOptions {
|
|
82
|
+
pg: PGliteInterface | Transaction;
|
|
83
|
+
metadataSchema: string;
|
|
84
|
+
shapeTable: string;
|
|
85
|
+
messages: ChangeMessage<Row<unknown>>[];
|
|
86
|
+
primaryKey: string[];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
|
|
90
|
+
* change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
|
|
91
|
+
* row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
|
|
92
|
+
* shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
|
|
93
|
+
* eviction in the same commit, so an add-then-remove within one batch resolves correctly.
|
|
94
|
+
*/
|
|
95
|
+
export declare function applyShapeTagSync({ pg, metadataSchema, shapeTable, messages, primaryKey, }: TagSyncOptions): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
|
|
98
|
+
* A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
|
|
99
|
+
* authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
|
|
100
|
+
* not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
|
|
101
|
+
* Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
|
|
102
|
+
* eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
|
|
103
|
+
* A row with no `tags` (a non-subquery shape) is a no-op.
|
|
104
|
+
*/
|
|
105
|
+
export declare function addShapeRowTags({ pg, metadataSchema, shapeTable, messages, primaryKey, }: TagSyncOptions): Promise<void>;
|
|
106
|
+
interface MoveOutOptions {
|
|
107
|
+
pg: PGliteInterface | Transaction;
|
|
108
|
+
metadataSchema: string;
|
|
109
|
+
shapeTable: string;
|
|
110
|
+
/** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
|
|
111
|
+
target: ApplyTarget;
|
|
112
|
+
/** One entry per buffered `move-out` event, each its own pattern set. */
|
|
113
|
+
patternSets: MovePattern[][];
|
|
114
|
+
debug: boolean;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
|
|
118
|
+
* carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
|
|
119
|
+
* survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
|
|
120
|
+
* trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
|
|
121
|
+
*/
|
|
122
|
+
export declare function applyShapeMoveOut({ pg, metadataSchema, shapeTable, target, patternSets, debug, }: MoveOutOptions): Promise<number>;
|
|
123
|
+
/** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
|
|
124
|
+
export declare function clearShapeTags({ pg, metadataSchema, shapeTable, }: {
|
|
125
|
+
pg: PGliteInterface | Transaction;
|
|
126
|
+
metadataSchema: string;
|
|
127
|
+
shapeTable: string;
|
|
128
|
+
}): Promise<void>;
|
|
129
|
+
export {};
|
|
130
|
+
//# sourceMappingURL=tags.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/sync/tags.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAMzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAKnD;;;;;;;;;;;;;;;;;GAiBG;AAEH;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,cAAc,CAAC;AAQnD;;;;;;;;;;GAUG;AACH,wBA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