@pgxsinkit/contracts 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/dist/apply-strategy.d.ts +13 -1
- package/dist/apply-strategy.d.ts.map +1 -1
- package/dist/config.d.ts +256 -87
- package/dist/config.d.ts.map +1 -1
- package/dist/convergence-model.d.ts +2 -2
- package/dist/convergence-model.d.ts.map +1 -1
- package/dist/event-stream.d.ts +1 -1
- package/dist/fingerprint.d.ts +31 -11
- package/dist/fingerprint.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +480 -202
- package/dist/index.js.map +16 -14
- package/dist/predicate.d.ts +162 -0
- package/dist/predicate.d.ts.map +1 -0
- package/dist/projection.d.ts +2 -2
- package/dist/projection.d.ts.map +1 -1
- package/dist/registry-diff.d.ts.map +1 -1
- package/dist/registry-invariant.d.ts +26 -14
- package/dist/registry-invariant.d.ts.map +1 -1
- package/dist/registry.d.ts +74 -48
- package/dist/registry.d.ts.map +1 -1
- package/dist/sql-role-guard.d.ts +1 -1
- package/dist/stream-envelope.d.ts +84 -0
- package/dist/stream-envelope.d.ts.map +1 -0
- package/dist/supabase-rls.d.ts +32 -36
- package/dist/supabase-rls.d.ts.map +1 -1
- package/package.json +3 -2
- package/skills/registry-authoring/SKILL.md +185 -185
- package/skills/registry-authoring/references/storage-engine-and-build.md +29 -0
- package/src/apply-strategy.ts +23 -4
- package/src/config.ts +340 -116
- package/src/convergence-model.ts +2 -2
- package/src/event-stream.ts +1 -1
- package/src/fingerprint.ts +76 -14
- package/src/index.ts +2 -0
- package/src/predicate.ts +274 -0
- package/src/projection.ts +6 -2
- package/src/registry-diff.ts +15 -4
- package/src/registry-invariant.ts +34 -19
- package/src/registry.ts +324 -78
- package/src/sql-role-guard.ts +1 -1
- package/src/stream-envelope.ts +91 -0
- package/src/supabase-rls.ts +76 -74
package/src/config.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { PgDialect } from "drizzle-orm/pg-core";
|
|
1
|
+
import type { AnyColumn } from "drizzle-orm";
|
|
3
2
|
import { z } from "zod";
|
|
4
3
|
|
|
5
|
-
|
|
4
|
+
import { p, type Predicate } from "./predicate";
|
|
6
5
|
|
|
7
6
|
export type TableMode = "readonly" | "writeonly" | "readwrite";
|
|
8
7
|
|
|
@@ -33,7 +32,7 @@ export function isConflictPolicy(value: unknown): value is ConflictPolicy {
|
|
|
33
32
|
}
|
|
34
33
|
|
|
35
34
|
/**
|
|
36
|
-
* Subscription timing for a synced table (ADR-0021): **when** its
|
|
35
|
+
* Subscription timing for a synced table (ADR-0021): **when** its read-path shape subscribes.
|
|
37
36
|
*
|
|
38
37
|
* - `eager` (default) — subscribed in the boot set, as today.
|
|
39
38
|
* - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,
|
|
@@ -41,7 +40,8 @@ export function isConflictPolicy(value: unknown): value is ConflictPolicy {
|
|
|
41
40
|
* sessions; with `ephemeral` retention it is session-scoped.
|
|
42
41
|
*
|
|
43
42
|
* A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since
|
|
44
|
-
* a group
|
|
43
|
+
* a group's streams commit atomically together — all up-to-date, then one transaction (ADR-0056) — so
|
|
44
|
+
* it cannot be partly lazy (ADR-0021 §4).
|
|
45
45
|
*/
|
|
46
46
|
export type SubscriptionTiming = "eager" | "lazy";
|
|
47
47
|
|
|
@@ -56,7 +56,7 @@ export function isSubscriptionTiming(value: unknown): value is SubscriptionTimin
|
|
|
56
56
|
/**
|
|
57
57
|
* Retention for a synced table (ADR-0021): **whether** its local copy is durable.
|
|
58
58
|
*
|
|
59
|
-
* - `persistent` (default) — the durable
|
|
59
|
+
* - `persistent` (default) — the durable pgwasm backend with a resumable subscription-state.
|
|
60
60
|
* - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,
|
|
61
61
|
* views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable
|
|
62
62
|
* trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic
|
|
@@ -137,6 +137,71 @@ export function isStorageDurability(value: unknown): value is StorageDurability
|
|
|
137
137
|
return typeof value === "string" && (STORAGE_DURABILITIES as readonly string[]).includes(value);
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
+
/**
|
|
141
|
+
* The registry-declared store BUILD (ADR-0063): which pgwasm engine build owns the store's data directory.
|
|
142
|
+
* `c` (default) is the C PostgreSQL build; `pgrust` is the Rust one. Like the engine module, it is part of
|
|
143
|
+
* the store's identity — a datadir belongs to the build that wrote it, so a different build is a DIFFERENT
|
|
144
|
+
* store, minted fresh under a fresh path, never a rehome of an existing one.
|
|
145
|
+
*
|
|
146
|
+
* The declaration only NAMES the build. The build itself is always supplied as code at the minting site,
|
|
147
|
+
* never loaded from this string.
|
|
148
|
+
*/
|
|
149
|
+
export type StorageBuild = "c" | "pgrust";
|
|
150
|
+
|
|
151
|
+
/** The {@link StorageBuild} values. Source of truth for {@link SyncStorageDeclaration} validation. */
|
|
152
|
+
export const STORAGE_BUILDS = ["c", "pgrust"] as const satisfies readonly StorageBuild[];
|
|
153
|
+
|
|
154
|
+
/** Type guard: is `value` a {@link StorageBuild}? */
|
|
155
|
+
export function isStorageBuild(value: unknown): value is StorageBuild {
|
|
156
|
+
return typeof value === "string" && (STORAGE_BUILDS as readonly string[]).includes(value);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The declared store ENGINE (ADR-0050 addendum 2026-09-08): the module URL of a store factory that answers
|
|
161
|
+
* for the store instead of the toolkit's own `createPgwasmClient`.
|
|
162
|
+
*
|
|
163
|
+
* `module` is an **absolute or origin-relative module URL** the engine home can `import()`. Its default
|
|
164
|
+
* export — or a named `createStore` — is the toolkit's own `createStore` seam (ADR-0036), unchanged:
|
|
165
|
+
* `(storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>`. The module owns everything
|
|
166
|
+
* this declaration does not carry: its own assets (derivable from `import.meta.url`; there is no asset
|
|
167
|
+
* base and there will not be one), its own storage layout under the store path, and its own environment
|
|
168
|
+
* requirements (a threaded engine that needs a cross-origin-isolated page refuses to construct without
|
|
169
|
+
* one, loudly, from inside the module).
|
|
170
|
+
*
|
|
171
|
+
* Nothing in the toolkit knows, names or imports any particular engine — this field is the whole surface.
|
|
172
|
+
*/
|
|
173
|
+
export interface StorageEngineDeclaration {
|
|
174
|
+
module: string;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Type guard: is `value` a usable {@link StorageEngineDeclaration.module} — a non-blank string that parses
|
|
179
|
+
* as an ABSOLUTE URL (`https://…/factory.js`) or an ORIGIN-RELATIVE one (`/store-engine/factory.js`)?
|
|
180
|
+
*
|
|
181
|
+
* A document-relative specifier (`./factory.js`, `factory.js`) is deliberately rejected: the declaration
|
|
182
|
+
* crosses a bridge into a worker scope whose base URL is the worker chunk's, not the tab's, so a relative
|
|
183
|
+
* URL would resolve differently on either side of the wire. Source of truth for
|
|
184
|
+
* {@link SyncStorageDeclaration} validation.
|
|
185
|
+
*/
|
|
186
|
+
export function isStorageEngineModule(value: unknown): value is string {
|
|
187
|
+
if (typeof value !== "string" || value.trim() === "") return false;
|
|
188
|
+
try {
|
|
189
|
+
// The base is only consulted for the origin-relative form; an absolute URL ignores it entirely.
|
|
190
|
+
const url = new URL(value, "https://storage-engine.invalid/");
|
|
191
|
+
return value.startsWith("/") || url.href === new URL(value).href;
|
|
192
|
+
} catch {
|
|
193
|
+
// Not parseable as either form — a hand-typed specifier gone wrong, refused rather than guessed at.
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Type guard: is `value` a well-formed {@link StorageEngineDeclaration}? */
|
|
199
|
+
export function isStorageEngineDeclaration(value: unknown): value is StorageEngineDeclaration {
|
|
200
|
+
return (
|
|
201
|
+
typeof value === "object" && value !== null && isStorageEngineModule((value as StorageEngineDeclaration).module)
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
140
205
|
/**
|
|
141
206
|
* The registry's storage contract (ADR-0049 decision 1, ADR-0047). Storage is PART OF THE DATA CONTRACT:
|
|
142
207
|
* whether losing the last not-yet-flushed action is acceptable, and whether OPFS may be used at all, is
|
|
@@ -147,20 +212,34 @@ export function isStorageDurability(value: unknown): value is StorageDurability
|
|
|
147
212
|
* to contradict it; a capability fallback keeps the declared mode. A no-op on `memory` clones.
|
|
148
213
|
* - {@link StorageBackend backend} defaults to `"opfs"` and scopes the BROWSER store only; Node/`file` and
|
|
149
214
|
* `memory` clones are unaffected. `"idbfs"` opts the store out of the capability/election machinery.
|
|
215
|
+
* - {@link StorageBuild build} defaults to `"c"` and names the pgwasm build that owns the store's datadir
|
|
216
|
+
* (ADR-0063). It resolves and binds exactly as `durability` does.
|
|
217
|
+
* - {@link StorageEngineDeclaration engine} defaults to ABSENT — the toolkit's own store. Present, its
|
|
218
|
+
* `module` URL is the store factory that mints this store instead (ADR-0050 addendum 2026-09-08). It is
|
|
219
|
+
* part of the declaration for the same reason the other two are: a store's datadir belongs to the engine
|
|
220
|
+
* that wrote it, so a different `module` is a DIFFERENT store, minted fresh under a fresh path, never a
|
|
221
|
+
* rehome of an existing one.
|
|
150
222
|
*/
|
|
151
223
|
export interface SyncStorageDeclaration {
|
|
152
224
|
backend?: StorageBackend;
|
|
153
225
|
durability?: StorageDurability;
|
|
226
|
+
build?: StorageBuild;
|
|
227
|
+
engine?: StorageEngineDeclaration;
|
|
154
228
|
}
|
|
155
229
|
|
|
156
230
|
/**
|
|
157
231
|
* A {@link SyncStorageDeclaration} with every field resolved (ADR-0050) — the store's BOUND declaration.
|
|
158
232
|
* Produced once per store by {@link resolveStorageDeclaration} and immutable for the store's lifetime: a
|
|
159
233
|
* preference change mints a fresh store under a fresh path, never rebinds an existing one.
|
|
234
|
+
*
|
|
235
|
+
* `engine` is the one field that stays OPTIONAL after resolution, because the toolkit's own store has no
|
|
236
|
+
* module URL to name: absent IS the resolved value of "the built-in engine".
|
|
160
237
|
*/
|
|
161
238
|
export interface ResolvedStorageDeclaration {
|
|
162
239
|
backend: StorageBackend;
|
|
163
240
|
durability: StorageDurability;
|
|
241
|
+
build: StorageBuild;
|
|
242
|
+
engine?: StorageEngineDeclaration;
|
|
164
243
|
}
|
|
165
244
|
|
|
166
245
|
/**
|
|
@@ -176,6 +255,45 @@ export class StorageDeclarationRefusedError extends Error {
|
|
|
176
255
|
}
|
|
177
256
|
}
|
|
178
257
|
|
|
258
|
+
/**
|
|
259
|
+
* Where a store's Postgres build was checked against its declaration (ADR-0063): before a mint by the
|
|
260
|
+
* build a site supplies (`createSyncClient`, `defineSyncWorker`, `createPgwasmClient`), or on an instance a
|
|
261
|
+
* site adopts (`pgwasmInstance`, `precreatedPgwasm`, the result of a worker's `createStore`).
|
|
262
|
+
*/
|
|
263
|
+
export type StoreBuildCheckSite =
|
|
264
|
+
| "createSyncClient"
|
|
265
|
+
| "defineSyncWorker"
|
|
266
|
+
| "createPgwasmClient"
|
|
267
|
+
| "pgwasmInstance"
|
|
268
|
+
| "precreatedPgwasm"
|
|
269
|
+
| "createStore";
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The registry declares one Postgres build (`storage.build`, ADR-0063) and the code supplied or adopted
|
|
273
|
+
* another. Thrown before any store is touched. A store's build is code, never a declared string: pass the
|
|
274
|
+
* declared build (e.g. `defineSyncWorker({ build })`, `createSyncClient({ build })`), or fix the declaration.
|
|
275
|
+
* The stable `name` survives bridge serialization (`BridgeErrorWire.name`), and `detail` carries the three
|
|
276
|
+
* fields across it, so a tab can detect the refusal typed.
|
|
277
|
+
*/
|
|
278
|
+
export class StorageBuildMismatchError extends Error {
|
|
279
|
+
readonly declared: StorageBuild;
|
|
280
|
+
readonly supplied: string;
|
|
281
|
+
readonly site: StoreBuildCheckSite;
|
|
282
|
+
readonly detail: { readonly declared: StorageBuild; readonly supplied: string; readonly site: StoreBuildCheckSite };
|
|
283
|
+
|
|
284
|
+
constructor(declared: StorageBuild, supplied: string, site: StoreBuildCheckSite) {
|
|
285
|
+
super(
|
|
286
|
+
`storage build mismatch at ${site}: the registry declares the "${declared}" Postgres build but the ` +
|
|
287
|
+
`store's build is "${supplied}" — supply the declared build (a \`build\` option), or fix \`storage.build\``,
|
|
288
|
+
);
|
|
289
|
+
this.name = "StorageBuildMismatchError";
|
|
290
|
+
this.declared = declared;
|
|
291
|
+
this.supplied = supplied;
|
|
292
|
+
this.site = site;
|
|
293
|
+
this.detail = { declared, supplied, site };
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
179
297
|
/** One field's resolution: explicit-vs-explicit disagreement refuses; otherwise the explicit value, else the default. */
|
|
180
298
|
function resolveDeclarationField<TValue>(
|
|
181
299
|
field: keyof SyncStorageDeclaration,
|
|
@@ -199,12 +317,21 @@ function resolveDeclarationField<TValue>(
|
|
|
199
317
|
* declaration (authoritative) and the tab's WIRE declaration (honoured only where the registry is silent).
|
|
200
318
|
* Per field: an unset field is "no opinion" and can never conflict; both explicit and disagreeing is a
|
|
201
319
|
* {@link StorageDeclarationRefusedError}; unresolved fields take the capability defaults
|
|
202
|
-
* (`backend: "opfs"`, `durability: "relaxed"`).
|
|
320
|
+
* (`backend: "opfs"`, `durability: "relaxed"`, `build: "c"`, and NO engine module — the toolkit's own store).
|
|
321
|
+
*
|
|
322
|
+
* The `engine` field resolves on its `module` URL, which is the identity that matters: two declarations
|
|
323
|
+
* naming the same module are the same engine, and a disagreement refuses exactly as the other fields do.
|
|
203
324
|
*/
|
|
204
325
|
export function resolveStorageDeclaration(
|
|
205
326
|
staticDeclaration: SyncStorageDeclaration | undefined,
|
|
206
327
|
wireDeclaration: SyncStorageDeclaration | undefined,
|
|
207
328
|
): ResolvedStorageDeclaration {
|
|
329
|
+
const engineModule = resolveDeclarationField<string | undefined>(
|
|
330
|
+
"engine",
|
|
331
|
+
staticDeclaration?.engine?.module,
|
|
332
|
+
wireDeclaration?.engine?.module,
|
|
333
|
+
undefined,
|
|
334
|
+
);
|
|
208
335
|
return {
|
|
209
336
|
backend: resolveDeclarationField("backend", staticDeclaration?.backend, wireDeclaration?.backend, "opfs"),
|
|
210
337
|
durability: resolveDeclarationField(
|
|
@@ -213,6 +340,8 @@ export function resolveStorageDeclaration(
|
|
|
213
340
|
wireDeclaration?.durability,
|
|
214
341
|
"relaxed",
|
|
215
342
|
),
|
|
343
|
+
build: resolveDeclarationField("build", staticDeclaration?.build, wireDeclaration?.build, "c"),
|
|
344
|
+
...(engineModule === undefined ? {} : { engine: { module: engineModule } }),
|
|
216
345
|
};
|
|
217
346
|
}
|
|
218
347
|
|
|
@@ -220,13 +349,18 @@ export function resolveStorageDeclaration(
|
|
|
220
349
|
* Check a LATER declaration against a store's bound resolution (ADR-0050): an unset or equal field is
|
|
221
350
|
* idempotent; an explicit field disagreeing with the bound value is a {@link StorageDeclarationRefusedError}.
|
|
222
351
|
* The bound declaration is immutable — first arrival binds, later arrivals only confirm.
|
|
352
|
+
*
|
|
353
|
+
* `engine` is checked on its `module` URL, and only when the incoming declaration names one: an incoming
|
|
354
|
+
* declaration with NO engine is "no opinion" exactly like an unset `backend`, never an assertion that the
|
|
355
|
+
* store is on the built-in engine. (Absence is how the built-in engine is spelled, so it cannot double as
|
|
356
|
+
* an explicit contradiction; a consumer switching back mints a fresh store rather than redeclaring one.)
|
|
223
357
|
*/
|
|
224
358
|
export function assertStorageDeclarationCompatible(
|
|
225
359
|
bound: ResolvedStorageDeclaration,
|
|
226
360
|
incoming: SyncStorageDeclaration | undefined,
|
|
227
361
|
): void {
|
|
228
362
|
if (incoming === undefined) return;
|
|
229
|
-
for (const field of ["backend", "durability"] as const) {
|
|
363
|
+
for (const field of ["backend", "durability", "build"] as const) {
|
|
230
364
|
const value = incoming[field];
|
|
231
365
|
if (value !== undefined && value !== bound[field]) {
|
|
232
366
|
throw new StorageDeclarationRefusedError(
|
|
@@ -236,6 +370,15 @@ export function assertStorageDeclarationCompatible(
|
|
|
236
370
|
);
|
|
237
371
|
}
|
|
238
372
|
}
|
|
373
|
+
const incomingEngine = incoming.engine?.module;
|
|
374
|
+
if (incomingEngine !== undefined && incomingEngine !== bound.engine?.module) {
|
|
375
|
+
throw new StorageDeclarationRefusedError(
|
|
376
|
+
`storage declaration disagreement on "engine": the store is bound to ` +
|
|
377
|
+
`${bound.engine === undefined ? "the built-in store engine" : `"${bound.engine.module}"`} but a later ` +
|
|
378
|
+
`declaration says "${incomingEngine}" — a store's declaration is immutable; a store's datadir belongs ` +
|
|
379
|
+
`to the engine that wrote it, so an engine change mints a fresh store under a fresh path`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
239
382
|
}
|
|
240
383
|
|
|
241
384
|
/**
|
|
@@ -265,24 +408,109 @@ export interface ShapeSpec {
|
|
|
265
408
|
/**
|
|
266
409
|
* INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the
|
|
267
410
|
* shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's
|
|
268
|
-
* name so several shapes can read one physical table under distinct `shapeKey`s; the
|
|
269
|
-
* an incoming
|
|
270
|
-
* `table`
|
|
411
|
+
* name so several shapes can read one physical table under distinct `shapeKey`s; the control plane
|
|
412
|
+
* resolves an incoming subscription by `shapeKey` and consults this only when it creates the shape, as
|
|
413
|
+
* the source `table` it hands the engine. `attachSyncRegistrySchema` also fills/qualifies it for
|
|
414
|
+
* schema-bound registries.
|
|
271
415
|
*
|
|
272
416
|
* Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or
|
|
273
417
|
* wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The
|
|
274
418
|
* combinator derives it from the owner; `defineSyncTable` never sets it from input.
|
|
275
419
|
*/
|
|
276
|
-
|
|
420
|
+
physicalTable?: string;
|
|
277
421
|
rowFilter?: RowFilterSpec;
|
|
422
|
+
/**
|
|
423
|
+
* SHARED TIER (ADR-0055) — the scope columns, resolved to column names, whose values key this
|
|
424
|
+
* shape family. The predicate is *generated* as an `AND` of equalities over them, so disjointness
|
|
425
|
+
* is a property of the construction rather than something a checker has to enforce: a row carries
|
|
426
|
+
* exactly one value per scope column, so it falls in exactly one shape of the family, and an
|
|
427
|
+
* overlapping pair is not expressible at all.
|
|
428
|
+
*
|
|
429
|
+
* `NULL` is a legal scope value and compiles to `IS NULL` — which is how an offering-wide row gets
|
|
430
|
+
* its own scope `(O, null)` rather than appearing in every group's shape. The tempting
|
|
431
|
+
* `group_id IS NULL OR group_id = $G` form is not merely disallowed here; it is wrong, because it
|
|
432
|
+
* places one row in every group shape at once.
|
|
433
|
+
*
|
|
434
|
+
* Its presence is what makes this a shared-tier shape. Declaring it alongside `rowFilter` is
|
|
435
|
+
* refused at definition time — see {@link readShapeTier}.
|
|
436
|
+
*/
|
|
437
|
+
scope?: readonly string[];
|
|
438
|
+
/**
|
|
439
|
+
* The **static** half of the shape's predicate: subscriber-independent, identical for every
|
|
440
|
+
* reader, and therefore safe in either tier. On the shared tier it is conjoined with the generated
|
|
441
|
+
* scope equalities; on the private tier, with whatever `rowFilter` resolves to for the subject.
|
|
442
|
+
*
|
|
443
|
+
* Native AST, not SQL text — see {@link Predicate}.
|
|
444
|
+
*/
|
|
445
|
+
where?: Predicate;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Which read tier a shape belongs to (ADR-0055 decision 2). */
|
|
449
|
+
export type ShapeTier = "shared" | "private";
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The tier a shape declares, or a refusal.
|
|
453
|
+
*
|
|
454
|
+
* The tier is not configured; it is *read off* which field the author declared — `scope` for shared,
|
|
455
|
+
* `rowFilter` for private. That makes a shape's tier evident from its authoring and impossible to
|
|
456
|
+
* leave ambiguous, which matters because the two differ in whether their bytes are user-independent,
|
|
457
|
+
* and so in whether they may be shared and cached at all.
|
|
458
|
+
*
|
|
459
|
+
* Declaring both is refused rather than resolved by precedence. A `rowFilter` fuses the subject into
|
|
460
|
+
* the predicate, which is exactly what makes a stream unshareable; silently letting it ride along on
|
|
461
|
+
* a shape declared as shared would produce a stream that is cached under a scope key while carrying
|
|
462
|
+
* subject-dependent bytes — a disclosure, not a stale row.
|
|
463
|
+
*/
|
|
464
|
+
export function readShapeTier(shape: ShapeSpec): ShapeTier {
|
|
465
|
+
if (shape.scope != null && shape.rowFilter != null) {
|
|
466
|
+
throw new Error(
|
|
467
|
+
`[pgxsinkit] shape "${shape.shapeKey}" declares both scope and rowFilter — a shape is shared ` +
|
|
468
|
+
`(scope: the predicate is a function of scope values only) or private (rowFilter: the subject ` +
|
|
469
|
+
`is fused into the predicate), never both. A rowFilter makes the stream's bytes ` +
|
|
470
|
+
`subject-dependent, so it cannot be served from a scope-keyed shared stream. Move the ` +
|
|
471
|
+
`subject-dependent part into the entitlement rule, or drop scope and keep this private.`,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
return shape.scope != null ? "shared" : "private";
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Refuse a shape whose `rowFilter` cannot actually filter.
|
|
479
|
+
*
|
|
480
|
+
* The control plane compiles a private-tier shape from `customPredicate` alone, so a filter that does
|
|
481
|
+
* not supply one is created with no subject test and streams **every** row to whoever subscribed. That
|
|
482
|
+
* is the precise shape of a silent authorization bypass: the registry says "filtered", the wire says
|
|
483
|
+
* "all rows", and nothing anywhere reports a discrepancy.
|
|
484
|
+
*
|
|
485
|
+
* The way to land there is a `rowFilter` that filters nothing at all — no predicate and no column
|
|
486
|
+
* allow-list — so it asserts a restriction it does not carry. (A filter holding *only* `columns` is
|
|
487
|
+
* legitimate: that is how `defineReadProjection` narrows a projection's wire columns without
|
|
488
|
+
* restricting its rows.)
|
|
489
|
+
*
|
|
490
|
+
* Refused at DEFINITION time, not at the first subscribe: declaring a `rowFilter` asserts that these
|
|
491
|
+
* rows are not for everyone, and there is no input for which a filter that cannot run could later turn
|
|
492
|
+
* out to be fine. A shape that genuinely serves every row omits `rowFilter` entirely — the difference
|
|
493
|
+
* between "no filter" and "a filter that does nothing" is exactly what this keeps expressible.
|
|
494
|
+
*/
|
|
495
|
+
export function assertShapeFilterIsEnforceable(shape: ShapeSpec): void {
|
|
496
|
+
const filter = shape.rowFilter;
|
|
497
|
+
if (filter == null || filter.customPredicate != null) return;
|
|
498
|
+
|
|
499
|
+
if (filter.columns == null) {
|
|
500
|
+
throw new Error(
|
|
501
|
+
`[pgxsinkit] shape "${shape.shapeKey}" declares a rowFilter that restricts nothing — no ` +
|
|
502
|
+
`customPredicate and no column allow-list. Declare customPredicate, or drop the rowFilter if ` +
|
|
503
|
+
`the rows really are for everyone (an absent rowFilter is how a shape says so).`,
|
|
504
|
+
);
|
|
505
|
+
}
|
|
278
506
|
}
|
|
279
507
|
|
|
280
508
|
/** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.
|
|
281
509
|
* When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.
|
|
282
|
-
* `
|
|
283
|
-
* (see {@link ShapeSpec.
|
|
510
|
+
* `physicalTable` is deliberately absent — it is a resolved/internal field, never a consumer input
|
|
511
|
+
* (see {@link ShapeSpec.physicalTable}); a read projection over an existing table is authored with
|
|
284
512
|
* `defineReadProjection`, which derives it from the owner. */
|
|
285
|
-
export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "
|
|
513
|
+
export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "physicalTable"> & {
|
|
286
514
|
tableName?: string;
|
|
287
515
|
shapeKey?: string;
|
|
288
516
|
};
|
|
@@ -294,34 +522,74 @@ export interface RowTransformContext {
|
|
|
294
522
|
}
|
|
295
523
|
|
|
296
524
|
/**
|
|
297
|
-
* Per-row rewrite applied
|
|
298
|
-
* column omission). Receives a
|
|
525
|
+
* Per-row rewrite applied on the server's read egress path (after the row filter, before
|
|
526
|
+
* column omission). Receives a streamed row's column map (keys are wire/column names)
|
|
299
527
|
* and returns a possibly-rewritten one — letting the server strip a *sub-document* of a
|
|
300
528
|
* jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses
|
|
301
529
|
* what a static, whole-column `omitColumns` cannot.
|
|
302
530
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
531
|
+
* Server authority only: it never alters the local pgwasm schema and never alters the shape
|
|
532
|
+
* definition — the engine ref-counts shapes by definition (ADR-0055), so a transform can
|
|
533
|
+
* neither change which stream a subject reads nor split one that would otherwise be shared.
|
|
534
|
+
* Return the same `row` reference to signal "no change".
|
|
306
535
|
*/
|
|
307
536
|
export type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;
|
|
308
537
|
|
|
538
|
+
/**
|
|
539
|
+
* One index the LOCAL store should carry on a synced table (see {@link ClientProjectionSpec.localIndexes}).
|
|
540
|
+
* A plain ascending btree over projected columns — deliberately the same expressiveness the local schema
|
|
541
|
+
* generator's shared `CREATE INDEX` core has for the journal indexes, and no more.
|
|
542
|
+
*/
|
|
543
|
+
export interface LocalIndexSpec {
|
|
544
|
+
/** The index's name. Unique within the entry, and a plain identifier — it is emitted into DDL. */
|
|
545
|
+
name: string;
|
|
546
|
+
/**
|
|
547
|
+
* The indexed columns, in order. Each names a column of the entry's table by DB column name or by
|
|
548
|
+
* Drizzle property key (the same either/or the primary-key specs accept), and must survive the client
|
|
549
|
+
* projection: naming an `omitColumns` column is a registry error, because the local table has no such
|
|
550
|
+
* column to index.
|
|
551
|
+
*/
|
|
552
|
+
columns: readonly string[];
|
|
553
|
+
/**
|
|
554
|
+
* Emit `CREATE UNIQUE INDEX`. Note what that means for a synced cache: uniqueness is the SERVER's
|
|
555
|
+
* guarantee, and a local unique index turns a violation into a failed apply rather than a rejected
|
|
556
|
+
* write. Declare it only where the server constraint genuinely holds for the projected rows.
|
|
557
|
+
*/
|
|
558
|
+
unique?: boolean;
|
|
559
|
+
}
|
|
560
|
+
|
|
309
561
|
export interface ClientProjectionSpec {
|
|
310
562
|
syncedTable?: string;
|
|
311
563
|
overlayTable?: string;
|
|
312
564
|
journalTable?: string;
|
|
313
565
|
omitColumns?: readonly string[];
|
|
314
566
|
localPrimaryKey?: PrimaryKeySpec;
|
|
567
|
+
/**
|
|
568
|
+
* OPT-IN local indexes for this entry's synced table (ADR-0029 D3's renderer, consumer-declared).
|
|
569
|
+
*
|
|
570
|
+
* The local store renders a table's PRIMARY KEY and nothing else — a synced table's server-side indexes
|
|
571
|
+
* are NOT mirrored, deliberately: they serve server loads, and half of them cover columns a client
|
|
572
|
+
* projection omits. So a local read path that needs an index has to say so here, and only here.
|
|
573
|
+
*
|
|
574
|
+
* Declare what the CLIENT's queries need, not what the server has: a scan the app runs on every render
|
|
575
|
+
* over a large synced table (the motivating case: a `due_at` window over 100k rows — ~13 ms sequential
|
|
576
|
+
* vs ~0.1 ms indexed on pgwasm, logged by `tests/unit/read-model-overlay-plan`). Each index costs write
|
|
577
|
+
* time on every applied batch and space in the user's store, so an index nothing queries is a straight loss.
|
|
578
|
+
*
|
|
579
|
+
* Rendered on the synced table ONLY — never on the overlay, whose primary key is already its index and
|
|
580
|
+
* whose plan problem is not an index problem (see the read model's non-membership test).
|
|
581
|
+
*/
|
|
582
|
+
localIndexes?: readonly LocalIndexSpec[];
|
|
315
583
|
}
|
|
316
584
|
|
|
317
585
|
/**
|
|
318
|
-
* Server-side projection applied
|
|
319
|
-
* authority, not client shape — it never alters the local
|
|
320
|
-
*
|
|
586
|
+
* Server-side projection applied on the read egress path. This is server
|
|
587
|
+
* authority, not client shape — it never alters the local pgwasm schema or the
|
|
588
|
+
* shape definition — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
|
|
321
589
|
*/
|
|
322
590
|
export interface ServerProjectionSpec {
|
|
323
591
|
/**
|
|
324
|
-
* Optional per-row rewrite applied
|
|
592
|
+
* Optional per-row rewrite applied on the read egress path. Runs before column
|
|
325
593
|
* omission, so it may read a column (e.g. a control flag) that
|
|
326
594
|
* `clientProjection.omitColumns` then removes from the client-visible row. See
|
|
327
595
|
* {@link RowTransform}.
|
|
@@ -382,8 +650,9 @@ export interface TableSpecInput {
|
|
|
382
650
|
clientProjection?: ClientProjectionSpec;
|
|
383
651
|
governance?: TableGovernanceSpec;
|
|
384
652
|
/**
|
|
385
|
-
* Consistency group (ADR-0009 decision 2): tables sharing a group sync on one
|
|
386
|
-
*
|
|
653
|
+
* Consistency group (ADR-0009 decision 2): tables sharing a group sync on one set of streams and
|
|
654
|
+
* commit atomically — every stream up-to-date, then one transaction (ADR-0056). Absent → the table is
|
|
655
|
+
* its own singleton group.
|
|
387
656
|
*/
|
|
388
657
|
consistencyGroup?: string;
|
|
389
658
|
/**
|
|
@@ -404,12 +673,6 @@ export interface TableSpecInput {
|
|
|
404
673
|
writeMode?: WriteMode;
|
|
405
674
|
}
|
|
406
675
|
|
|
407
|
-
export interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {
|
|
408
|
-
electricUrl: string;
|
|
409
|
-
localSchema?: string;
|
|
410
|
-
tables: TTables;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
676
|
export function getLocalSyncPrimaryKey(source: {
|
|
414
677
|
primaryKey: PrimaryKeySpec;
|
|
415
678
|
clientProjection?: Pick<ClientProjectionSpec, "localPrimaryKey">;
|
|
@@ -426,56 +689,47 @@ export function getLocalSyncPrimaryKeyColumns(source: {
|
|
|
426
689
|
|
|
427
690
|
export interface RowFilterSpec {
|
|
428
691
|
/**
|
|
429
|
-
* The row filter:
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
* embed request-derived values directly — they become **bound `$n` params**, never hand-escaped
|
|
433
|
-
* literals. Enum columns must be cast to text (`${c(col)}::text = 'x'`) for Electric's grammar,
|
|
434
|
-
* and subqueries must be self-contained (not correlated), since Electric needs plain column refs.
|
|
692
|
+
* The PRIVATE-TIER row filter (ADR-0055): the predicate fused with the caller's claims, compiled
|
|
693
|
+
* into the shape at subscribe. `null` bypasses filtering (all rows); {@link DENY_ALL_PREDICATE}
|
|
694
|
+
* denies.
|
|
435
695
|
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
439
|
-
*
|
|
696
|
+
* Authored with the `p.*` builders over real Drizzle column objects, so a comparison is checked
|
|
697
|
+
* against the column's own TypeScript type — a mistyped enum label, a `null` against a NOT NULL
|
|
698
|
+
* column, or a `jsonb`/`Date` column with no scalar wire form are all compile errors rather than
|
|
699
|
+
* silently-wrong filters.
|
|
440
700
|
*
|
|
441
|
-
* **Must be pure
|
|
442
|
-
*
|
|
443
|
-
* {@link isClaimsDependentRowFilter}). Do not memoize, mutate external state, or assume it runs once.
|
|
701
|
+
* **Must be pure**: it is called fresh per shape creation, and probed with empty claims to detect
|
|
702
|
+
* claims-dependence (ADR-0039 — {@link isClaimsDependentRowFilter}).
|
|
444
703
|
*/
|
|
445
|
-
|
|
704
|
+
customPredicate?: (claims: JwtClaims, params?: Record<string, unknown>) => Predicate | null;
|
|
446
705
|
/** Column projection for the shape URL (e.g. ["id", "source_text"]). */
|
|
447
706
|
columns?: string[];
|
|
448
707
|
/**
|
|
449
|
-
* An opaque version tag for the part of this filter the fingerprint cannot see — the
|
|
450
|
-
* body (you cannot hash a closure; only its *presence* is fingerprinted). Bump
|
|
451
|
-
* string/number) whenever you change that logic so the fingerprint shifts and the
|
|
452
|
-
* rebuilds + the shape subscription resets. Leaving it unchanged after a
|
|
453
|
-
* authorization change would silently serve the stale shape.
|
|
708
|
+
* An opaque version tag for the part of this filter the fingerprint cannot see — the
|
|
709
|
+
* `customPredicate` body (you cannot hash a closure; only its *presence* is fingerprinted). Bump
|
|
710
|
+
* this (any new string/number) whenever you change that logic so the fingerprint shifts and the
|
|
711
|
+
* local read cache rebuilds + the shape subscription resets. Leaving it unchanged after a
|
|
712
|
+
* `customPredicate` authorization change would silently serve the stale shape.
|
|
454
713
|
*/
|
|
455
714
|
revision?: string | number;
|
|
456
715
|
}
|
|
457
716
|
|
|
458
717
|
/**
|
|
459
|
-
*
|
|
460
|
-
* `"work_items"."workspace_id"`. Electric's shape `where` grammar requires *plain* column references
|
|
461
|
-
* (it rejects a qualified one with "Expected a plain column reference"), and Drizzle qualifies columns
|
|
462
|
-
* by default — so reference columns through `c()` when authoring a `customWhere` Drizzle fragment. The
|
|
463
|
-
* column object keeps the reference rename-safe and existence-checked at compile time; only the bare
|
|
464
|
-
* name reaches the wire. Subqueries must stay self-contained (not correlated), since bare names then
|
|
465
|
-
* resolve unambiguously to each FROM — a correlated subquery would need qualification Electric rejects.
|
|
466
|
-
*/
|
|
467
|
-
export function c(column: AnyColumn): SQL {
|
|
468
|
-
return sql`${sql.identifier(column.name)}`;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
/**
|
|
472
|
-
* The deny-all row filter: a `customWhere` returns this to make **no** rows visible (e.g. an
|
|
718
|
+
* The deny-all predicate: a `customPredicate` returns this to make **no** rows visible (e.g. an
|
|
473
719
|
* unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows
|
|
474
|
-
* visible).
|
|
475
|
-
*
|
|
476
|
-
*
|
|
720
|
+
* visible).
|
|
721
|
+
*
|
|
722
|
+
* An empty `OR` rather than a synthetic always-false comparison: the engine evaluates it as FALSE by
|
|
723
|
+
* construction (`Or` starts at FALSE and only TRUE dominates), it needs no column to name, and it
|
|
724
|
+
* cannot be made accidentally true by a NULL cell the way `col <> col` can.
|
|
725
|
+
*
|
|
726
|
+
* The control plane recognises it **by reference identity** and declines to create the shape at all,
|
|
727
|
+
* so a denied subject holds no handle and no stream is materialised — a stronger outcome than an
|
|
728
|
+
* empty stream, and the reason this is a frozen singleton rather than a shape a caller might
|
|
729
|
+
* reconstruct. A structurally equal but distinct `{ or: [] }` is still correct on the wire; it just
|
|
730
|
+
* costs an empty shape instead of a refusal.
|
|
477
731
|
*/
|
|
478
|
-
export const
|
|
732
|
+
export const DENY_ALL_PREDICATE: Predicate = Object.freeze({ or: [] as Predicate[] });
|
|
479
733
|
|
|
480
734
|
/**
|
|
481
735
|
* Whether a row filter denies (or cannot serve) an unauthenticated caller — a *claims-dependent*
|
|
@@ -483,65 +737,35 @@ export const DENY_ALL: SQL = sql`false`;
|
|
|
483
737
|
* claims-dependent, activated with no auth token, opens an empty subscription by construction, so
|
|
484
738
|
* the client warns.
|
|
485
739
|
*
|
|
486
|
-
* A filter is claims-dependent when its `
|
|
487
|
-
* exactly what the
|
|
488
|
-
* returns the {@link
|
|
489
|
-
* {@link
|
|
490
|
-
* the documented deny-anonymous pattern). Any other result — `null` (no
|
|
491
|
-
* different
|
|
740
|
+
* A filter is claims-dependent when its `customPredicate`, evaluated with **empty claims** (`{}` —
|
|
741
|
+
* exactly what the control plane passes for an unauthenticated request) and no params, either
|
|
742
|
+
* **throws** or returns the {@link DENY_ALL_PREDICATE} sentinel by **reference identity** (which every
|
|
743
|
+
* contracts helper — {@link buildOwnershipShapePredicate} and friends — returns for a missing subject,
|
|
744
|
+
* and which is already the documented deny-anonymous pattern). Any other result — `null` (no
|
|
745
|
+
* filtering) or a different predicate — is not claims-dependent as far as this probe can tell.
|
|
492
746
|
*
|
|
493
|
-
* Requires `
|
|
747
|
+
* Requires `customPredicate` to be pure (its contract; see {@link RowFilterSpec.customPredicate}).
|
|
494
748
|
*/
|
|
495
749
|
export function isClaimsDependentRowFilter(filter: RowFilterSpec | undefined): boolean {
|
|
496
|
-
if (!filter?.
|
|
750
|
+
if (!filter?.customPredicate) {
|
|
497
751
|
return false;
|
|
498
752
|
}
|
|
499
753
|
|
|
500
754
|
try {
|
|
501
|
-
return filter.
|
|
755
|
+
return filter.customPredicate({}, undefined) === DENY_ALL_PREDICATE;
|
|
502
756
|
} catch {
|
|
503
757
|
return true;
|
|
504
758
|
}
|
|
505
759
|
}
|
|
506
760
|
|
|
507
761
|
/**
|
|
508
|
-
* The ownership
|
|
509
|
-
*
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
|
|
514
|
-
export function buildOwnershipShapeWhere(ownerColumn: AnyColumn, subject: string | null | undefined): SQL {
|
|
515
|
-
return subject == null || subject === "" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
/** The parameterized shape filter the proxy sends to Electric: a `where` and its positional params. */
|
|
519
|
-
export interface RowFilterShape {
|
|
520
|
-
where: string;
|
|
521
|
-
params: string[];
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* The shape filter the proxy sends to Electric: the `where` plus its positional `params` (`$1`, `$2`,
|
|
526
|
-
* …). A `customWhere` returning a Drizzle `SQL` fragment is serialized here, so request-derived values
|
|
527
|
-
* become **bound params** — never hand-escaped literals; a string `customWhere` is the raw escape
|
|
528
|
-
* hatch (no params). Returns `null` when there is no filter (all rows visible).
|
|
762
|
+
* The ownership **predicate** the read path filters on: rows whose owner column equals the caller's
|
|
763
|
+
* subject, {@link DENY_ALL_PREDICATE} for an unauthenticated caller (by reference, so a
|
|
764
|
+
* `customPredicate` built on it probes claims-dependent).
|
|
765
|
+
*
|
|
766
|
+
* Takes the real Drizzle owner column, so the reference is rename-safe, and the subject rides as a
|
|
767
|
+
* typed JSON scalar rather than text that has to be escaped and re-parsed.
|
|
529
768
|
*/
|
|
530
|
-
export function
|
|
531
|
-
|
|
532
|
-
claims: JwtClaims | null,
|
|
533
|
-
params?: Record<string, unknown>,
|
|
534
|
-
): RowFilterShape | null {
|
|
535
|
-
const custom = filter.customWhere?.(claims ?? {}, params);
|
|
536
|
-
|
|
537
|
-
if (custom == null) {
|
|
538
|
-
return null;
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
if (typeof custom === "string") {
|
|
542
|
-
return custom ? { where: custom, params: [] } : null;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
const compiled = pgDialect.sqlToQuery(custom);
|
|
546
|
-
return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };
|
|
769
|
+
export function buildOwnershipShapePredicate(ownerColumn: AnyColumn, subject: string | null | undefined): Predicate {
|
|
770
|
+
return subject == null || subject === "" ? DENY_ALL_PREDICATE : p.eq(ownerColumn, subject);
|
|
547
771
|
}
|