@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
|
@@ -2,28 +2,28 @@
|
|
|
2
2
|
name: registry-authoring
|
|
3
3
|
description: >-
|
|
4
4
|
Load when defining or changing a pgxsinkit sync registry with @pgxsinkit/contracts —
|
|
5
|
-
defineSyncRegistry
|
|
6
|
-
Teaches the rules that throw or fail closed
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
CLI as a drizzle-kit migration. Covers per-client mode projection
|
|
11
|
-
asReadonly + assertReadContractPreserved) and Event-stream registration (ADR-0053):
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
5
|
+
defineSyncRegistry/defineSyncTable, sync modes, managed fields, conflict policy, filters, RLS.
|
|
6
|
+
Teaches the rules that throw or fail closed: every readwrite table needs a server-version managed field
|
|
7
|
+
plus a conflictPolicy (no default), authClaim/nowMicroseconds fields are server-assigned and rejected in
|
|
8
|
+
client payloads, a read filter is a predicate AST from the p.* builders over Drizzle columns (one
|
|
9
|
+
restricting nothing is refused) deriving from the RLS policy's own predicate, and the apply function
|
|
10
|
+
comes from the pgxsinkit-generate CLI as a drizzle-kit migration. Covers per-client mode projection
|
|
11
|
+
(asReadonly + assertReadContractPreserved) and Event-stream registration (ADR-0053): defineEventStream,
|
|
12
|
+
name limits, claimPath identity stamping, compatible-only payload evolution, and streams riding the
|
|
13
|
+
lock/diff but never the fingerprint. Load before authoring a registry, adding a table, registering an
|
|
14
|
+
Event stream, or wiring RLS.
|
|
15
15
|
metadata:
|
|
16
16
|
type: core
|
|
17
17
|
library: "@pgxsinkit/contracts"
|
|
18
|
-
library_version: "0.
|
|
18
|
+
library_version: "0.5.0"
|
|
19
19
|
source: https://pgxsinkit.github.io/start/getting-started/
|
|
20
20
|
---
|
|
21
21
|
|
|
22
22
|
# Authoring a pgxsinkit registry
|
|
23
23
|
|
|
24
|
-
The registry (`defineSyncRegistry` over `defineSyncTable`) is the single source of truth both paths read
|
|
25
|
-
|
|
26
|
-
is what keeps read and write authorization from drifting.
|
|
24
|
+
The registry (`defineSyncRegistry` over `defineSyncTable`) is the single source of truth both paths read from
|
|
25
|
+
— the read path's shapes (compiled by the control plane at subscribe) and the write apply function are derived
|
|
26
|
+
from it, so getting it right is what keeps read and write authorization from drifting.
|
|
27
27
|
|
|
28
28
|
## Writable tables have two hard requirements (or it throws)
|
|
29
29
|
|
|
@@ -56,14 +56,13 @@ widgets: defineSyncTable({
|
|
|
56
56
|
}),
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
-
**Column types don't constrain sync.** The read-path backfill picks a bulk-insert tier (COPY / JSON /
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
stores
|
|
65
|
-
|
|
66
|
-
`managedFields` target (both strategies stamp one scalar).
|
|
59
|
+
**Column types don't constrain sync.** The read-path backfill picks a bulk-insert tier (COPY / JSON / per-row
|
|
60
|
+
`INSERT`) statically from a table's Drizzle column types; enum columns and `GENERATED ALWAYS AS IDENTITY` primary
|
|
61
|
+
keys are fully supported (labels round-trip through COPY/JSON, a synced identity PK keeps the server's value via
|
|
62
|
+
`OVERRIDING SYSTEM VALUE`), so never avoid them for sync's sake. **Array columns are supported at ONE dimension**
|
|
63
|
+
(`uuid("source_ids").array()`) on both paths: a write sends a JSON array, `[]` stores an empty array and JSON `null`
|
|
64
|
+
stores NULL, element order preserved. Everything else about arrays fails at GENERATE time, named — `.array("[][]")`
|
|
65
|
+
(multi-dimensional), an array PK column, and an array `managedFields` target (both strategies stamp one scalar).
|
|
67
66
|
|
|
68
67
|
## The `primaryKey` spec emits the physical PRIMARY KEY — it is the single source of truth
|
|
69
68
|
|
|
@@ -79,19 +78,19 @@ produce), so pgxsinkit DDL matches plain-Postgres inline-PK DDL and drizzle-kit
|
|
|
79
78
|
- **Rejected:** a table-level `primaryKey(...)` through `extras`/`policies`, and more than one column-level
|
|
80
79
|
`.primaryKey()` — declare composite keys via the `primaryKey` option instead.
|
|
81
80
|
|
|
82
|
-
## `applyMode` —
|
|
81
|
+
## `applyMode` — the **backfill** conflict policy (default stays strict)
|
|
83
82
|
|
|
84
|
-
`applyMode` chooses how
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
local one.
|
|
83
|
+
`applyMode` no longer chooses how steady-state changes apply (ADR-0058). The engine's wire vocabulary is
|
|
84
|
+
`upsert | delete` — an `upsert` states a row's value without claiming it is new — so **every** streamed change
|
|
85
|
+
applies as `INSERT … ON CONFLICT (pk) DO UPDATE`, whatever this says. What survives is the **initial load**: a fresh
|
|
86
|
+
subscription or a post-must-refetch re-snapshot lands on a table assumed empty, which is what lets it use COPY or a
|
|
87
|
+
plain multi-row INSERT, neither of which can express `ON CONFLICT`.
|
|
90
88
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
89
|
+
**`"insert"` (default)** keeps that fast path, so a row already sitting there surfaces as a real precondition
|
|
90
|
+
failure. **Use `"upsert"` only** when the emptiness assumption does not hold — this table legitimately receives
|
|
91
|
+
locally-**derived** provisional rows (a local trigger on another synced table writes a row here that the server
|
|
92
|
+
independently creates too) that a backfill could land on top of. It then takes the conflict-tolerant applier, at the
|
|
93
|
+
cost of the faster path. Declare the exception where it lives; never weaken the default repo-wide.
|
|
95
94
|
|
|
96
95
|
## Managed fields are server-assigned — never send them
|
|
97
96
|
|
|
@@ -128,31 +127,39 @@ that is not a writable (projected) column splits into exactly two cases:
|
|
|
128
127
|
The rule that follows: **write a server-only (omitted) column outside the sync rail** — a server-side
|
|
129
128
|
`UPDATE`, a trigger, or a managed field (`governance.managedFields`); the route rejects it in a payload.
|
|
130
129
|
|
|
131
|
-
##
|
|
130
|
+
## Local indexes are opt-in — your server's indexes are NOT mirrored
|
|
132
131
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
132
|
+
The local store renders a synced table's primary key and nothing else: server indexes serve server loads and many
|
|
133
|
+
cover projected-away columns. A client read that needs one declares it — `clientProjection: { localIndexes: [{ name:
|
|
134
|
+
"cards_due_at_idx", columns: ["dueAt"] }] }`, an ascending btree over projected columns (`unique?` optional), refused
|
|
135
|
+
at registry-build time if a column is unknown or omitted or a name repeats. Index only what the **client** scans (a
|
|
136
|
+
due window over 100k local-store rows: ~13 ms sequential vs ~0.1 ms indexed); each index costs write time per batch.
|
|
137
|
+
|
|
138
|
+
## Read-path filtering: `customPredicate` compiles to a predicate AST, not SQL
|
|
139
|
+
|
|
140
|
+
A table's `shape.rowFilter.customPredicate` is compiled by the **control plane** at shape creation — once per
|
|
141
|
+
(shape, subject), not per request — and posted to the Circuits engine as a **predicate AST**. No SQL text is
|
|
142
|
+
involved: build the predicate with the `p.*` builders over the table's **real Drizzle columns**, and
|
|
143
|
+
request-derived values ride as typed JSON scalars.
|
|
137
144
|
|
|
138
145
|
```ts
|
|
139
|
-
function widgetsReadFilter(claims) {
|
|
146
|
+
function widgetsReadFilter(claims: JwtClaims): Predicate | null {
|
|
140
147
|
if (isAdmin(claims)) return null; // null = no filter (all rows visible)
|
|
141
|
-
if (!claims.sub) return
|
|
142
|
-
return
|
|
148
|
+
if (!claims.sub) return DENY_ALL_PREDICATE; // the deny-all sentinel (no rows visible)
|
|
149
|
+
return p.eq(widgets.ownerId, claims.sub);
|
|
143
150
|
}
|
|
144
151
|
```
|
|
145
152
|
|
|
146
|
-
|
|
147
|
-
`
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
153
|
+
The builders are `p.eq`/`p.ne`/`p.lt`/`p.lte`/`p.gt`/`p.gte`, `p.like`/`p.notLike`, `p.isNull`/`p.isNotNull`,
|
|
154
|
+
`p.and`/`p.or`/`p.not`, and `p.in`/`p.notIn` over a `p.subquery` (below) — namespaced so they never collide with
|
|
155
|
+
`drizzle-orm`'s `eq`/`and`/`or`. Every comparison is checked against the column's own TypeScript type, so a mistyped
|
|
156
|
+
enum label, a `null` against a NOT NULL column, or a `jsonb`/`Date` column with no scalar wire form is a **compile
|
|
157
|
+
error**. **No `::text` casts** — values are typed JSON scalars; render a `Date` as the column stores it, as a string.
|
|
151
158
|
|
|
152
159
|
**Inline (all-in-one `defineSyncTable`) — `rowFilter` as a function of the columns.** The example above
|
|
153
160
|
assumes the table is built _elsewhere_. Declaring a table and its filter in **one** call, the table object
|
|
154
|
-
does not exist yet — so
|
|
155
|
-
|
|
161
|
+
does not exist yet — so give `shape.rowFilter` a **function of the built columns** (the typed columns `extras`
|
|
162
|
+
gets) rather than falling back to column-name strings:
|
|
156
163
|
|
|
157
164
|
```ts
|
|
158
165
|
defineSyncTable({
|
|
@@ -160,50 +167,50 @@ defineSyncTable({
|
|
|
160
167
|
makeColumns: () => ({ id: uuid("id").primaryKey(), ownerId: uuid("owner_id") }),
|
|
161
168
|
shape: {
|
|
162
169
|
rowFilter: (columns) => ({
|
|
163
|
-
|
|
170
|
+
customPredicate: (claims) => (claims.sub ? p.eq(columns.ownerId, claims.sub) : DENY_ALL_PREDICATE),
|
|
164
171
|
}),
|
|
165
172
|
},
|
|
166
173
|
});
|
|
167
174
|
```
|
|
168
175
|
|
|
169
|
-
The column callback is the only authoring form. **
|
|
170
|
-
|
|
171
|
-
|
|
176
|
+
The column callback is the only authoring form. **Say deny explicitly:** a `customPredicate` returning `null` means
|
|
177
|
+
_no filter — every row visible_, so an owner filter returning `null` for "no claim" exposes every row.
|
|
178
|
+
`DENY_ALL_PREDICATE` is the deny, recognised by reference: the control plane declines to create the shape at all, so
|
|
179
|
+
a denied subject holds no stream. It must also be **pure** (called per shape creation, and probed with empty claims
|
|
180
|
+
to detect claims-dependence), and a `rowFilter` restricting nothing — no `customPredicate`, no `columns` allow-list
|
|
181
|
+
— **throws at definition time** rather than compiling to a shape with no subject test.
|
|
172
182
|
|
|
173
|
-
## Cross-table filters:
|
|
183
|
+
## Cross-table filters: `p.subquery` over another table's column
|
|
174
184
|
|
|
175
|
-
A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
variant share one definition (the read-path twin of the membership RLS predicate):
|
|
185
|
+
A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customPredicate` whose
|
|
186
|
+
test is a **subquery over another table**. `p.subquery(projectedColumn, where?)` names the inner set by the column it
|
|
187
|
+
projects, so there is no table name to get wrong and no way to project a column that table does not have. Factor it
|
|
188
|
+
into a helper the read filter and any narrower variant share (the read-path twin of the membership RLS predicate):
|
|
180
189
|
|
|
181
190
|
```ts
|
|
182
|
-
//
|
|
183
|
-
function memberContainers(subject: string):
|
|
184
|
-
return
|
|
191
|
+
// Uncorrelated by construction: the inner `where` reads the membership table's own columns only.
|
|
192
|
+
function memberContainers(subject: string): SubqueryRef<string> {
|
|
193
|
+
return p.subquery(membership.containerId, p.eq(membership.memberId, subject));
|
|
185
194
|
}
|
|
186
195
|
|
|
187
|
-
function widgetsReadFilter(claims: JwtClaims):
|
|
188
|
-
if (!claims.sub) return
|
|
189
|
-
return
|
|
196
|
+
function widgetsReadFilter(claims: JwtClaims): Predicate {
|
|
197
|
+
if (!claims.sub) return DENY_ALL_PREDICATE; // no claim → deny (NOT null, which would expose every row)
|
|
198
|
+
return p.in(widgets.containerId, memberContainers(claims.sub));
|
|
190
199
|
}
|
|
191
200
|
```
|
|
192
201
|
|
|
193
|
-
What the
|
|
194
|
-
|
|
195
|
-
**
|
|
196
|
-
|
|
197
|
-
`where`
|
|
198
|
-
|
|
199
|
-
(no self-serve toggle yet). Combine with the function form when the table is defined all-in-one: the row's
|
|
200
|
-
own column comes from `(columns) => …`, the foreign table is imported built.
|
|
202
|
+
What the AST form buys: columns stay rename-safe and existence-checked, the projected column's type rides on the
|
|
203
|
+
`SubqueryRef` so `p.in` refuses an outer column it cannot be compared with, and the engine maintains the inner set
|
|
204
|
+
**incrementally and shares it across every shape referencing the same subquery** — an entitlement-shaped membership
|
|
205
|
+
costs one index, not one per shape. Two constraints: `IN` is **single-column** (no composite `(a, b) IN (…)`), and the
|
|
206
|
+
subquery stays **uncorrelated** — its `where` never references the outer row. Combine with the function form when the
|
|
207
|
+
table is defined all-in-one: the row's own column comes from `(columns) => …`, the foreign table is imported built.
|
|
201
208
|
|
|
202
209
|
## RLS: derive read and write from the same Drizzle columns
|
|
203
210
|
|
|
204
|
-
Authorization runs in two engines (Postgres RLS for writes, the
|
|
205
|
-
the **same Drizzle columns**, so a rename or typo can never make a
|
|
206
|
-
versa):
|
|
211
|
+
Authorization runs in two engines (Postgres RLS for writes, the shape predicate the Circuits engine
|
|
212
|
+
evaluates for reads). Build both from the **same Drizzle columns**, so a rename or typo can never make a
|
|
213
|
+
row readable-but-unwritable (or vice versa):
|
|
207
214
|
|
|
208
215
|
- Common shapes: `buildSupabaseOwnerOrAdminNativePolicies({ role, ownerColumn })` and
|
|
209
216
|
`buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })`. They take **real
|
|
@@ -217,17 +224,18 @@ versa):
|
|
|
217
224
|
SECURITY DEFINER membership helper, a `current_setting('request.jwt.claims')` admin check), and inline that
|
|
218
225
|
predicate rather than referencing a not-yet-created function. For "compare OLD vs NEW" rules RLS cannot
|
|
219
226
|
help (`WITH CHECK` sees only NEW, `USING` only OLD) — use a `BEFORE UPDATE` trigger.
|
|
220
|
-
- **Do not hand-write the read half — every policy family ships its read-path mirror.**
|
|
221
|
-
|
|
222
|
-
`
|
|
223
|
-
(
|
|
224
|
-
`
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
227
|
+
- **Do not hand-write the read half — every policy family ships its read-path mirror.** The sync engine cannot read
|
|
228
|
+
RLS, so the shape predicate re-derives the same visible set in JS from the same declaration:
|
|
229
|
+
`buildOwnershipShapePredicate`, `buildOwnerOrAdminShapePredicate` (admin → `null`, mirroring the policy's bypass
|
|
230
|
+
branch), `buildMembershipShapePredicate` (pass the **same** options object you gave the policy builder), and
|
|
231
|
+
`buildGrantScopeAccessShapePredicate` (bypass grant → `null` too; bare `resolveGrantScopeIds` +
|
|
232
|
+
`buildGrantScopeShapePredicate` cannot see it). Each takes the column plus the claims; return it straight from
|
|
233
|
+
`customPredicate` — they deny with `DENY_ALL_PREDICATE`, so the filter probes claims-dependent.
|
|
234
|
+
- Two mirror properties: they cover **SELECT only** (write-gate branches stay with the
|
|
235
|
+
INSERT/UPDATE/DELETE policies), and the two surfaces express containment in **different forms on
|
|
236
|
+
purpose** — RLS emits `= ANY(ARRAY(select …))` for the InitPlan/index-scan discipline, the read half a
|
|
237
|
+
first-class `p.in` over a `p.subquery` the engine maintains incrementally and shares between shapes. (A
|
|
238
|
+
grant set lives in the JWT, not a table, so that mirror is an `OR` of equalities instead.)
|
|
231
239
|
|
|
232
240
|
Give drizzle-kit `entities: { roles: { provider: "supabase" } }` in `drizzle.config.ts` so the Supabase roles
|
|
233
241
|
(`authenticated`/`anon`/`service_role`/…) are treated as externally managed — referenced in a policy's `to:`,
|
|
@@ -235,12 +243,12 @@ never created or dropped.
|
|
|
235
243
|
|
|
236
244
|
## Composition obligations: two correct policies can still break an invariant
|
|
237
245
|
|
|
238
|
-
The registry keeps ONE table's read filter and write policy from drifting. A domain invariant usually spans
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
246
|
+
The registry keeps ONE table's read filter and write policy from drifting. A domain invariant usually spans several
|
|
247
|
+
tables and rails, and no registry feature can see that composition. Worked example: an invite table's RLS grants an
|
|
248
|
+
offering-scoped teacher INSERT; an acceptance worker then mints a membership row. Each policy is correct alone;
|
|
249
|
+
together they violate "this offering only ever has one member". The worker's semantics are invisible to per-table
|
|
250
|
+
declarations, so the obligation is permanently the consumer's. When you add a worker, route, or trigger that writes
|
|
251
|
+
rows as a CONSEQUENCE of other rows:
|
|
244
252
|
|
|
245
253
|
- List the invariants the OUTPUT table participates in, not just the input's — the output is where the
|
|
246
254
|
violation lands — and for each ask whether the composed path enforces it or merely assumes the input row's
|
|
@@ -255,10 +263,10 @@ route, or trigger that writes rows as a CONSEQUENCE of other rows:
|
|
|
255
263
|
## Provision the apply function from the registry
|
|
256
264
|
|
|
257
265
|
The write path applies through one in-database PL/pgSQL function, `pgxsinkit_apply_mutations`. Generate its
|
|
258
|
-
drizzle-kit migration with the `pgxsinkit-generate` CLI (a `bin` of `@pgxsinkit/server`) and apply it through
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
266
|
+
drizzle-kit migration with the `pgxsinkit-generate` CLI (a `bin` of `@pgxsinkit/server`) and apply it through your
|
|
267
|
+
normal migration flow; it is **deny-by-default** (see `deploying` for `--grant-execute-to`). It and the audit/version
|
|
268
|
+
column DEFAULTs both **call** `public.pgxsinkit_clock_us()`, so the `--utilities` migration installing that clock
|
|
269
|
+
must be **first in the chain** (hence the early-sorting name):
|
|
262
270
|
|
|
263
271
|
```bash
|
|
264
272
|
bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
|
|
@@ -269,13 +277,13 @@ bun run pgxsinkit-generate --utilities \
|
|
|
269
277
|
|
|
270
278
|
## Multi-client: one authoritative registry, readonly projections (ADR-0025)
|
|
271
279
|
|
|
272
|
-
When the same table is `readwrite` for one client and `readonly` for another, `mode` is **per-client**, not
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
280
|
+
When the same table is `readwrite` for one client and `readonly` for another, `mode` is **per-client**, not a
|
|
281
|
+
property of the table: define it **once** in an authoritative registry at its writable capability and project it per
|
|
282
|
+
client. `mode` is baked at `defineSyncTable` time and drives the overlay/journal machinery + the `_read_model` view,
|
|
283
|
+
so a hand-spread `{ ...entry, mode: "readonly" }` is **broken** (it keeps a view over overlay state the readonly
|
|
284
|
+
client never creates). `asReadonly` re-derives a true readonly entry — dropping the overlay/journal projection, the
|
|
285
|
+
view, and `conflictPolicy`/`governance`/`writeMode`, keeping columns, primary key, synced table, shape/row filter
|
|
286
|
+
and `rowClass`.
|
|
279
287
|
|
|
280
288
|
```ts
|
|
281
289
|
const authoritativeRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry }); // readwrite
|
|
@@ -287,12 +295,12 @@ assertReadContractPreserved(authoritativeRegistry, teacherRegistry, { label: "te
|
|
|
287
295
|
assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "learner" });
|
|
288
296
|
```
|
|
289
297
|
|
|
290
|
-
- **
|
|
291
|
-
table and stamps managed fields / reject-if-stale from the entry's write
|
|
292
|
-
writable entry. A claims-branching `
|
|
293
|
-
- A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group),
|
|
294
|
-
|
|
295
|
-
|
|
298
|
+
- **Run the server (apply function + control plane) off the authoritative registry** — the generated apply
|
|
299
|
+
function emits a branch per table and stamps managed fields / reject-if-stale from the entry's write
|
|
300
|
+
contract, so it must see the writable entry. A claims-branching `customPredicate` then serves every client.
|
|
301
|
+
- A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group), never
|
|
302
|
+
in the read contract — `assertReadContractPreserved` enforces it (it cannot see the `customPredicate` body,
|
|
303
|
+
so bump `rowFilter.revision` on a logic change).
|
|
296
304
|
- The full registry fingerprint differs between the writable and readonly variants — expected and fine:
|
|
297
305
|
it is client-local (guards each client's own store rebuild) and the server never sees it.
|
|
298
306
|
|
|
@@ -309,54 +317,43 @@ export const assessmentDefinition = defineSyncTable({ tableName: "assessment_def
|
|
|
309
317
|
export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentDefinition, {
|
|
310
318
|
as: "assessment_definition_admin_summary", // distinct local table + shapeKey
|
|
311
319
|
columns: ["offeringId", "assessmentType", "title", "state"], // typed subset of owner keys; PK always kept
|
|
312
|
-
rowFilter: (c) => ({
|
|
320
|
+
rowFilter: (c) => ({ customPredicate: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
|
|
313
321
|
});
|
|
314
322
|
```
|
|
315
323
|
|
|
316
324
|
- It **owns no table**: its `table` IS the owner's, so nothing new is migrated and nothing leaks into a
|
|
317
325
|
drizzle-kit schema barrel. Only its `localTable` (named `as`) and shape are its own.
|
|
318
|
-
- `columns` is a typed subset of the owner's keys
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
`serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and `columns`, and must be disjoint from
|
|
352
|
-
`columns` and the PK — each is a loud error. **No inheritance — enforced.** A projection does NOT inherit its owner's `serverProjection`: an inherited
|
|
353
|
-
transform whose input column is absent from the projection's fetch list reads `undefined` and fails OPEN.
|
|
354
|
-
Since a bare projection over a redacting owner would then egress the RAW row, `defineReadProjection` THROWS
|
|
355
|
-
when the owner declares an egress `rowTransform` unless the projection declares its posture — its own
|
|
356
|
-
`serverProjection` (usually the same fn) + `serverOnlyColumns`, or the explicit opt-out `serverProjection:
|
|
357
|
-
"unredacted"` (only after confirming the kept columns leak nothing; it attaches no transform but records the
|
|
358
|
-
raw-egress decision at the definition site). `"unredacted"` over a transform-less owner is itself rejected — a
|
|
359
|
-
stale opt-out would pre-authorize a leak if the owner later gained one.
|
|
326
|
+
- `columns` is a typed subset of the owner's keys; the local table carries the owner's real per-column types
|
|
327
|
+
restricted to those keys, so a row typechecks by property key with no casts. The PK is always kept **at
|
|
328
|
+
runtime** but the type is a safe **under-claim** — list a PK column in `columns` to read it typed. The
|
|
329
|
+
subset becomes the shape's **emitted** column set, so an omitted (heavy) column is **never streamed**.
|
|
330
|
+
- The physical table is **derived** from the owner — you never name a source string. The `rowFilter`
|
|
331
|
+
callback receives the OWNER's full columns: the engine matches on columns the shape does not emit, so the
|
|
332
|
+
predicate may reference a column the subset omits.
|
|
333
|
+
- It is **readonly**; register it under its own key in the authoritative registry and in the reading client's.
|
|
334
|
+
RLS for its reads lives on the **owner** (a projection adds no DDL), so its `customPredicate` must be a
|
|
335
|
+
subset of what that RLS allows. The control plane resolves each shape by `shapeKey`, so owner and
|
|
336
|
+
projection coexist over one physical table.
|
|
337
|
+
|
|
338
|
+
### Redacting projection: keep the secret out of the row, not out of the response
|
|
339
|
+
|
|
340
|
+
**Prefer redacting in Postgres.** Model a "window" over a keyed table as SCHEMA where you can: compute the
|
|
341
|
+
redacted value into its own column (generated or trigger-maintained), sync THAT, and split the projections by
|
|
342
|
+
predicate on the control flag — the flag never reaches the client and the raw value never enters storage.
|
|
343
|
+
|
|
344
|
+
`serverProjection` (an egress `rowTransform`) is the escape hatch when the decision is per-row and cannot be
|
|
345
|
+
pre-computed. It runs **at the stream edge**, per request: the edge rewrites every row of the JSON long-poll
|
|
346
|
+
body, then strips each row to the client keep-set — which takes `serverOnlyColumns` (fetched so the transform
|
|
347
|
+
can read them) off the wire. Costs, confined to shapes that declare one: `claims` are `{ sub }` only (richer
|
|
348
|
+
claims belong in `rowFilter.customPredicate`); the shape is private-tier (`scope` + `rowTransform` is refused)
|
|
349
|
+
and answered `cache-control: private, no-store`; JSON long-poll only — an SSE read gets `406`.
|
|
350
|
+
|
|
351
|
+
Guards fire at definition time: `serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and
|
|
352
|
+
`columns`, disjoint from `columns` and the PK. **No inheritance — enforced:** `defineReadProjection` THROWS
|
|
353
|
+
when the owner declares a `rowTransform` unless the projection states its own (usually the same fn, plus
|
|
354
|
+
`serverOnlyColumns` for its control flags) or opts out with the literal `serverProjection: "unredacted"` —
|
|
355
|
+
only after confirming the kept columns leak nothing. `"unredacted"` over a transform-less owner is itself
|
|
356
|
+
rejected, so a stale opt-out cannot pre-authorize a leak the owner gains later.
|
|
360
357
|
|
|
361
358
|
## Classify rows and assert registry invariants (ADR-0052)
|
|
362
359
|
|
|
@@ -374,9 +371,9 @@ assertRegistryInvariant(registry, {
|
|
|
374
371
|
name: "team-scoped rows are invisible to an anonymous caller",
|
|
375
372
|
appliesTo: ["team-scoped"], // classes (or a predicate); an undeclared class / zero matches throws
|
|
376
373
|
claimsFixtures: { anonymous: {}, member: { sub: memberId }, admin: adminClaims },
|
|
377
|
-
holds: ({ fixtureName,
|
|
374
|
+
holds: ({ fixtureName, readPredicate, renderedPolicies }) =>
|
|
378
375
|
fixtureName !== "anonymous" ||
|
|
379
|
-
(
|
|
376
|
+
(deniesAllRows(readPredicate) && renderedPolicies.every((policy) => policy.using !== "true")) ||
|
|
380
377
|
"anonymous is not denied on one of the two surfaces", // reported as `entry (fixture): reason`
|
|
381
378
|
});
|
|
382
379
|
```
|
|
@@ -384,26 +381,26 @@ assertRegistryInvariant(registry, {
|
|
|
384
381
|
So a table added next month cannot inherit the obligation invisibly (omit `rowClasses` and `rowClass` is
|
|
385
382
|
unconstrained, as the bare registry-map form always is). Projections carry the class (`asReadonly`,
|
|
386
383
|
`asEphemeral`; `defineReadProjection` inherits the owner's, overridable). Each cell gets that persona's
|
|
387
|
-
|
|
388
|
-
unfiltered), `renderedPolicies` the table's RLS as inline
|
|
389
|
-
ALL failing cells aggregate into one error.
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
the
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
384
|
+
RESOLVED artifacts — `readPredicate` is the entry's `customPredicate` output for those claims, exactly what
|
|
385
|
+
the control plane compiles into the shape (`null` = unfiltered), `renderedPolicies` the table's RLS as inline
|
|
386
|
+
SQL — so one predicate covers both surfaces and ALL failing cells aggregate into one error. Match on STRUCTURE
|
|
387
|
+
(`deniesAllRows`, the `isXPredicate` guards), never a rendered string. `rowClass` is authoring metadata,
|
|
388
|
+
deliberately in NEITHER fingerprint (classifying never wipes a cache); the **lock** carries it, so losing a
|
|
389
|
+
class is a `risky` diff. It complements `RowFilterSpec.revision`: only `revision` makes a `customPredicate`
|
|
390
|
+
logic change move the fingerprint (rebuilding the cache, resetting the subscription), while the assertion
|
|
391
|
+
renders that logic — for the fixtures you hand it, and no others.
|
|
392
|
+
|
|
393
|
+
## Storage declaration: `storage.backend`, `durability`, `engine`, `build` (browser stores)
|
|
394
|
+
|
|
395
|
+
The registry carries the browser store's storage contract — `SyncRegistryDefinition.storage`, `{ backend?: "opfs" |
|
|
396
|
+
"idbfs"; durability?: "relaxed" | "strict"; engine?: { module }; build?: "c" | "pgrust" }` (`engine`, `build`:
|
|
397
|
+
[references/storage-engine-and-build.md](references/storage-engine-and-build.md)). It lives on the registry, not on a minting surface, worker entry, or attach site, because every property follows the DATA: one declaration
|
|
400
398
|
binds every open of every store minted from that registry, so no tab can disagree with another.
|
|
401
399
|
|
|
402
|
-
- **`backend`** (default `"opfs"`) — the normal boot everywhere: the toolkit probes OPFS sync-access at boot
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
only decision you declare is whether to force idb.
|
|
400
|
+
- **`backend`** (default `"opfs"`) — the normal boot everywhere: the toolkit probes OPFS sync-access at boot and
|
|
401
|
+
runs the `opfs-repacked` engine wherever handles are granted, falling back automatically to in-SharedWorker idbfs
|
|
402
|
+
(declared durability kept) only where the platform grants them nowhere. `backend: "idbfs"` is the one opt-out (no
|
|
403
|
+
probe, no election). Where the engine runs is never a knob; the only decision you declare is whether to force idb.
|
|
407
404
|
- **`durability`** (default `"relaxed"`) — relaxed returns the local write before the physical flush and
|
|
408
405
|
schedules it asynchronously; `"strict"` awaits the flush per commit. Relaxed is right for a sync toolkit
|
|
409
406
|
(the server is the source of truth, and the loss window is one recent action); declare `"strict"` only for
|
|
@@ -413,18 +410,21 @@ It scopes the **browser** store only; Node mints stay `file://` and export clone
|
|
|
413
410
|
|
|
414
411
|
## Consistency groups: scope them to the joined cluster
|
|
415
412
|
|
|
416
|
-
`consistencyGroup` binds tables
|
|
417
|
-
a reader never sees one grouped table advanced past another for
|
|
418
|
-
|
|
413
|
+
`consistencyGroup` binds tables into one subscription that commits **atomically at boot and catch-up
|
|
414
|
+
alignment** — a reader never sees one grouped table advanced past another for a transaction the group caught
|
|
415
|
+
up on. Each member is its own stream; the group commits when **every** member's most recent response asserted
|
|
416
|
+
up-to-date (offsets are per-stream, so the gate is that predicate, plus the engine barrier on each alignment
|
|
417
|
+
generation's first commit). Live deliveries commit per response, so two halves of one transaction can land a
|
|
418
|
+
few milliseconds apart — a documented window (backlog 0014), not a guarantee. Default is none — a per-table
|
|
419
|
+
singleton committing on its own. Three scoping rules:
|
|
419
420
|
|
|
420
421
|
1. **Group the transactionally-joined cluster** — tables written together in one server transaction and
|
|
421
|
-
rendered joined (FK parent + children); that is what the atomic
|
|
422
|
+
rendered joined (FK parent + children); that is what the atomic commit protects. If the app otherwise
|
|
422
423
|
needs post-ack re-reads to hide half-applied transactions, the tables belong in a group.
|
|
423
|
-
2. **Quiet members are affordable.**
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
separate groups or stay singletons.
|
|
424
|
+
2. **Quiet members are affordable.** Every `204` long-poll timeout re-asserts up-to-date, so a rarely-written
|
|
425
|
+
reference table never holds its group behind a stale watermark — keep lookup tables in their natural group.
|
|
426
|
+
3. **Don't group "everything".** A group commits at the pace of its slowest member; unrelated clusters go
|
|
427
|
+
in separate groups or stay singletons.
|
|
428
428
|
|
|
429
429
|
All members of a group must agree on `subscription`, `retention`, `writeMode` (or the registry rejects it).
|
|
430
430
|
|
|
@@ -478,8 +478,8 @@ export const registry = defineSyncRegistry({
|
|
|
478
478
|
- Trying to write an `omitColumns` (server-only) column from a client payload — the write route
|
|
479
479
|
**400-rejects** it (an unknown typo is instead silently dropped, surfaced by a per-process `console.warn`);
|
|
480
480
|
write them outside the sync rail (a server `UPDATE`, a trigger, or a managed field).
|
|
481
|
-
- In a `
|
|
482
|
-
|
|
481
|
+
- In a `customPredicate`: returning `null` for "no claim" (that is _every row_ — return `DENY_ALL_PREDICATE`), a
|
|
482
|
+
`rowFilter` that restricts nothing (throws), a correlated `p.subquery`, or SQL text where a `p.*` builder exists.
|
|
483
483
|
- A multi-dimensional array column, an array PK, or a managed field on an array column — each fails at
|
|
484
484
|
generate time; single-dimension arrays are fully supported on both paths.
|
|
485
485
|
- Letting the read filter and RLS policy diverge instead of building both from the same Drizzle columns.
|
|
@@ -495,5 +495,5 @@ export const registry = defineSyncRegistry({
|
|
|
495
495
|
client-supplied and can lie), a non-strict object payload (the registry throws), projecting a registry
|
|
496
496
|
without re-declaring `streams`, evolving a payload incompatibly, or a `.refine` change with no `revision`.
|
|
497
497
|
|
|
498
|
-
For the surrounding model (two paths, one write path, fail-closed
|
|
499
|
-
from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
|
|
498
|
+
For the surrounding model (two paths, one write path, the fail-closed control plane and edge), load the
|
|
499
|
+
`core` skill from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# `storage.engine` and `storage.build`
|
|
2
|
+
|
|
3
|
+
Both are part of the store's **identity**, like `backend`: one declaration binds every open of every store
|
|
4
|
+
minted from the registry, and changing either means minting a fresh store under a fresh path — never
|
|
5
|
+
reopening an existing one.
|
|
6
|
+
|
|
7
|
+
## `storage.engine` — a different store engine
|
|
8
|
+
|
|
9
|
+
`storage: { engine: { module: "/store-engine/factory.js" } }`. `module` is an absolute or origin-relative module
|
|
10
|
+
URL. pgxsinkit `import()`s it in whichever scope is minting and takes its **default export** — or, failing
|
|
11
|
+
that, a named `createStore` — as the store factory: `(storePath: string, backendOverride?: "memory") =>
|
|
12
|
+
Promise<PgwasmClient>`, the same signature as `defineSyncWorker`'s `createStore` option. That module then
|
|
13
|
+
answers for the store instead of the built-in `createPgwasmClient`. Absent (the default) is the built-in
|
|
14
|
+
store. The module owns its own assets (derive them from `import.meta.url`), its storage layout under the store
|
|
15
|
+
path, and its environment requirements; serve it same-origin. A module that will not load, or exports no
|
|
16
|
+
factory, fails the mint loudly naming the module — it never falls back to the built-in store.
|
|
17
|
+
Full prose: <https://pgxsinkit.github.io/concepts/worker-mode/#declaring-a-different-store-engine>.
|
|
18
|
+
|
|
19
|
+
## `storage.build` — the Postgres build
|
|
20
|
+
|
|
21
|
+
`storage: { build: "c" }`. `build` names the Postgres build that owns every store minted from the registry:
|
|
22
|
+
`"c"` (the default, `cBuild` from `@pgxsinkit/pgwasm-c`) or `"pgrust"`. A data directory belongs to the build
|
|
23
|
+
that created it, so a different build is a different store. The declaration only names the build; the app
|
|
24
|
+
supplies the build itself as code (the `build` option of `createSyncClient`, `defineSyncWorker` and
|
|
25
|
+
`createPgwasmClient`), and a supplied or adopted build that is not the declared one fails with
|
|
26
|
+
`StorageBuildMismatchError` before any store is touched. A bare table map declares it with
|
|
27
|
+
`attachSyncRegistryStorage`. It may also travel on the wire with a dynamic declaration; an explicit
|
|
28
|
+
disagreement between the two is a `StorageDeclarationRefusedError`. Leave it at the default unless the app
|
|
29
|
+
runs another build. Full prose: <https://pgxsinkit.github.io/concepts/postgres-builds/>.
|