@pgxsinkit/contracts 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config.d.ts +126 -84
- 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 +368 -198
- package/dist/index.js.map +14 -12
- package/dist/predicate.d.ts +162 -0
- package/dist/predicate.d.ts.map +1 -0
- package/dist/projection.d.ts +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 +67 -43
- package/dist/registry.d.ts.map +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 +1 -1
- package/skills/registry-authoring/SKILL.md +149 -149
- package/src/config.ts +154 -112
- 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 +1 -1
- package/src/registry-diff.ts +15 -4
- package/src/registry-invariant.ts +34 -19
- package/src/registry.ts +193 -65
- 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
|
|
|
@@ -265,24 +265,109 @@ export interface ShapeSpec {
|
|
|
265
265
|
/**
|
|
266
266
|
* INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the
|
|
267
267
|
* 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`
|
|
268
|
+
* name so several shapes can read one physical table under distinct `shapeKey`s; the control plane
|
|
269
|
+
* resolves an incoming subscription by `shapeKey` and consults this only when it creates the shape, as
|
|
270
|
+
* the source `table` it hands the engine. `attachSyncRegistrySchema` also fills/qualifies it for
|
|
271
|
+
* schema-bound registries.
|
|
271
272
|
*
|
|
272
273
|
* Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or
|
|
273
274
|
* wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The
|
|
274
275
|
* combinator derives it from the owner; `defineSyncTable` never sets it from input.
|
|
275
276
|
*/
|
|
276
|
-
|
|
277
|
+
physicalTable?: string;
|
|
277
278
|
rowFilter?: RowFilterSpec;
|
|
279
|
+
/**
|
|
280
|
+
* SHARED TIER (ADR-0055) — the scope columns, resolved to column names, whose values key this
|
|
281
|
+
* shape family. The predicate is *generated* as an `AND` of equalities over them, so disjointness
|
|
282
|
+
* is a property of the construction rather than something a checker has to enforce: a row carries
|
|
283
|
+
* exactly one value per scope column, so it falls in exactly one shape of the family, and an
|
|
284
|
+
* overlapping pair is not expressible at all.
|
|
285
|
+
*
|
|
286
|
+
* `NULL` is a legal scope value and compiles to `IS NULL` — which is how an offering-wide row gets
|
|
287
|
+
* its own scope `(O, null)` rather than appearing in every group's shape. The tempting
|
|
288
|
+
* `group_id IS NULL OR group_id = $G` form is not merely disallowed here; it is wrong, because it
|
|
289
|
+
* places one row in every group shape at once.
|
|
290
|
+
*
|
|
291
|
+
* Its presence is what makes this a shared-tier shape. Declaring it alongside `rowFilter` is
|
|
292
|
+
* refused at definition time — see {@link readShapeTier}.
|
|
293
|
+
*/
|
|
294
|
+
scope?: readonly string[];
|
|
295
|
+
/**
|
|
296
|
+
* The **static** half of the shape's predicate: subscriber-independent, identical for every
|
|
297
|
+
* reader, and therefore safe in either tier. On the shared tier it is conjoined with the generated
|
|
298
|
+
* scope equalities; on the private tier, with whatever `rowFilter` resolves to for the subject.
|
|
299
|
+
*
|
|
300
|
+
* Native AST, not SQL text — see {@link Predicate}.
|
|
301
|
+
*/
|
|
302
|
+
where?: Predicate;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Which read tier a shape belongs to (ADR-0055 decision 2). */
|
|
306
|
+
export type ShapeTier = "shared" | "private";
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The tier a shape declares, or a refusal.
|
|
310
|
+
*
|
|
311
|
+
* The tier is not configured; it is *read off* which field the author declared — `scope` for shared,
|
|
312
|
+
* `rowFilter` for private. That makes a shape's tier evident from its authoring and impossible to
|
|
313
|
+
* leave ambiguous, which matters because the two differ in whether their bytes are user-independent,
|
|
314
|
+
* and so in whether they may be shared and cached at all.
|
|
315
|
+
*
|
|
316
|
+
* Declaring both is refused rather than resolved by precedence. A `rowFilter` fuses the subject into
|
|
317
|
+
* the predicate, which is exactly what makes a stream unshareable; silently letting it ride along on
|
|
318
|
+
* a shape declared as shared would produce a stream that is cached under a scope key while carrying
|
|
319
|
+
* subject-dependent bytes — a disclosure, not a stale row.
|
|
320
|
+
*/
|
|
321
|
+
export function readShapeTier(shape: ShapeSpec): ShapeTier {
|
|
322
|
+
if (shape.scope != null && shape.rowFilter != null) {
|
|
323
|
+
throw new Error(
|
|
324
|
+
`[pgxsinkit] shape "${shape.shapeKey}" declares both scope and rowFilter — a shape is shared ` +
|
|
325
|
+
`(scope: the predicate is a function of scope values only) or private (rowFilter: the subject ` +
|
|
326
|
+
`is fused into the predicate), never both. A rowFilter makes the stream's bytes ` +
|
|
327
|
+
`subject-dependent, so it cannot be served from a scope-keyed shared stream. Move the ` +
|
|
328
|
+
`subject-dependent part into the entitlement rule, or drop scope and keep this private.`,
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
return shape.scope != null ? "shared" : "private";
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Refuse a shape whose `rowFilter` cannot actually filter.
|
|
336
|
+
*
|
|
337
|
+
* The control plane compiles a private-tier shape from `customPredicate` alone, so a filter that does
|
|
338
|
+
* not supply one is created with no subject test and streams **every** row to whoever subscribed. That
|
|
339
|
+
* is the precise shape of a silent authorization bypass: the registry says "filtered", the wire says
|
|
340
|
+
* "all rows", and nothing anywhere reports a discrepancy.
|
|
341
|
+
*
|
|
342
|
+
* The way to land there is a `rowFilter` that filters nothing at all — no predicate and no column
|
|
343
|
+
* allow-list — so it asserts a restriction it does not carry. (A filter holding *only* `columns` is
|
|
344
|
+
* legitimate: that is how `defineReadProjection` narrows a projection's wire columns without
|
|
345
|
+
* restricting its rows.)
|
|
346
|
+
*
|
|
347
|
+
* Refused at DEFINITION time, not at the first subscribe: declaring a `rowFilter` asserts that these
|
|
348
|
+
* rows are not for everyone, and there is no input for which a filter that cannot run could later turn
|
|
349
|
+
* out to be fine. A shape that genuinely serves every row omits `rowFilter` entirely — the difference
|
|
350
|
+
* between "no filter" and "a filter that does nothing" is exactly what this keeps expressible.
|
|
351
|
+
*/
|
|
352
|
+
export function assertShapeFilterIsEnforceable(shape: ShapeSpec): void {
|
|
353
|
+
const filter = shape.rowFilter;
|
|
354
|
+
if (filter == null || filter.customPredicate != null) return;
|
|
355
|
+
|
|
356
|
+
if (filter.columns == null) {
|
|
357
|
+
throw new Error(
|
|
358
|
+
`[pgxsinkit] shape "${shape.shapeKey}" declares a rowFilter that restricts nothing — no ` +
|
|
359
|
+
`customPredicate and no column allow-list. Declare customPredicate, or drop the rowFilter if ` +
|
|
360
|
+
`the rows really are for everyone (an absent rowFilter is how a shape says so).`,
|
|
361
|
+
);
|
|
362
|
+
}
|
|
278
363
|
}
|
|
279
364
|
|
|
280
365
|
/** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.
|
|
281
366
|
* When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.
|
|
282
|
-
* `
|
|
283
|
-
* (see {@link ShapeSpec.
|
|
367
|
+
* `physicalTable` is deliberately absent — it is a resolved/internal field, never a consumer input
|
|
368
|
+
* (see {@link ShapeSpec.physicalTable}); a read projection over an existing table is authored with
|
|
284
369
|
* `defineReadProjection`, which derives it from the owner. */
|
|
285
|
-
export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "
|
|
370
|
+
export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "physicalTable"> & {
|
|
286
371
|
tableName?: string;
|
|
287
372
|
shapeKey?: string;
|
|
288
373
|
};
|
|
@@ -294,15 +379,16 @@ export interface RowTransformContext {
|
|
|
294
379
|
}
|
|
295
380
|
|
|
296
381
|
/**
|
|
297
|
-
* Per-row rewrite applied
|
|
298
|
-
* column omission). Receives a
|
|
382
|
+
* Per-row rewrite applied on the server's read egress path (after the row filter, before
|
|
383
|
+
* column omission). Receives a streamed row's column map (keys are wire/column names)
|
|
299
384
|
* and returns a possibly-rewritten one — letting the server strip a *sub-document* of a
|
|
300
385
|
* jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses
|
|
301
386
|
* what a static, whole-column `omitColumns` cannot.
|
|
302
387
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
388
|
+
* Server authority only: it never alters the local PGlite schema and never alters the shape
|
|
389
|
+
* definition — the engine ref-counts shapes by definition (ADR-0055), so a transform can
|
|
390
|
+
* neither change which stream a subject reads nor split one that would otherwise be shared.
|
|
391
|
+
* Return the same `row` reference to signal "no change".
|
|
306
392
|
*/
|
|
307
393
|
export type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;
|
|
308
394
|
|
|
@@ -315,13 +401,13 @@ export interface ClientProjectionSpec {
|
|
|
315
401
|
}
|
|
316
402
|
|
|
317
403
|
/**
|
|
318
|
-
* Server-side projection applied
|
|
404
|
+
* Server-side projection applied on the read egress path. This is server
|
|
319
405
|
* authority, not client shape — it never alters the local PGlite schema or the
|
|
320
|
-
*
|
|
406
|
+
* shape definition — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
|
|
321
407
|
*/
|
|
322
408
|
export interface ServerProjectionSpec {
|
|
323
409
|
/**
|
|
324
|
-
* Optional per-row rewrite applied
|
|
410
|
+
* Optional per-row rewrite applied on the read egress path. Runs before column
|
|
325
411
|
* omission, so it may read a column (e.g. a control flag) that
|
|
326
412
|
* `clientProjection.omitColumns` then removes from the client-visible row. See
|
|
327
413
|
* {@link RowTransform}.
|
|
@@ -382,8 +468,9 @@ export interface TableSpecInput {
|
|
|
382
468
|
clientProjection?: ClientProjectionSpec;
|
|
383
469
|
governance?: TableGovernanceSpec;
|
|
384
470
|
/**
|
|
385
|
-
* Consistency group (ADR-0009 decision 2): tables sharing a group sync on one
|
|
386
|
-
*
|
|
471
|
+
* Consistency group (ADR-0009 decision 2): tables sharing a group sync on one set of streams and
|
|
472
|
+
* commit atomically — every stream up-to-date, then one transaction (ADR-0056). Absent → the table is
|
|
473
|
+
* its own singleton group.
|
|
387
474
|
*/
|
|
388
475
|
consistencyGroup?: string;
|
|
389
476
|
/**
|
|
@@ -404,12 +491,6 @@ export interface TableSpecInput {
|
|
|
404
491
|
writeMode?: WriteMode;
|
|
405
492
|
}
|
|
406
493
|
|
|
407
|
-
export interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {
|
|
408
|
-
electricUrl: string;
|
|
409
|
-
localSchema?: string;
|
|
410
|
-
tables: TTables;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
494
|
export function getLocalSyncPrimaryKey(source: {
|
|
414
495
|
primaryKey: PrimaryKeySpec;
|
|
415
496
|
clientProjection?: Pick<ClientProjectionSpec, "localPrimaryKey">;
|
|
@@ -426,56 +507,47 @@ export function getLocalSyncPrimaryKeyColumns(source: {
|
|
|
426
507
|
|
|
427
508
|
export interface RowFilterSpec {
|
|
428
509
|
/**
|
|
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.
|
|
510
|
+
* The PRIVATE-TIER row filter (ADR-0055): the predicate fused with the caller's claims, compiled
|
|
511
|
+
* into the shape at subscribe. `null` bypasses filtering (all rows); {@link DENY_ALL_PREDICATE}
|
|
512
|
+
* denies.
|
|
435
513
|
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
439
|
-
*
|
|
514
|
+
* Authored with the `p.*` builders over real Drizzle column objects, so a comparison is checked
|
|
515
|
+
* against the column's own TypeScript type — a mistyped enum label, a `null` against a NOT NULL
|
|
516
|
+
* column, or a `jsonb`/`Date` column with no scalar wire form are all compile errors rather than
|
|
517
|
+
* silently-wrong filters.
|
|
440
518
|
*
|
|
441
|
-
* **Must be pure
|
|
442
|
-
*
|
|
443
|
-
* {@link isClaimsDependentRowFilter}). Do not memoize, mutate external state, or assume it runs once.
|
|
519
|
+
* **Must be pure**: it is called fresh per shape creation, and probed with empty claims to detect
|
|
520
|
+
* claims-dependence (ADR-0039 — {@link isClaimsDependentRowFilter}).
|
|
444
521
|
*/
|
|
445
|
-
|
|
522
|
+
customPredicate?: (claims: JwtClaims, params?: Record<string, unknown>) => Predicate | null;
|
|
446
523
|
/** Column projection for the shape URL (e.g. ["id", "source_text"]). */
|
|
447
524
|
columns?: string[];
|
|
448
525
|
/**
|
|
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.
|
|
526
|
+
* An opaque version tag for the part of this filter the fingerprint cannot see — the
|
|
527
|
+
* `customPredicate` body (you cannot hash a closure; only its *presence* is fingerprinted). Bump
|
|
528
|
+
* this (any new string/number) whenever you change that logic so the fingerprint shifts and the
|
|
529
|
+
* local read cache rebuilds + the shape subscription resets. Leaving it unchanged after a
|
|
530
|
+
* `customPredicate` authorization change would silently serve the stale shape.
|
|
454
531
|
*/
|
|
455
532
|
revision?: string | number;
|
|
456
533
|
}
|
|
457
534
|
|
|
458
535
|
/**
|
|
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
|
|
536
|
+
* The deny-all predicate: a `customPredicate` returns this to make **no** rows visible (e.g. an
|
|
473
537
|
* unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows
|
|
474
|
-
* visible).
|
|
475
|
-
*
|
|
476
|
-
*
|
|
538
|
+
* visible).
|
|
539
|
+
*
|
|
540
|
+
* An empty `OR` rather than a synthetic always-false comparison: the engine evaluates it as FALSE by
|
|
541
|
+
* construction (`Or` starts at FALSE and only TRUE dominates), it needs no column to name, and it
|
|
542
|
+
* cannot be made accidentally true by a NULL cell the way `col <> col` can.
|
|
543
|
+
*
|
|
544
|
+
* The control plane recognises it **by reference identity** and declines to create the shape at all,
|
|
545
|
+
* so a denied subject holds no handle and no stream is materialised — a stronger outcome than an
|
|
546
|
+
* empty stream, and the reason this is a frozen singleton rather than a shape a caller might
|
|
547
|
+
* reconstruct. A structurally equal but distinct `{ or: [] }` is still correct on the wire; it just
|
|
548
|
+
* costs an empty shape instead of a refusal.
|
|
477
549
|
*/
|
|
478
|
-
export const
|
|
550
|
+
export const DENY_ALL_PREDICATE: Predicate = Object.freeze({ or: [] as Predicate[] });
|
|
479
551
|
|
|
480
552
|
/**
|
|
481
553
|
* Whether a row filter denies (or cannot serve) an unauthenticated caller — a *claims-dependent*
|
|
@@ -483,65 +555,35 @@ export const DENY_ALL: SQL = sql`false`;
|
|
|
483
555
|
* claims-dependent, activated with no auth token, opens an empty subscription by construction, so
|
|
484
556
|
* the client warns.
|
|
485
557
|
*
|
|
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
|
|
558
|
+
* A filter is claims-dependent when its `customPredicate`, evaluated with **empty claims** (`{}` —
|
|
559
|
+
* exactly what the control plane passes for an unauthenticated request) and no params, either
|
|
560
|
+
* **throws** or returns the {@link DENY_ALL_PREDICATE} sentinel by **reference identity** (which every
|
|
561
|
+
* contracts helper — {@link buildOwnershipShapePredicate} and friends — returns for a missing subject,
|
|
562
|
+
* and which is already the documented deny-anonymous pattern). Any other result — `null` (no
|
|
563
|
+
* filtering) or a different predicate — is not claims-dependent as far as this probe can tell.
|
|
492
564
|
*
|
|
493
|
-
* Requires `
|
|
565
|
+
* Requires `customPredicate` to be pure (its contract; see {@link RowFilterSpec.customPredicate}).
|
|
494
566
|
*/
|
|
495
567
|
export function isClaimsDependentRowFilter(filter: RowFilterSpec | undefined): boolean {
|
|
496
|
-
if (!filter?.
|
|
568
|
+
if (!filter?.customPredicate) {
|
|
497
569
|
return false;
|
|
498
570
|
}
|
|
499
571
|
|
|
500
572
|
try {
|
|
501
|
-
return filter.
|
|
573
|
+
return filter.customPredicate({}, undefined) === DENY_ALL_PREDICATE;
|
|
502
574
|
} catch {
|
|
503
575
|
return true;
|
|
504
576
|
}
|
|
505
577
|
}
|
|
506
578
|
|
|
507
579
|
/**
|
|
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).
|
|
580
|
+
* The ownership **predicate** the read path filters on: rows whose owner column equals the caller's
|
|
581
|
+
* subject, {@link DENY_ALL_PREDICATE} for an unauthenticated caller (by reference, so a
|
|
582
|
+
* `customPredicate` built on it probes claims-dependent).
|
|
583
|
+
*
|
|
584
|
+
* Takes the real Drizzle owner column, so the reference is rename-safe, and the subject rides as a
|
|
585
|
+
* typed JSON scalar rather than text that has to be escaped and re-parsed.
|
|
529
586
|
*/
|
|
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)) };
|
|
587
|
+
export function buildOwnershipShapePredicate(ownerColumn: AnyColumn, subject: string | null | undefined): Predicate {
|
|
588
|
+
return subject == null || subject === "" ? DENY_ALL_PREDICATE : p.eq(ownerColumn, subject);
|
|
547
589
|
}
|
package/src/convergence-model.ts
CHANGED
|
@@ -169,11 +169,11 @@ export const CONVERGENCE_EVENTS = [
|
|
|
169
169
|
"journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up",
|
|
170
170
|
},
|
|
171
171
|
{
|
|
172
|
-
event: "
|
|
172
|
+
event: "synced upsert observed",
|
|
173
173
|
effect: "synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal",
|
|
174
174
|
},
|
|
175
175
|
{
|
|
176
|
-
event: "
|
|
176
|
+
event: "synced delete observed",
|
|
177
177
|
effect: "resolved by synced-row absence (deletes carry no Server version — ADR-0010)",
|
|
178
178
|
},
|
|
179
179
|
{ event: "resolution", effect: "clear overlay/journal only through the shared barrier predicate (decision 4)" },
|
package/src/event-stream.ts
CHANGED
|
@@ -72,7 +72,7 @@ export interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {
|
|
|
72
72
|
identity: Record<string, EventStreamIdentityField>;
|
|
73
73
|
/**
|
|
74
74
|
* An opaque version counter for the part of this payload contract the lock's hash cannot see — the same
|
|
75
|
-
* role `RowFilterSpec.revision` plays for a `
|
|
75
|
+
* role `RowFilterSpec.revision` plays for a `customPredicate` closure. The lock hashes the payload schema as
|
|
76
76
|
* a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer
|
|
77
77
|
* demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce
|
|
78
78
|
* the identical stream hash, so the `risky` diff the ADR relies on never fires.
|
package/src/fingerprint.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
|
|
2
2
|
|
|
3
3
|
import type { RowFilterSpec } from "./config";
|
|
4
|
+
import {
|
|
5
|
+
isAndPredicate,
|
|
6
|
+
isInSubqueryPredicate,
|
|
7
|
+
isIsNullPredicate,
|
|
8
|
+
isNotPredicate,
|
|
9
|
+
isOrPredicate,
|
|
10
|
+
type Predicate,
|
|
11
|
+
} from "./predicate";
|
|
4
12
|
import type { SyncTableEntry, SyncTableRegistry } from "./registry";
|
|
5
13
|
|
|
6
14
|
/**
|
|
@@ -9,10 +17,10 @@ import type { SyncTableEntry, SyncTableRegistry } from "./registry";
|
|
|
9
17
|
*
|
|
10
18
|
* This is the single source of "has the shape changed" — consumed as the local-DB
|
|
11
19
|
* version key and as the basis of the registry-diff gate (ADR-0006). Function *bodies*
|
|
12
|
-
* (`rowTransform`, `
|
|
20
|
+
* (`rowTransform`, `customPredicate`) cannot be fingerprinted and are excluded — but their
|
|
13
21
|
* *presence* and the surrounding **static** filter structure (the projected columns)
|
|
14
22
|
* participate. For the invisible *logic* itself, a consumer-bumped `rowFilter.revision` is
|
|
15
|
-
* folded in: changing it is how a `
|
|
23
|
+
* folded in: changing it is how a `customPredicate` authorization change is forced to shift the
|
|
16
24
|
* fingerprint (and so rebuild the cache + reset the subscription).
|
|
17
25
|
*/
|
|
18
26
|
|
|
@@ -39,8 +47,18 @@ export interface CanonicalTable {
|
|
|
39
47
|
shape: {
|
|
40
48
|
tableName: string;
|
|
41
49
|
shapeKey: string;
|
|
42
|
-
|
|
50
|
+
physicalTable: string | null;
|
|
43
51
|
rowFilter: CanonicalRowFilter | null;
|
|
52
|
+
/** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
|
|
53
|
+
scope: string[] | null;
|
|
54
|
+
/**
|
|
55
|
+
* The native static predicate, canonicalized in full.
|
|
56
|
+
*
|
|
57
|
+
* Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
|
|
58
|
+
* ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
|
|
59
|
+
* a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
|
|
60
|
+
*/
|
|
61
|
+
where: string | null;
|
|
44
62
|
} | null;
|
|
45
63
|
managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;
|
|
46
64
|
/**
|
|
@@ -61,16 +79,16 @@ export interface CanonicalTable {
|
|
|
61
79
|
|
|
62
80
|
/**
|
|
63
81
|
* The static, fingerprint-able structure of a row filter. A changed projection shifts the
|
|
64
|
-
* fingerprint, so the local store rebuilds and the diff gate flags it. `
|
|
65
|
-
* invisible — only its presence (`
|
|
82
|
+
* fingerprint, so the local store rebuilds and the diff gate flags it. `customPredicate`'s body is
|
|
83
|
+
* invisible — only its presence (`hasCustomPredicate`) is recorded — so a `customPredicate` *logic* change
|
|
66
84
|
* is surfaced only by bumping `revision`.
|
|
67
85
|
*/
|
|
68
86
|
export interface CanonicalRowFilter {
|
|
69
|
-
|
|
87
|
+
hasCustomPredicate: boolean;
|
|
70
88
|
columns: string[] | null;
|
|
71
89
|
/**
|
|
72
|
-
* The consumer-supplied version tag for the non-fingerprintable filter logic (the `
|
|
73
|
-
* body). Changing it shifts the fingerprint, which is the only way a `
|
|
90
|
+
* The consumer-supplied version tag for the non-fingerprintable filter logic (the `customPredicate`
|
|
91
|
+
* body). Changing it shifts the fingerprint, which is the only way a `customPredicate` *logic* change
|
|
74
92
|
* forces a cache + subscription reset.
|
|
75
93
|
*/
|
|
76
94
|
revision: string | null;
|
|
@@ -108,12 +126,42 @@ function canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable["manag
|
|
|
108
126
|
.sort((a, b) => asString(a.field, b.field));
|
|
109
127
|
}
|
|
110
128
|
|
|
129
|
+
/**
|
|
130
|
+
* A stable string form of a native predicate.
|
|
131
|
+
*
|
|
132
|
+
* Keys are emitted in a fixed order rather than serialized as authored, so two predicates that
|
|
133
|
+
* differ only in how their object literals were written fingerprint identically — otherwise a
|
|
134
|
+
* cosmetic edit would force every client to rebuild its local cache.
|
|
135
|
+
*/
|
|
136
|
+
function canonicalizePredicate(node: Predicate | undefined): string | null {
|
|
137
|
+
if (node === undefined) return null;
|
|
138
|
+
const render = (current: Predicate): unknown => {
|
|
139
|
+
if (isAndPredicate(current)) return { and: current.and.map(render) };
|
|
140
|
+
if (isOrPredicate(current)) return { or: current.or.map(render) };
|
|
141
|
+
if (isNotPredicate(current)) return { not: render(current.not) };
|
|
142
|
+
if (isInSubqueryPredicate(current)) {
|
|
143
|
+
return {
|
|
144
|
+
col: current.col,
|
|
145
|
+
in: {
|
|
146
|
+
table: current.in.table,
|
|
147
|
+
project: current.in.project,
|
|
148
|
+
where: current.in.where ? render(current.in.where) : null,
|
|
149
|
+
},
|
|
150
|
+
negated: current.negated === true,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (isIsNullPredicate(current)) return { col: current.col, isNull: current.isNull };
|
|
154
|
+
return { col: current.col, op: current.op, value: current.value };
|
|
155
|
+
};
|
|
156
|
+
return JSON.stringify(render(node));
|
|
157
|
+
}
|
|
158
|
+
|
|
111
159
|
function canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {
|
|
112
160
|
if (!filter) {
|
|
113
161
|
return null;
|
|
114
162
|
}
|
|
115
163
|
return {
|
|
116
|
-
|
|
164
|
+
hasCustomPredicate: filter.customPredicate != null,
|
|
117
165
|
columns: filter.columns ? [...filter.columns].sort(asString) : null,
|
|
118
166
|
revision: filter.revision != null ? String(filter.revision) : null,
|
|
119
167
|
};
|
|
@@ -133,8 +181,10 @@ function canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {
|
|
|
133
181
|
? {
|
|
134
182
|
tableName: entry.shape.tableName,
|
|
135
183
|
shapeKey: entry.shape.shapeKey,
|
|
136
|
-
|
|
184
|
+
physicalTable: entry.shape.physicalTable ?? null,
|
|
137
185
|
rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
|
|
186
|
+
scope: entry.shape.scope ? [...entry.shape.scope] : null,
|
|
187
|
+
where: canonicalizePredicate(entry.shape.where),
|
|
138
188
|
}
|
|
139
189
|
: null;
|
|
140
190
|
|
|
@@ -198,7 +248,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
|
|
|
198
248
|
/**
|
|
199
249
|
* The **read contract** of a single sync table: the subset of its canonical shape that decides what
|
|
200
250
|
* data streams down and how a row is identified and filtered — synced-table name, columns, primary key
|
|
201
|
-
* (and any local-PK override), column omission, and the shape (
|
|
251
|
+
* (and any local-PK override), column omission, and the shape (physical table + row filter). It is the
|
|
202
252
|
* stable identity a writable entry shares with its {@link asReadonly} projection.
|
|
203
253
|
*
|
|
204
254
|
* Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:
|
|
@@ -209,7 +259,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
|
|
|
209
259
|
*
|
|
210
260
|
* What it pins is the data itself: two registries that present "the same" logical table to different
|
|
211
261
|
* clients must agree here, or those clients are silently seeing different rows/columns. As with the
|
|
212
|
-
* full registry fingerprint, the `
|
|
262
|
+
* full registry fingerprint, the `customPredicate` *body* is invisible — only its presence and the
|
|
213
263
|
* consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence
|
|
214
264
|
* a logic-only change would otherwise hide.
|
|
215
265
|
*/
|
|
@@ -222,8 +272,18 @@ export interface CanonicalReadContract {
|
|
|
222
272
|
shape: {
|
|
223
273
|
tableName: string;
|
|
224
274
|
shapeKey: string;
|
|
225
|
-
|
|
275
|
+
physicalTable: string | null;
|
|
226
276
|
rowFilter: CanonicalRowFilter | null;
|
|
277
|
+
/** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
|
|
278
|
+
scope: string[] | null;
|
|
279
|
+
/**
|
|
280
|
+
* The native static predicate, canonicalized in full.
|
|
281
|
+
*
|
|
282
|
+
* Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
|
|
283
|
+
* ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
|
|
284
|
+
* a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
|
|
285
|
+
*/
|
|
286
|
+
where: string | null;
|
|
227
287
|
} | null;
|
|
228
288
|
}
|
|
229
289
|
|
|
@@ -233,8 +293,10 @@ export function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadCo
|
|
|
233
293
|
? {
|
|
234
294
|
tableName: entry.shape.tableName,
|
|
235
295
|
shapeKey: entry.shape.shapeKey,
|
|
236
|
-
|
|
296
|
+
physicalTable: entry.shape.physicalTable ?? null,
|
|
237
297
|
rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
|
|
298
|
+
scope: entry.shape.scope ? [...entry.shape.scope] : null,
|
|
299
|
+
where: canonicalizePredicate(entry.shape.where),
|
|
238
300
|
}
|
|
239
301
|
: null;
|
|
240
302
|
|
package/src/index.ts
CHANGED
|
@@ -9,9 +9,11 @@ export * from "./registry";
|
|
|
9
9
|
export * from "./registry-diff";
|
|
10
10
|
export * from "./registry-invariant";
|
|
11
11
|
export * from "./mutation";
|
|
12
|
+
export * from "./predicate";
|
|
12
13
|
export * from "./projection";
|
|
13
14
|
export * from "./runtime";
|
|
14
15
|
export * from "./sql-defaults";
|
|
16
|
+
export * from "./stream-envelope";
|
|
15
17
|
export * from "./sql-identifier";
|
|
16
18
|
export * from "./sql-role-guard";
|
|
17
19
|
export * from "./supabase-rls";
|