@ultimat3/entity 31.55.0 → 31.57.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/CLAUDE.md CHANGED
@@ -138,13 +138,13 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
138
138
  - **Tenancy applies to writes in two places**: the plan bounds WHICH rows; `assertRowTenant`
139
139
  judges the VALUE at every write seam — refuse, never stamp. †
140
140
  - **A reference stays inside its tenant** (`sameTenantOf`, `describe.ts`, at describe time): `sameTenant` is `null` on the record and ABSENT on the column otherwise (the hash). `entity()` never resolves a thunk at declaration. Memory (`memory-same-tenant.ts`) refuses only a target FOUND elsewhere. The suite, `same-tenant.live.test.ts`.
141
- - **`lock`/`lockKey`**: optional on `Repo`, required on `Table` (`table-locks.ts`, `X_LOCK_UNSUPPORTED`); `pg-lock.ts`, `memory-lock.ts` (`update`/`delete` queue too, the filtered writes do not), one tenant derivation (`lock-key.ts`, via `readPlan`). the suite, `pg-lock-attribution.test.ts`, `lock.live.test.ts`, `lock-seams.test.ts`. Why: `docs/history/entity.md` (2026-11-02).
141
+ - **`lock`/`lockKey`** (+`holdKey`, `hold-key*.test.ts`): optional on `Repo`, required on `Table` (`table-locks.ts`, `X_LOCK_UNSUPPORTED`); `pg-lock.ts`, `memory-lock.ts` (`update`/`delete` queue too, the filtered writes do not), one tenant derivation (`lock-key.ts`, via `readPlan`). the suite, `pg-lock-attribution.test.ts`, `lock.live.test.ts`, `lock-seams.test.ts`. Why: `docs/history/entity.md` (2026-11-02).
142
142
  - **`crossTenant(reason, fn)` is the ONE way to read across tenants** — an `asyncContext` scope from
143
143
  core (`scripts/async-context-guard.ts`), `CROSS_TENANT_SCOPE` (`tenancy:cross`) proven at the call
144
144
  and at every plan (`X_TENANCY_CROSS_DENIED`), refused outside a request, blank reason `X_INVARIANT`.
145
145
  - **`deleteWhere` / `updateWhere` (and `updateWhereReturning`, the same write answering its rows: `pg-driver.ts`'s `filteredPatch` is the shared half, a bounded Postgres transaction handles a drifting pre-write count; count-only stores and a `Repo` without the method refuse before mutation, `returningUnsupported`) are the only filtered writes** — a chain's `updateAll`/`deleteAll` (`query-write.ts`) IS one, its predicates in `FilteredWriteOptions.where`, one plan (`write-where.ts`). `updateMany`/`insertAllCount`/`upsertAllCount`/`copyAll` are `Repo`-optional with typed-handle fallbacks; every wrapper (sealed, append-only, view, mirror, observer, memory-observed) handles each (`query-write-wrappers.test.ts`). Empty filter `X_WRITE_UNFILTERED`,
146
146
  empty patch `X_PATCH_EMPTY` (undefined values dropped first); soft delete respected; both return a
147
- count; a JS-only invariant is judged
147
+ count; a JS-only invariant is judged only when the patch can move it (`judgedRules`, fails closed, all drivers),
148
148
  in the statement's transaction (`judged-write.ts`), refused past `MAX_ASSERTED_ROWS`. Full rule: `docs/history/entity.md`.
149
149
  - **Sweep 5b seams** (`read-wrappers.test.ts`, `history-purge.test.ts`): `Repo.latestBy?`/`aggregates?`/`lockKeys?` optional, each forwarded by sealed (refuses sealed group/order/measure/filter columns, opens rows), search-repo and memory-observed; `countBy`'s 3rd arg `{ where }` forwarded everywhere. `defineDriver` composes filtered `countBy` and `aggregates` from existing capabilities; a versioned entity there takes the judged path, one CAS store write per row. `update(id)` calls `assertVersionedUpdate` in all three drivers. `purgingHistory` (`history-purge.ts`) is the only door out of a history table. `IndexDef` carries `expression`/`orders`/`include`/`operatorClass` (types.ts; checked in `declared-index-keys.ts`, rendered by db); one covering rule for implicit indexes (`coveringIndexOf`). Files: `latest-by*.ts`, `measures.ts`, `text-contains.ts`, `version-lock*.ts`, `lock-key.ts`, `counter-observed.ts`, `all-truncated.ts`.
150
150
  - **`text().collate('C')`** (`sealed-column.ts`'s `makeTextColumn`): `ColumnMeta.collation`, `'C'` only (else `X_INVARIANT_VIOLATED`), projected on `ColumnDescription.collation` only when declared; db renders/diffs it. `@ultimat3/query`'s `live-collation.ts` exempts it from the live-order warning.
package/README.md CHANGED
@@ -941,6 +941,7 @@ await db.accounts.lockKeys(['acct:' + from, 'acct:' + to], async (tx) => { /*
941
941
  | `andWhere(col, 'contains', term)` on `text()`/`char()` | case-insensitive substring (`ilike`, the term bound and escaped). Served by a trigram index only — declare `indexes: [{ on: ['<col>'], using: 'gin', operatorClass: 'gin_trgm_ops' }]` (`trigramDeclaration(col)`); the plan sweep reports one without it |
942
942
  | `indexes:` key parts | four optional fields beside `on`, each absent by default so no existing index name or schema hash moves (`declared-index-keys.ts`, refused at `entity()` with `X_INVARIANT_VIOLATED`): `expression: 'lower(email)'` — the ONE key is that SQL over physical columns, `on` names the columns it reads (a concurrent `refreshView` refuses it as its unique key); `orders: ['desc', null]` — a direction per key, btree only, never beside `order`; `include: ['title']` — INCLUDE payload, btree only; `operatorClass: 'gin_trgm_ops'` — needs `using: 'gin'`. A foreign-key index another index already leads with is still emitted — dropping it would make an existing app's next `x db gen` remove an index the database holds — and is listed on `RegistryEntry.coveredIndexes` (`CoveredIndex`: the index and the one that covers it; `coveredImplicitIndexes`, `tenant-index.ts`) |
943
943
  | `lockKeys(keys, fn)` | `lockKey`'s tenancy and hashing per key, deduped, sorted, at most `MAX_LOCK_KEYS` (64), one transaction; `X_LOCK_UNSUPPORTED` for a repository without it |
944
+ | `holdKey(key)` · `holdKeys(keys)` | `lockKey`'s / `lockKeys`' lock taken in the caller's open transaction, held to its root's end (or a rollback to a savepoint it was taken in): no callback, no savepoint, one statement. Outside a transaction `X_LOCK_HOLD_OUTSIDE_TX`; `X_LOCK_UNSUPPORTED` for a repository without them |
944
945
  | `entity({ version: 'lockVersion' })` | an optimistic lock on an `integer().default(0)` column: `update(id, { …patch, lockVersion: row.lockVersion })` conditions on it and increments it — moved since the read is `X_ENTITY_STALE` (409), omitted is `X_ENTITY_VERSION_INVALID`. `updateMany` checks every row (one stale row refuses the batch). `updateWhere`/`updateAll`/`transition`/soft delete increment it and may not set it (compare-and-set goes in the filter: `where({ id, lockVersion: 3 })`). `upsertAll` with `onMatch: 'update'` is refused, `'nothing'` allowed. A mutator carries the version as input |
945
946
  | `.all()` | one page; when a next page existed and the chain named no `limit()`, dev and test log `ALL_TRUNCATED` (`'entity.all.truncated'`) with the fix (`inBatches()` or `.limit(n)`) |
946
947
  | a `countedIn` child write | reports each parent whose count moved as an `entity.row` `update` (read back in the write's transaction, only while subscribed; `before` = the count moved back; a filter-pinned bulk write reports `before: null`, an unpinned one `entity.bulk` for the parent) — `counter-observed.ts` |
@@ -1711,7 +1712,10 @@ opts out; blank is `X_INVARIANT_VIOLATED`. A hand-written statement that must sc
1711
1712
  **A read-modify-write takes a lock.** `db.posts.lock(id, (row, tx) => …)` holds the row for the
1712
1713
  callback and `db.posts.lockKey(key, (tx) => …)` holds a key of this table and tenant. A transaction
1713
1714
  each, a savepoint inside an open one, and the lock lasts to the root COMMIT. `fn` writes with
1714
- `{ tx }`. A hand-written `Repo` without them answers `X_LOCK_UNSUPPORTED`.
1715
+ `{ tx }`. Inside `withTransaction`, where the caller owns the rollback, `db.posts.holdKey(key)`
1716
+ takes the same key lock with no savepoint: one statement, held to the root's end unless a
1717
+ savepoint it was taken in rolls back. A hand-written
1718
+ `Repo` without them answers `X_LOCK_UNSUPPORTED`.
1715
1719
  [The wiki](../../wiki/Entities-And-Migrations.md#locking-a-row-or-a-key).
1716
1720
 
1717
1721
  | Situation | Answer |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.55.0",
3
+ "version": "31.57.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,9 +45,9 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.55.0",
49
- "@ultimat3/db": "31.55.0",
50
- "@ultimat3/schema": "31.55.0",
51
- "@ultimat3/time": "31.55.0"
48
+ "@ultimat3/core": "31.57.0",
49
+ "@ultimat3/db": "31.57.0",
50
+ "@ultimat3/schema": "31.57.0",
51
+ "@ultimat3/time": "31.57.0"
52
52
  }
53
53
  }
@@ -6,7 +6,12 @@
6
6
  import { driverError, SQLSTATE } from '@ultimat3/db';
7
7
  import type { DriverAdvance } from './driver-kit-types';
8
8
  import type { DriverScope } from './driver-scope';
9
- import { assertedRowsTooMany, MAX_ASSERTED_ROWS } from './invariants';
9
+ import {
10
+ assertedRowsTooMany,
11
+ assertInvariants,
12
+ type Invariant,
13
+ MAX_ASSERTED_ROWS,
14
+ } from './invariants';
10
15
  import { mergedRow } from './memory-update';
11
16
  import { namedColumns } from './plan';
12
17
  import type { Tx } from './repo';
@@ -29,6 +34,8 @@ export interface CheckedUpdate<Row> {
29
34
  readonly references: (rows: readonly Row[]) => Promise<void>;
30
35
  /** Asked of every read's match count first: `updateWhereReturning`'s `returnedBound`. */
31
36
  readonly bound?: (matched: number) => void;
37
+ /** The invariants judged on each merged row: the ones the patch can move (`judged-write.ts`). */
38
+ readonly rules: readonly Invariant<Row>[];
32
39
  }
33
40
 
34
41
  /** What the write did: how many rows, and the rows as they were judged (for the search mirror). */
@@ -51,7 +58,8 @@ export const checkedUpdate = async <Row>(
51
58
  const { entity, raw } = scope;
52
59
  const { op, plan, patch, advance, narrowed, tx } = write;
53
60
  for (let attempt = 0; attempt <= MAX_CHECKED_RETRIES; attempt += 1) {
54
- // Every invariant, a SQL-expressible one too: a custom store enforces no CHECK.
61
+ // Every invariant the patch can move, a SQL-expressible one always: a custom store enforces no
62
+ // CHECK.
55
63
  const read = await raw.select({ plan, after: undefined, limit: MAX_ASSERTED_ROWS + 1, tx });
56
64
  const found = scope.checked(op, plan, read);
57
65
  write.bound?.(found.length);
@@ -61,7 +69,7 @@ export const checkedUpdate = async <Row>(
61
69
  const results = found.map((row) => mergedRow(entity, row, patch));
62
70
  for (const merged of results) {
63
71
  assertRowTenant(entity.$name, entity.$tenantColumn, op, merged);
64
- entity.$assert(merged);
72
+ assertInvariants(entity.$name, write.rules, merged);
65
73
  }
66
74
  await write.references(results);
67
75
  // The narrowed values the merge produced — the same for every row — so the store holds what
@@ -21,7 +21,14 @@ import {
21
21
  } from './driver-write-scope';
22
22
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
23
23
  import { notFound } from './errors';
24
- import { assertedRowsTooMany, MAX_ASSERTED_ROWS, returnedBound } from './invariants';
24
+ import {
25
+ assertedRowsTooMany,
26
+ assertInvariants,
27
+ type Invariant,
28
+ MAX_ASSERTED_ROWS,
29
+ returnedBound,
30
+ } from './invariants';
31
+ import { judgedRules } from './judged-write';
25
32
  import { mergedRow } from './memory-update';
26
33
  import { idPlan, namedColumns, singleKeyOf } from './plan';
27
34
  import type { FilteredWriteOptions, Repo, RepoOptions, Tx } from './repo';
@@ -107,7 +114,8 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
107
114
  * atomically (`DriverRepo.update`'s `advance`): a value the kit computed from a read would let a
108
115
  * second process's newer version be written over. `found` is the rows a won compare-and-set
109
116
  * compared against — the row as it stood when written, which `updateMany`'s rollback restores;
110
- * `cas` takes that path even with nothing to judge, so a CAS store always reports them.
117
+ * `cas` takes that path even with nothing to judge, so a CAS store always reports them. `rules`
118
+ * are the invariants judged: a filtered write's are the ones its patch can move (`judged-write.ts`).
111
119
  */
112
120
  const patchedRows = async (
113
121
  op: string,
@@ -115,6 +123,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
115
123
  patch: object,
116
124
  options: RepoOptions | undefined,
117
125
  cas = false,
126
+ rules: readonly Invariant<Row>[] = entity.$invariants,
118
127
  ): Promise<{ readonly written: number; readonly found: readonly Row[] | undefined }> => {
119
128
  const tx = scope.txOf(op, options);
120
129
  // Nothing to judge: no read-back and no cap — one store call, as Postgres sends one statement.
@@ -127,7 +136,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
127
136
  // A declared version lock is per row (`v = stored + 1`), which one store patch cannot say: the
128
137
  // judged path below, one write per row (`driver-versioned-write.ts`).
129
138
  const lock = versionOf(entity);
130
- const nothingToJudge = entity.$invariants.length === 0 && !movesReference;
139
+ const nothingToJudge = rules.length === 0 && !movesReference;
131
140
  if (nothingToJudge && lock === null && !(cas && raw.updateChecked !== undefined)) {
132
141
  // The search mirror asked for the rows: read them first, as the judged path does. Past the
133
142
  // judged bound they are not handed over — the mirror logs the write it could not name.
@@ -155,13 +164,14 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
155
164
  narrowed,
156
165
  tx,
157
166
  references,
167
+ rules,
158
168
  });
159
169
  if (sink !== undefined && checked.found.length > 0) {
160
170
  sink(await writtenBack(op, plan, checked.found, tx));
161
171
  }
162
172
  return { written: checked.written, found: checked.found };
163
173
  }
164
- // Every invariant, a SQL-expressible one too: a custom store enforces no CHECK.
174
+ // Every rule in `rules`, a SQL-expressible one always: a custom store enforces no CHECK.
165
175
  const found = scope.checked(
166
176
  op,
167
177
  plan,
@@ -173,7 +183,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
173
183
  const results = found.map((row) => mergedRow(entity, row, patch));
174
184
  for (const merged of results) {
175
185
  assertRowTenant(entity.$name, entity.$tenantColumn, op, merged);
176
- entity.$assert(merged);
186
+ assertInvariants(entity.$name, rules, merged);
177
187
  }
178
188
  await references(results);
179
189
  // The row each won write was conditioned on: what `updateMany`'s rollback restores.
@@ -194,12 +204,14 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
194
204
  if (sink !== undefined) sink(await writtenBack(op, plan, found, tx));
195
205
  return { written, found: won };
196
206
  };
207
+ /** A filtered write: judged by the rules its patch can move. */
197
208
  const patched = async (
198
209
  op: string,
199
210
  plan: QueryPlan,
200
211
  patch: object,
201
212
  options: RepoOptions | undefined,
202
- ): Promise<number> => (await patchedRows(op, plan, patch, options)).written;
213
+ ): Promise<number> =>
214
+ (await patchedRows(op, plan, patch, options, false, judgedRules(entity, patch))).written;
203
215
 
204
216
  /** Hard or soft, decided once so `delete(id)` and `deleteWhere` cannot drift apart. */
205
217
  const removed = (op: string, plan: QueryPlan, options: RepoOptions | undefined) =>
@@ -243,7 +255,8 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
243
255
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
244
256
  const tx = scope.txOf(op, options);
245
257
  const bound = (matched: number) => returnedBound(entity.$name, matched);
246
- const write = { op, plan, patch, ...shapeOf(patch), tx, references, bound };
258
+ const rules = judgedRules(entity, patch);
259
+ const write = { op, plan, patch, ...shapeOf(patch), tx, references, bound, rules };
247
260
  const { written, found } = await checkedUpdate(scope, write);
248
261
  if (written === 0) return [];
249
262
  // What the won set wrote, as `returning *` answers it: a read-back would carry a later
@@ -299,7 +312,9 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
299
312
  assertVersionedUpdate(entity, patch);
300
313
  const plan = scope.storePlan(op, idPlan(entity, id, options, op));
301
314
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
302
- if (namedColumns(patch).length > 0 && (await patched(op, plan, patch, options)) === 0) {
315
+ // Every rule, as `update(id)` judges on Postgres and in memory: only a filtered write narrows.
316
+ const wrote = namedColumns(patch).length > 0 && (await patchedRows(op, plan, patch, options));
317
+ if (wrote !== false && wrote.written === 0) {
303
318
  throw notFound(entity.$name, id);
304
319
  }
305
320
  // The row as the store now holds it — what `returning *` answers on Postgres: read by the
@@ -60,6 +60,7 @@ export const ENTITY_ERROR_CODES = [
60
60
  'X_ENTITY_VERSION_INVALID',
61
61
  'X_ENTITY_ALL_TRUNCATED',
62
62
  'X_ENTITY_PREDICATE_NODE_INVALID',
63
+ 'X_LOCK_HOLD_OUTSIDE_TX',
63
64
  ] as const;
64
65
 
65
66
  export type EntityErrorCode = (typeof ENTITY_ERROR_CODES)[number];
@@ -116,6 +117,7 @@ export const ENTITY_ERROR_TITLES: Readonly<Record<EntityErrorCode, string>> = {
116
117
  X_ENTITY_ALL_TRUNCATED: '.all() answered one page and dropped the cursor to the rest',
117
118
  X_ENTITY_PREDICATE_NODE_INVALID:
118
119
  'a predicate tree (andWhereNode, a policy scope) no driver can answer',
120
+ X_LOCK_HOLD_OUTSIDE_TX: 'a lock was held outside a transaction',
119
121
  };
120
122
 
121
123
  // Registered at module load, unconditionally, in one call. Without this the registry humanises the
package/src/index.ts CHANGED
@@ -179,6 +179,7 @@ export type {
179
179
  FilteredWriteOptions,
180
180
  FindByIdOptions,
181
181
  FindManyArgs,
182
+ HoldOptions,
182
183
  MemoryRepo,
183
184
  Repo,
184
185
  RepoOptions,
package/src/invariants.ts CHANGED
@@ -77,6 +77,10 @@ export const bindInvariant = <T>(
77
77
  // `ALTER TABLE "account" ADD CONSTRAINT "account_seats_non_negative_check" …` — a relation that
78
78
  // does not exist and a constraint name no migration ever wrote. Never re-render it here.
79
79
 
80
+ /** A rule with no CHECK: judged in the app, on the rows a write returned. */
81
+ export const isAppOnly = <T>(rule: Invariant<T>): boolean =>
82
+ rule.kind === 'assert' && rule.sql === null;
83
+
80
84
  /**
81
85
  * Whether any rule here can only be judged in the app. This is what decides whether a FILTERED
82
86
  * write has to read back the rows it wrote: a `check` or a `unique` is a constraint Postgres
@@ -86,7 +90,7 @@ export const bindInvariant = <T>(
86
90
  * a conflict target — one declaration, two questions.
87
91
  */
88
92
  export const hasJsOnlyInvariant = <T>(invariants: readonly Invariant<T>[]): boolean =>
89
- invariants.some((inv) => inv.kind === 'assert' && inv.sql === null);
93
+ invariants.some(isAppOnly);
90
94
 
91
95
  /**
92
96
  * How many rows a filtered write may bring back to be judged. Only the case above needs any: with
@@ -1,10 +1,15 @@
1
- // Single responsibility: a write whose RESULT the app still has to judge. A rule with no CHECK
2
- // (`kind: 'assert'`) is asserted on the rows a statement returned — after it was sent — so outside
3
- // a transaction the violating row was committed and the refusal arrived too late to matter.
1
+ // Single responsibility: a write whose RESULT the app still has to judge, and which rules it judges.
2
+ // A rule with no CHECK is asserted on the rows a statement returned, so the write runs in a
3
+ // transaction the refusal rolls back. A filtered write judges only the rules its patch can move: an
4
+ // app-only rule reading no column the patch sets keeps the stored row's verdict.
4
5
 
5
6
  import { type DbClient, withTransaction } from '@ultimat3/db';
7
+ import { columnFor, columnName, moneyColumns } from './column';
6
8
  import type { EntityCore } from './entity';
7
- import { hasJsOnlyInvariant } from './invariants';
9
+ import { hasJsOnlyInvariant, type Invariant, isAppOnly } from './invariants';
10
+ import { namedColumns } from './plan';
11
+ import type { QueryPlan } from './tenancy';
12
+ import { versionOf } from './version-lock';
8
13
 
9
14
  /**
10
15
  * Runs `work` on the connection its statement and its judgement share. With an app-only rule
@@ -26,3 +31,53 @@ export const judgedWrite = <Row, T>(
26
31
  if (!hasJsOnlyInvariant(entity.$invariants)) return work(direct);
27
32
  return withTransaction((tx) => work(tx), pinned === undefined ? {} : { client: pinned });
28
33
  };
34
+
35
+ /**
36
+ * The physical columns a property-keyed patch sets, `undefined` (absent) excluded, plus a declared
37
+ * version lock, which every update advances unnamed. `null` when a key names no column: what it
38
+ * sets is unknown, so every rule is judged.
39
+ */
40
+ const writtenColumns = <Row>(entity: EntityCore<Row>, patch: object): Set<string> | null => {
41
+ const written = new Set<string>();
42
+ const lock = versionOf(entity);
43
+ for (const [property] of [...namedColumns(patch), ...(lock === null ? [] : [[lock]])]) {
44
+ const column = property === undefined ? undefined : columnFor(entity.$columns, property);
45
+ if (property === undefined || column === undefined) return null;
46
+ if (column.$meta.kind !== 'money') {
47
+ written.add(columnName(property, column.$meta));
48
+ continue;
49
+ }
50
+ const parts = moneyColumns(property, column.$meta);
51
+ for (const part of [parts.minor, parts.currency, parts.scale]) {
52
+ if (part !== null) written.add(part);
53
+ }
54
+ }
55
+ return written;
56
+ };
57
+
58
+ /**
59
+ * The invariants a write setting `patch` judges on each merged row: every rule a constraint states
60
+ * (Postgres re-checks a CHECK on every row it updates), and each app-only rule that reads a column
61
+ * the patch sets. Fails closed: an app-only rule naming no column, or a patch key naming none,
62
+ * is judged.
63
+ */
64
+ export const judgedRules = <Row>(entity: EntityCore<Row>, patch: object): Invariant<Row>[] => {
65
+ const written = writtenColumns(entity, patch);
66
+ return entity.$invariants.filter(
67
+ (rule) =>
68
+ !isAppOnly(rule) ||
69
+ written === null ||
70
+ rule.columns.length === 0 ||
71
+ rule.columns.some((column) => written.has(column)),
72
+ );
73
+ };
74
+
75
+ /** Whether a write setting `patch` has a rule only the app can judge on its rows. */
76
+ export const judgesInApp = <Row>(entity: EntityCore<Row>, patch: object): boolean =>
77
+ judgedRules(entity, patch).some(isAppOnly);
78
+
79
+ /** Whether the plan names every primary key column with `eq`: at most one row can match. */
80
+ export const keyedPlan = <Row>(entity: EntityCore<Row>, plan: QueryPlan): boolean =>
81
+ entity.$primaryKey.every((key) =>
82
+ plan.where.some(({ column, op }) => column === key && op === 'eq'),
83
+ );
@@ -1,14 +1,29 @@
1
- // The refusal a hand-written `Repo` answers `lock` and `lockKey` with. They are optional on the
2
- // contract so such a driver still compiles, which is exactly why the typed handle has to say so.
1
+ // The refusals the typed handle's locks answer with: a hand-written `Repo` without `lock`, `lockKey`,
2
+ // `lockKeys`, `holdKey` or `holdKeys` (optional on the contract so such a driver still compiles,
3
+ // which is exactly why the handle has to say so), and a `holdKey` with no transaction to hold to.
3
4
 
4
5
  import { EntityError } from './entity-error';
5
6
 
6
7
  export const lockUnsupported = (
7
8
  entityName: string,
8
- method: 'lock' | 'lockKey' | 'lockKeys',
9
+ method: 'lock' | 'lockKey' | 'lockKeys' | 'holdKey' | 'holdKeys',
9
10
  ): EntityError =>
10
11
  new EntityError({
11
12
  code: 'X_LOCK_UNSUPPORTED',
12
- cause: `${entityName}.${method}() reached a repository that does not implement it: a hand-written driver, which the contract lets omit both`,
13
- fix: 'database(entities, { driver: postgresDriver() }) # the shipped driver has both; a hand-written Repo implements lock, lockKey and lockKeys',
13
+ cause: `${entityName}.${method}() reached a repository that does not implement it: a hand-written driver, which the contract lets omit`,
14
+ fix: `database(entities, { driver: postgresDriver() }) # the shipped driver has every lock; a hand-written Repo implements ${method}`,
15
+ });
16
+
17
+ /**
18
+ * `holdKey`/`holdKeys` outside a transaction: a transaction-scoped lock taken in autocommit is
19
+ * released by the same statement's implicit COMMIT, so it would read as a lock and hold nothing.
20
+ */
21
+ export const lockHeldOutsideTx = (
22
+ entityName: string,
23
+ method: 'holdKey' | 'holdKeys',
24
+ ): EntityError =>
25
+ new EntityError({
26
+ code: 'X_LOCK_HOLD_OUTSIDE_TX',
27
+ cause: `${entityName}.${method}() was called with no open transaction, so its transaction-scoped lock would be released the moment it was taken`,
28
+ fix: `withTransaction(async () => { await db.${entityName}.${method}(${method === 'holdKey' ? "'k'" : "['k']"}); /* the writes it guards */ }) # or db.${entityName}.${method === 'holdKey' ? "lockKey('k', fn)" : "lockKeys(['k'], fn)"}, which opens its own`,
14
29
  });
@@ -3,12 +3,14 @@
3
3
  // detection for a cycle, and this driver has neither, so a wait that lasts is the refusal instead.
4
4
 
5
5
  import { asyncContext } from '@ultimat3/core';
6
- import { driverError } from '@ultimat3/db';
7
- import { holdInOrder } from './lock-key';
6
+ import { driverError, refuseAbandoned } from '@ultimat3/db';
7
+ import type { EntityCore } from './entity';
8
+ import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
9
+ import { lockHeldOutsideTx } from './lock-unsupported';
8
10
  import { undoingBatch } from './memory-batch';
9
11
  import { memoryJournal, memoryRoot, refuseIfMemoryTxClosed } from './memory-journal';
10
12
  import { memoryTransactor } from './memory-transactor';
11
- import type { Tx } from './repo';
13
+ import type { Repo, Tx } from './repo';
12
14
 
13
15
  /** Past this a waiter gives up. Generous for a test, and a cycle reaches it every time. */
14
16
  export const MEMORY_LOCK_WAIT_MS = 5_000;
@@ -34,6 +36,21 @@ export interface MemoryLocks {
34
36
  outer: Tx | undefined,
35
37
  work: (tx: Tx) => Promise<R> | R,
36
38
  ): Promise<R>;
39
+ /**
40
+ * Every key, in the order given (`lockKeysInput` sorts them), taken in the OPEN transaction
41
+ * (`outer`, this chain's lock, or the ambient one) and held to its root's end, or to the end
42
+ * of a savepoint scope that rolls back, as on Postgres: `holdKey`, which
43
+ * Postgres sends as one statement with no savepoint. No transaction, or a hand-written one with
44
+ * no `onCommit` to say when it ends, and `outside()` is the refusal: there is nothing to hold
45
+ * the keys to. One already ended is `X_DB_TRANSACTION_CLOSED`, as its statement would be.
46
+ */
47
+ hold(keys: readonly string[], outer: Tx | undefined, outside: () => Error): Promise<void>;
48
+ }
49
+
50
+ /** A key a root holds: the queue's release, and how many of its scopes still rely on it. */
51
+ interface Held {
52
+ readonly release: () => void;
53
+ scopes: number;
37
54
  }
38
55
 
39
56
  /** What this async chain holds, and the transaction its innermost lock runs in. */
@@ -68,13 +85,20 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
68
85
  const instance = instances;
69
86
  /** The last holder's end, per key: a newcomer waits on it and becomes the new end. */
70
87
  const tails = new Map<string, Promise<void>>();
71
- /** What a joined scope still holds once it returned, per ROOT: same root, same key, no wait. */
72
- const heldByTx = new WeakMap<Tx, Set<string>>();
88
+ /**
89
+ * What a root holds, per key: the queue's release and how many of its scopes rely on it. Same
90
+ * root, same key, no wait; the key goes back to the queue when the last of those scopes ends.
91
+ */
92
+ const heldByTx = new WeakMap<Tx, Map<string, Held>>();
93
+ /**
94
+ * A key a root is still waiting for: a second call on it in the same root joins that wait
95
+ * instead of queueing behind a holder only that root's end releases, which nothing inside the
96
+ * root can reach.
97
+ */
98
+ const pendingByTx = new WeakMap<Tx, Map<string, Promise<void>>>();
73
99
 
74
- const inTx = <R>(outer: Tx | undefined, work: (tx: Tx) => Promise<R> | R): Promise<R> =>
75
- outer === undefined
76
- ? memoryTransactor().run(async (tx) => work(tx))
77
- : Promise.resolve(undoingBatch(outer, work));
100
+ const inTx = <R>(outer: Tx, work: (tx: Tx) => Promise<R> | R): Promise<R> =>
101
+ Promise.resolve(undoingBatch(outer, work));
78
102
 
79
103
  const acquire = async (name: string): Promise<() => void> => {
80
104
  const previous = tails.get(name);
@@ -106,6 +130,69 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
106
130
  }
107
131
  };
108
132
 
133
+ /**
134
+ * One more scope of the root relies on `held`, until `outer` ends: for a savepoint that commits
135
+ * that is the root's end, for one that rolls back its own. The last one out releases the key.
136
+ */
137
+ const rely = (outer: Tx, onCommit: (effect: () => void) => void, name: string): void => {
138
+ const root = memoryRoot(outer);
139
+ const byName = heldByTx.get(root);
140
+ const held = byName?.get(name);
141
+ if (byName === undefined || held === undefined) return;
142
+ held.scopes += 1;
143
+ let ended = false;
144
+ const end = (): void => {
145
+ if (ended) return;
146
+ ended = true;
147
+ held.scopes -= 1;
148
+ if (held.scopes > 0) return;
149
+ byName.delete(name);
150
+ held.release();
151
+ };
152
+ // A scope that ended while the key was waited for refuses the registration: the reference is
153
+ // dropped at once, so a key no scope can release is never left held.
154
+ try {
155
+ onCommit.call(outer, end);
156
+ outer.onRollback(end);
157
+ } catch (error) {
158
+ end();
159
+ throw error;
160
+ }
161
+ };
162
+
163
+ /**
164
+ * `name` held by `outer` to its end: shared when its root holds it already, joined when the root
165
+ * is waiting for it, else queued for. Filed under the root, so any scope of it finds the key.
166
+ */
167
+ const take = async (
168
+ outer: Tx,
169
+ onCommit: (effect: () => void) => void,
170
+ name: string,
171
+ ): Promise<void> => {
172
+ const root = memoryRoot(outer);
173
+ if (heldByTx.get(root)?.has(name) !== true) {
174
+ const pending = pendingByTx.get(root) ?? new Map<string, Promise<void>>();
175
+ pendingByTx.set(root, pending);
176
+ const joined = pending.get(name);
177
+ if (joined !== undefined) {
178
+ await joined;
179
+ return take(outer, onCommit, name);
180
+ }
181
+ const taking = acquire(name).then((release) => {
182
+ const byName = heldByTx.get(root) ?? new Map<string, Held>();
183
+ byName.set(name, { release, scopes: 0 });
184
+ heldByTx.set(root, byName);
185
+ });
186
+ pending.set(name, taking);
187
+ try {
188
+ await taking;
189
+ } finally {
190
+ pending.delete(name);
191
+ }
192
+ }
193
+ rely(outer, onCommit, name);
194
+ };
195
+
109
196
  const holds = (name: string, chain: Chain | undefined, outer: Tx | undefined): boolean =>
110
197
  chain?.names.has(name) === true ||
111
198
  (outer !== undefined && heldByTx.get(memoryRoot(outer))?.has(name)) === true;
@@ -120,30 +207,22 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
120
207
  const outer = given ?? chain?.tx ?? memoryJournal();
121
208
  // Before the wait, as a statement on a finished transaction is refused before it is sent.
122
209
  refuseIfMemoryTxClosed(outer);
210
+ // No transaction at all: open one and take the key in it, so the key is filed under the
211
+ // transaction `work` runs in and a `holdKey` inside it re-enters instead of queueing.
212
+ if (outer === undefined) return memoryTransactor().run((tx) => locks.run(key, tx, work));
123
213
  // `work` runs knowing its own tx, so a lock nested in it with no options joins this one.
124
214
  const body =
125
215
  <R>(step: (tx: Tx) => Promise<R> | R) =>
126
216
  (tx: Tx) =>
127
217
  heldByChain.run({ names: new Set([...(chain?.names ?? []), name]), tx }, () => step(tx));
128
- if (holds(name, chain, outer)) return inTx(outer, body(work));
129
- const release = await acquire(name);
218
+ if (chain?.names.has(name) === true) return inTx(outer, body(work));
130
219
  // Held to the root's end when there is one that can say so. A hand-written `Tx` with no
131
220
  // `onCommit` cannot, and the scope's own end is the only moment left.
132
221
  if (outer?.onCommit !== undefined) {
133
- // Filed under the root, so any scope of it finds the key; released by `outer`'s end, which
134
- // for a savepoint that commits is the root's, and for one that rolls back is its own.
135
- const root = memoryRoot(outer);
136
- const held = heldByTx.get(root) ?? new Set<string>();
137
- held.add(name);
138
- heldByTx.set(root, held);
139
- const once = (): void => {
140
- held.delete(name);
141
- release();
142
- };
143
- outer.onCommit(once);
144
- outer.onRollback(once);
222
+ await take(outer, outer.onCommit, name);
145
223
  return inTx(outer, body(work));
146
224
  }
225
+ const release = await acquire(name);
147
226
  try {
148
227
  return await inTx(outer, body(work));
149
228
  } finally {
@@ -163,8 +242,60 @@ export const memoryLocks = (waitMs: number = MEMORY_LOCK_WAIT_MS): MemoryLocks =
163
242
  }
164
243
  },
165
244
 
245
+ async hold(keys, given, outside) {
246
+ // The ambient transaction before the lock chain's: inside a lock's callback, a savepoint the
247
+ // callback opened is the scope a hold must end with, not the callback's own transaction.
248
+ const outer = given ?? memoryJournal() ?? heldByChain.get()?.tx;
249
+ if (outer?.onCommit === undefined) throw outside();
250
+ refuseIfMemoryTxClosed(outer);
251
+ // In order and one at a time: the sorted order is what keeps two holders from deadlocking.
252
+ for (const key of keys) await take(outer, outer.onCommit, `${instance}:${key}`);
253
+ },
254
+
166
255
  runAll: (keys, outer, work) =>
167
256
  holdInOrder(keys, (key, tx, body) => locks.run(key, tx, body), work, outer),
168
257
  };
169
258
  return locks;
170
259
  };
260
+
261
+ /**
262
+ * A memory repository's key locks over one `memoryLocks()` queue: `lockKey`, `lockKeys`, `holdKey`
263
+ * and `holdKeys`, with `lock-key.ts`'s inputs, the ones Postgres hashes.
264
+ */
265
+ export const memoryKeyLocks = <Row>(
266
+ entity: EntityCore<Row>,
267
+ locks: MemoryLocks,
268
+ ): Required<Pick<Repo<Row>, 'lockKey' | 'lockKeys' | 'holdKey' | 'holdKeys'>> => ({
269
+ // Every key through the one-key queue, sorted, each inside the last: `lockKey`'s spelling.
270
+ lockKeys: async (keys, fn, options) => {
271
+ refuseAbandoned();
272
+ return holdInOrder(
273
+ lockKeysInput(entity, keys, options),
274
+ (input, outer, body) => locks.run(`key:${input}`, outer, body),
275
+ fn,
276
+ options?.tx,
277
+ );
278
+ },
279
+
280
+ lockKey: async (key, fn, options) => {
281
+ refuseAbandoned();
282
+ return locks.run(`key:${lockKeyInput(entity, key, options)}`, options?.tx, fn);
283
+ },
284
+
285
+ // The same queue's keys, held to the open transaction's end instead of for a callback.
286
+ holdKey: async (key, options) => {
287
+ refuseAbandoned();
288
+ return locks.hold([`key:${lockKeyInput(entity, key, options)}`], undefined, () =>
289
+ lockHeldOutsideTx(entity.$name, 'holdKey'),
290
+ );
291
+ },
292
+
293
+ holdKeys: async (keys, options) => {
294
+ refuseAbandoned();
295
+ return locks.hold(
296
+ lockKeysInput(entity, keys, options).map((input) => `key:${input}`),
297
+ undefined,
298
+ () => lockHeldOutsideTx(entity.$name, 'holdKeys'),
299
+ );
300
+ },
301
+ });
@@ -49,6 +49,11 @@ type Operation = keyof typeof OPERATIONS;
49
49
 
50
50
  /** Taken before the body runs, as Postgres answers the lock before the body it guards. */
51
51
  const LOCKS = ['lock', 'lockKey', 'lockKeys'] as const;
52
+ /**
53
+ * Reported once held: no body runs under them, and a refusal before the lock (no transaction, no
54
+ * tenant) is one Postgres answers without sending the statement.
55
+ */
56
+ const HOLDS = ['holdKey', 'holdKeys'] as const;
52
57
 
53
58
  const report = (
54
59
  entity: string,
@@ -129,5 +134,13 @@ export function observedMemoryRepo<Row>(entity: string, repo: MemoryRepo<Row>):
129
134
  return method(...args);
130
135
  };
131
136
  }
137
+ for (const op of HOLDS) {
138
+ const method = repo[op] as AnyMethod;
139
+ wrapped[op] = async (...args) => {
140
+ const stack = callerStack();
141
+ await method(...args);
142
+ report(entity, op, 'select', 1, stack);
143
+ };
144
+ }
132
145
  return Object.assign({}, repo, wrapped);
133
146
  }
@@ -19,20 +19,22 @@ import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
19
19
  import { invariantViolated, notFound } from './errors';
20
20
  import {
21
21
  assertedRowsTooMany,
22
- hasJsOnlyInvariant,
22
+ assertInvariants,
23
+ type Invariant,
24
+ isAppOnly,
23
25
  MAX_ASSERTED_ROWS,
24
26
  returnedBound,
25
27
  } from './invariants';
26
- import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
28
+ import { judgedRules } from './judged-write';
27
29
  import { memoryAggregates } from './memory-aggregates';
28
30
  import { undoingBatch } from './memory-batch';
29
31
  import { memoryJournal } from './memory-journal';
30
32
  import { memoryLatestBy } from './memory-latest-by';
31
33
  import { memoryLifecycle } from './memory-lifecycle';
32
- import { memoryLocks } from './memory-lock';
34
+ import { memoryKeyLocks, memoryLocks } from './memory-lock';
33
35
  import { compareByKind, matchesPredicate } from './memory-match';
34
36
  import { observedMemoryRepo } from './memory-observed';
35
- import { type MemoryTables, sameTenantJudge } from './memory-same-tenant';
37
+ import { type MemoryTables, memoryTable, sameTenantJudge } from './memory-same-tenant';
36
38
  import { afterCursor } from './memory-seek';
37
39
  import { StoredRows, uniqueIndex, uniqueViolation } from './memory-unique';
38
40
  import { judgeUpdate, mergedRow } from './memory-update';
@@ -85,31 +87,7 @@ export const memoryRepo = <Row>(
85
87
  const rows = new StoredRows<Row>(entity);
86
88
  for (const row of seed) rows.set(storeKey(row), row);
87
89
  registerMemoryScan(tables, entity.$name, () => rows.values());
88
- tables.set(entity.$name, {
89
- entity: entity as EntityCore,
90
- // By the primary key when that is what is asked, which is nearly every reference.
91
- find: (property, value) => {
92
- const kind = kindOf(entity, property) ?? '';
93
- const soleColumn = entity.$primaryKey.length === 1 ? entity.$primaryKey[0] : undefined;
94
- if (soleColumn === property) return rows.get(keyOf(kind, value));
95
- for (const row of rows.values()) {
96
- if (keyOf(kind, field(row, property)) === keyOf(kind, value)) return row;
97
- }
98
- return undefined;
99
- },
100
- raw: {
101
- store: (row, undo) => {
102
- const key = storeKey(row);
103
- rows.set(key, row as Row);
104
- undo(() => rows.delete(key));
105
- },
106
- replace: (before, after, undo) => {
107
- const key = storeKey(before);
108
- rows.set(key, after as Row);
109
- undo(() => rows.set(key, before as Row));
110
- },
111
- },
112
- });
90
+ tables.set(entity.$name, memoryTable(entity, rows, storeKey));
113
91
  /** The trigger half: history and counters, after every stored change (`memory-lifecycle.ts`). */
114
92
  const changed = memoryLifecycle(entity as EntityCore, tables);
115
93
  const judgeReferences = sameTenantJudge(entity, tables);
@@ -178,6 +156,8 @@ export const memoryRepo = <Row>(
178
156
  from?: string,
179
157
  /** `insertAll` judged every unique key of its batch already, against one index. */
180
158
  uniquesJudged = false,
159
+ /** A filtered write's: an app-only rule reading no column its patch sets is not judged. */
160
+ rules: readonly Invariant<Row>[] = entity.$invariants,
181
161
  ): Row => {
182
162
  // `MoneyInput` lets a writer hand a `bigint`; a stored row holds the value type. The Postgres
183
163
  // driver narrows at the same position — its write methods' entry — so without this an
@@ -188,7 +168,7 @@ export const memoryRepo = <Row>(
188
168
  // `update` reaches here with the STORED row merged under its patch, so a patch that moves a row
189
169
  // out of this tenant is refused by the same call that refuses an insert into another one.
190
170
  assertRowTenant(entity.$name, entity.$tenantColumn, operation, row);
191
- entity.$assert(row);
171
+ assertInvariants(entity.$name, rules, row);
192
172
  judgeReferences(row);
193
173
  const key = storeKey(row);
194
174
  if (key !== from && rows.has(key)) throw uniqueViolation(entity, `${entity.$table}_pkey`);
@@ -265,17 +245,20 @@ export const memoryRepo = <Row>(
265
245
  // sweep of twelve million rows was green here and `X_INVARIANT_VIOLATED` there, from one
266
246
  // call — a test proving a call production refuses. Before the loop, so a refusal never
267
247
  // writes the rows it declined to judge.
268
- if (hasJsOnlyInvariant(entity.$invariants)) assertedBound(found.length, op);
248
+ const rules = judgedRules(entity, patch);
249
+ if (rules.some(isAppOnly)) assertedBound(found.length, op);
269
250
  if (op === 'updateWhereReturning') returnedBound(entity.$name, found.length);
270
251
  // The WHOLE batch is judged before any row of it lands — the same statement Postgres sends,
271
252
  // which refuses as one. A row this batch refuses used to leave the rows before it stored:
272
253
  // the write was a loop, and the loop stopped half way through.
273
- const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey);
254
+ const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey, op, rules);
274
255
  for (const row of merged) judgeReferences(row);
275
256
  // Judged whole, yet each row still meets the rows stored as it lands: one refused undoes the
276
257
  // rows before it, as `deleteWhere`'s loop does and as Postgres rolls its statement back.
277
258
  const written = undoingBatch(options?.tx, (tx) =>
278
- merged.map((row, at) => write(row, { ...options, tx }, op, storeKey(found[at]))),
259
+ merged.map((row, at) =>
260
+ write(row, { ...options, tx }, op, storeKey(found[at]), false, rules),
261
+ ),
279
262
  );
280
263
  if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
281
264
  return written;
@@ -377,7 +360,16 @@ export const memoryRepo = <Row>(
377
360
  // The deleted row, for the search mirror when it asked (`search-written-rows.ts`).
378
361
  writtenRowsSink()?.([current]);
379
362
  if (entity.$softDelete) {
380
- write(mergedRow(entity, current, softDeletion()), options, 'delete', storeKey(current));
363
+ const stamp = softDeletion();
364
+ const rules = judgedRules(entity, stamp);
365
+ write(
366
+ mergedRow(entity, current, stamp),
367
+ options,
368
+ 'delete',
369
+ storeKey(current),
370
+ false,
371
+ rules,
372
+ );
381
373
  return;
382
374
  }
383
375
  const key = storeKey(current);
@@ -395,13 +387,14 @@ export const memoryRepo = <Row>(
395
387
  const doomed = rowsOf(writeWherePlan(entity, filter, options, 'deleteWhere'), {});
396
388
  // A soft delete is an update, so an app-only rule judges it: bounded as `updateWhere` is, and
397
389
  // one row refused takes the rows before it with it, as the statement does in Postgres.
398
- if (entity.$softDelete && hasJsOnlyInvariant(entity.$invariants)) {
399
- assertedBound(doomed.length, 'deleteWhere');
400
- }
390
+ const stamp = softDeletion();
391
+ const rules = judgedRules(entity, stamp);
392
+ if (entity.$softDelete && rules.some(isAppOnly)) assertedBound(doomed.length, 'deleteWhere');
401
393
  undoingBatch(options?.tx, (tx) => {
402
394
  for (const row of doomed) {
403
395
  if (entity.$softDelete) {
404
- write(mergedRow(entity, row, softDeletion()), { tx }, 'deleteWhere', storeKey(row));
396
+ const at = storeKey(row);
397
+ write(mergedRow(entity, row, stamp), { tx }, 'deleteWhere', at, false, rules);
405
398
  continue;
406
399
  }
407
400
  const key = storeKey(row);
@@ -464,21 +457,7 @@ export const memoryRepo = <Row>(
464
457
  );
465
458
  })(),
466
459
 
467
- // Every key through the one-key queue, sorted, each inside the last: `lockKey`'s spelling.
468
- lockKeys: (keys, fn, options) =>
469
- writing(async () =>
470
- holdInOrder(
471
- lockKeysInput(entity, keys, options),
472
- (input, outer, body) => locks.run(`key:${input}`, outer, body),
473
- fn,
474
- options?.tx,
475
- ),
476
- )(),
477
-
478
- lockKey: (key, fn, options) =>
479
- writing(async () =>
480
- locks.run(`key:${lockKeyInput(entity, key, options)}`, options?.tx, fn),
481
- )(),
460
+ ...memoryKeyLocks(entity, locks),
482
461
 
483
462
  reset() {
484
463
  rows.clear();
@@ -28,6 +28,39 @@ export interface MemoryTable {
28
28
  /** One per driver, keyed by entity name: what a reference names (`Binding.table`). */
29
29
  export type MemoryTables = Map<string, MemoryTable>;
30
30
 
31
+ /**
32
+ * `entity`'s rows as its neighbours see them: found by the primary key when that is what is asked,
33
+ * which is nearly every reference, else by a scan; written raw by a trigger.
34
+ */
35
+ export const memoryTable = <Row>(
36
+ entity: EntityCore<Row>,
37
+ rows: Map<string, Row>,
38
+ storeKey: (row: unknown) => string,
39
+ ): MemoryTable => ({
40
+ entity: entity as EntityCore,
41
+ find: (property, value) => {
42
+ const kind = kindOf(entity, property) ?? '';
43
+ const soleColumn = entity.$primaryKey.length === 1 ? entity.$primaryKey[0] : undefined;
44
+ if (soleColumn === property) return rows.get(keyOf(kind, value));
45
+ for (const row of rows.values()) {
46
+ if (keyOf(kind, valueAt(row, property)) === keyOf(kind, value)) return row;
47
+ }
48
+ return undefined;
49
+ },
50
+ raw: {
51
+ store: (row, undo) => {
52
+ const key = storeKey(row);
53
+ rows.set(key, row as Row);
54
+ undo(() => rows.delete(key));
55
+ },
56
+ replace: (before, after, undo) => {
57
+ const key = storeKey(before);
58
+ rows.set(key, after as Row);
59
+ undo(() => rows.set(key, before as Row));
60
+ },
61
+ },
62
+ });
63
+
31
64
  /** Spelled the way Postgres would, so a uuid written in capitals is still the same row. */
32
65
  const sameCell = (kind: string | undefined, left: unknown, right: unknown): boolean =>
33
66
  keyOf(kind ?? '', left) === keyOf(kind ?? '', right);
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { narrowRow } from './columns';
11
11
  import type { EntityCore } from './entity';
12
+ import { assertInvariants, type Invariant } from './invariants';
12
13
  import { uniqueIndex, uniqueViolation } from './memory-unique';
13
14
  import { rowKey } from './row-key';
14
15
  import { advanceVersion } from './search-index-version';
@@ -66,6 +67,8 @@ export const judgeUpdate = <Row>(
66
67
  untouched: readonly Row[],
67
68
  key: (row: unknown) => string,
68
69
  op = 'updateWhere',
70
+ /** The rules the patch can move (`judged-write.ts`): all of them unless the caller narrowed. */
71
+ rules: readonly Invariant<Row>[] = entity.$invariants,
69
72
  ): readonly Row[] => {
70
73
  const patchOf = typeof patch === 'function' ? patch : () => patch;
71
74
  const judged: Row[] = [];
@@ -80,7 +83,7 @@ export const judgeUpdate = <Row>(
80
83
  // The same four judgements `write` makes, in the same order — on the merged row rather than
81
84
  // on the patch, and on the whole batch rather than on the row that happens to come first.
82
85
  assertRowTenant(entity.$name, entity.$tenantColumn, op, result);
83
- entity.$assert(result);
86
+ assertInvariants(entity.$name, rules, result);
84
87
  // The primary key: a result may not land on a key another row holds — neither one this write
85
88
  // does not touch, nor one an earlier result of this same batch took. A row's OWN old version
86
89
  // is not among them: it is the row this result replaces, and it never collides with itself.
package/src/pg-driver.ts CHANGED
@@ -29,12 +29,13 @@ import { notFound, repoClientPinned } from './errors';
29
29
  import { stampHistoryActor } from './history-actor';
30
30
  import {
31
31
  assertedRowsTooMany,
32
- hasJsOnlyInvariant,
32
+ assertInvariants,
33
+ type Invariant,
33
34
  MAX_ASSERTED_ROWS,
34
35
  returnedBound,
35
36
  } from './invariants';
36
37
  import { forgetPreloaded, tagSiblings } from './jit-preload';
37
- import { judgedWrite } from './judged-write';
38
+ import { judgedRules, judgedWrite, judgesInApp, keyedPlan } from './judged-write';
38
39
  import { assertPageBytes } from './page-bytes';
39
40
  import { postgresAggregates } from './pg-aggregates';
40
41
  import { postgresBulkWrites } from './pg-bulk-repo';
@@ -125,11 +126,11 @@ export const postgresRepo = <Row>(
125
126
  * A soft delete's SET list: the stamp, plus a searchable entity's version — advanced past the
126
127
  * stored one in the statement (`pg-write-sql.ts`), so a deletion is a newer version too.
127
128
  */
128
- const softDeletion = (): ReadonlyMap<string, unknown> =>
129
+ const softDeletion = (
130
+ stamp = deletionStamp(entity as EntityCore<unknown>, SOFT_DELETE_COLUMN, entityNow()),
131
+ ): ReadonlyMap<string, unknown> =>
129
132
  new Map(
130
- Object.entries(
131
- deletionStamp(entity as EntityCore<unknown>, SOFT_DELETE_COLUMN, entityNow()),
132
- ).map(([property, value]) => [physicalName(entity, property), value]),
133
+ Object.entries(stamp).map(([property, value]) => [physicalName(entity, property), value]),
133
134
  );
134
135
 
135
136
  const one = async (plan: QueryPlan, args: FindManyArgs): Promise<Row | null> => {
@@ -213,41 +214,52 @@ export const postgresRepo = <Row>(
213
214
  };
214
215
 
215
216
  /**
216
- * Only an entity with a JS-only rule comes here: rows ARE needed, so how many is a memory bound.
217
- * Counted before the write. Returning updates also cap the rows sent back and judge the cap in
218
- * the transaction, because concurrent changes can invalidate the preliminary count.
217
+ * Only a write whose patch sets a column an app-only rule reads comes here (`judged-write.ts`):
218
+ * rows ARE needed, so how many is a memory bound. Counted before the write, unless the plan names
219
+ * the whole primary key, which matches at most one row. A non-keyed returning update also caps
220
+ * the rows sent back and judges the cap in the transaction, because concurrent changes can
221
+ * invalidate the preliminary count. `rules` are the ones the patch can move.
219
222
  */
220
223
  const judgedRows = async (
221
224
  op: string,
222
225
  plan: QueryPlan,
223
226
  values: ReadonlyMap<string, unknown>,
224
227
  shape: ReadShape,
228
+ rules: readonly Invariant<Row>[],
225
229
  ): Promise<Row[]> => {
226
- const rows = await matching(op, plan, shape);
227
- if (rows > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, op, rows);
230
+ const keyed = keyedPlan(entity, plan);
231
+ if (!keyed) {
232
+ const rows = await matching(op, plan, shape);
233
+ if (rows > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, op, rows);
234
+ }
235
+ const bounded = op === 'updateWhereReturning' && !keyed;
228
236
  const update = updateStatement(entity, plan, values, shape, true);
229
- const statement =
230
- op === 'updateWhereReturning'
231
- ? sql`with updated as (${update}) select * from updated limit ${MAX_ASSERTED_ROWS + 1}`
232
- : update;
237
+ const statement = bounded
238
+ ? sql`with updated as (${update}) select * from updated limit ${MAX_ASSERTED_ROWS + 1}`
239
+ : update;
233
240
  return judged(async (send) => {
234
241
  const written = await attributed(op, () => writing(() => send.query<PhysicalRow>(statement)));
235
- if (op === 'updateWhereReturning') returnedBound(entity.$name, written.length);
242
+ if (bounded) returnedBound(entity.$name, written.length);
236
243
  const decoded = written.map((row) => decodeRow(entity, row));
237
- for (const row of decoded) entity.$assert(row);
244
+ for (const row of decoded) assertInvariants(entity.$name, rules, row);
238
245
  writtenRowsSink()?.(decoded);
239
246
  return decoded;
240
247
  });
241
248
  };
242
249
 
243
250
  /**
244
- * `delete` and `deleteWhere`. A soft delete is an update, so an app-only rule judges the stamped
245
- * rows, as `memoryRepo`'s `write` does; everything else is one statement and a count.
251
+ * `delete` and `deleteWhere`. A soft delete is an update, so an app-only rule reading its stamp
252
+ * judges the stamped rows, as `memoryRepo`'s `write` does; everything else is one statement and
253
+ * a count.
246
254
  */
247
- const removed = (op: string, plan: QueryPlan): Promise<number> =>
248
- entity.$softDelete && hasJsOnlyInvariant(entity.$invariants)
249
- ? judgedRows(op, plan, softDeletion(), shapeOf({})).then((rows) => rows.length)
255
+ const removed = (op: string, plan: QueryPlan): Promise<number> => {
256
+ const stamp = deletionStamp(entity as EntityCore<unknown>, SOFT_DELETE_COLUMN, entityNow());
257
+ return entity.$softDelete && judgesInApp(entity, stamp)
258
+ ? judgedRows(op, plan, softDeletion(stamp), shapeOf({}), judgedRules(entity, stamp)).then(
259
+ (rows) => rows.length,
260
+ )
250
261
  : counted(op, plan, removalShape(), (returning) => removal(plan, returning));
262
+ };
251
263
 
252
264
  /**
253
265
  * What `updateWhere` and `updateWhereReturning` share before a statement exists: the plan (filter
@@ -265,7 +277,7 @@ export const postgresRepo = <Row>(
265
277
  const plan = updateWherePlan(entity, filter, patch, options, op);
266
278
  // The same move, filtered: one statement can hand away every row it matches.
267
279
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
268
- return { plan, values: bindValues(entity, patch), shape: shapeOf({}) };
280
+ return { plan, patch, values: bindValues(entity, patch), shape: shapeOf({}) };
269
281
  };
270
282
 
271
283
  const repo: Repo<Row> = {
@@ -395,20 +407,21 @@ export const postgresRepo = <Row>(
395
407
 
396
408
  async updateWhere(filter, given, options) {
397
409
  const op = 'updateWhere';
398
- const { plan, values, shape } = filteredPatch(op, filter, given, options);
410
+ const { plan, patch, values, shape } = filteredPatch(op, filter, given, options);
399
411
  // The rows come back only when something here can still refuse them. A `check` or a `unique`
400
412
  // invariant is a constraint Postgres enforced on the statement itself, so the answer is
401
413
  // already a count; only a JS-only rule (`kind: 'assert'`, `sql: null`) has to be judged on
402
414
  // the result. Unconditional, this was `returning *` on every filtered write in the framework
403
415
  // — a GDPR sweep patching twelve million rows streamed all twelve million into the process,
404
416
  // decoded each one, asserted nothing about any of them, and answered with a number.
405
- // `deleteWhere` was the tell: same predicate, same table, `execute()` and a count.
406
- if (!hasJsOnlyInvariant(entity.$invariants)) {
417
+ // `deleteWhere` was the tell: same predicate, same table, `execute()` and a count. A JS-only
418
+ // rule that reads no column the patch sets keeps the stored row's verdict: a count too.
419
+ if (!judgesInApp(entity, patch)) {
407
420
  return counted(op, plan, shape, (returning) =>
408
421
  updateStatement(entity, plan, values, shape, returning),
409
422
  );
410
423
  }
411
- return (await judgedRows(op, plan, values, shape)).length;
424
+ return (await judgedRows(op, plan, values, shape, judgedRules(entity, patch))).length;
412
425
  },
413
426
 
414
427
  // The same plan, patch and judging as `updateWhere`, and the rows ARE the answer: the one
@@ -417,11 +430,11 @@ export const postgresRepo = <Row>(
417
430
  // the preliminary count can drift. A primary key names at most one row.
418
431
  async updateWhereReturning(filter, given, options) {
419
432
  const op = 'updateWhereReturning';
420
- const { plan, values, shape } = filteredPatch(op, filter, given, options);
421
- if (hasJsOnlyInvariant(entity.$invariants)) return judgedRows(op, plan, values, shape);
422
- const keyed = entity.$primaryKey.every((key) =>
423
- plan.where.some(({ column, op: test }) => column === key && test === 'eq'),
424
- );
433
+ const { plan, patch, values, shape } = filteredPatch(op, filter, given, options);
434
+ if (judgesInApp(entity, patch)) {
435
+ return judgedRows(op, plan, values, shape, judgedRules(entity, patch));
436
+ }
437
+ const keyed = keyedPlan(entity, plan);
425
438
  if (!keyed) returnedBound(entity.$name, await matching(op, plan, shape));
426
439
  const statement = updateStatement(entity, plan, values, shape, true);
427
440
  if (keyed) {
package/src/pg-lock.ts CHANGED
@@ -1,12 +1,22 @@
1
- // Single responsibility: `lock`, `lockKey` and `lockKeys` on Postgres. A transaction, through the driver's own
2
- // transactor, so nested in `withTransaction` it is a savepoint and the lock lives to the root COMMIT.
1
+ // Single responsibility: the five locks on Postgres. `lock`, `lockKey` and `lockKeys` run in the
2
+ // driver's transactor (nested in `withTransaction`, a savepoint; the lock lives to the root COMMIT);
3
+ // `holdKey` and `holdKeys` send the lock alone into the caller's open transaction.
4
+ //
3
5
  // No wait option: the bound is the role's `statement_timeout`, and a deadlock the server breaks is
4
6
  // `X_DB_SERIALIZATION_FAILURE` through the funnel like any other statement.
5
7
 
6
- import { type DbClient, join, type SqlFragment, sql, withStatementAttribution } from '@ultimat3/db';
8
+ import {
9
+ currentTx,
10
+ type DbClient,
11
+ join,
12
+ type SqlFragment,
13
+ sql,
14
+ withStatementAttribution,
15
+ } from '@ultimat3/db';
7
16
  import type { EntityCore } from './entity';
8
17
  import { notFound } from './errors';
9
18
  import { lockKeyInput, lockKeysInput } from './lock-key';
19
+ import { lockHeldOutsideTx } from './lock-unsupported';
10
20
  import { decodeRow, type PhysicalRow } from './pg-row';
11
21
  import { selectStatement } from './pg-sql';
12
22
  import { postgresTransactor } from './pg-transactor';
@@ -31,11 +41,26 @@ const advisoryLocks = (inputs: readonly string[]): SqlFragment =>
31
41
  inputs.map((input) => sql`(${input}::text)`),
32
42
  )}) as held(k)`;
33
43
 
44
+ /**
45
+ * One lock statement into the open transaction, which `client()` resolves (and refuses a pinned
46
+ * repository's foreign one). Built first, so a blank key or an unscoped tenant is refused as a
47
+ * `lockKey` is; then the transaction, since autocommit would release the lock as it is taken.
48
+ */
49
+ const held = async (
50
+ entityName: string,
51
+ op: 'holdKey' | 'holdKeys',
52
+ lock: SqlFragment,
53
+ client: () => DbClient,
54
+ ): Promise<void> => {
55
+ if (currentTx() === undefined) throw lockHeldOutsideTx(entityName, op);
56
+ await withStatementAttribution(entityName, op, () => client().query(lock));
57
+ };
58
+
34
59
  export const postgresLocks = <Row>(
35
60
  entity: EntityCore<Row>,
36
61
  pinned: DbClient | undefined,
37
62
  client: () => DbClient,
38
- ): Required<Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys'>> => ({
63
+ ): Required<Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys' | 'holdKey' | 'holdKeys'>> => ({
39
64
  async lock(id, fn, options) {
40
65
  const plan = idPlan(entity, id, options, 'lock');
41
66
  return postgresTransactor(pinned === undefined ? {} : { client: pinned }).run(async (tx) => {
@@ -67,4 +92,10 @@ export const postgresLocks = <Row>(
67
92
  return fn(tx);
68
93
  });
69
94
  },
95
+
96
+ holdKey: async (key, options) =>
97
+ held(entity.$name, 'holdKey', advisoryLock(lockKeyInput(entity, key, options)), client),
98
+
99
+ holdKeys: async (keys, options) =>
100
+ held(entity.$name, 'holdKeys', advisoryLocks(lockKeysInput(entity, keys, options)), client),
70
101
  });
package/src/repo.ts CHANGED
@@ -26,6 +26,12 @@ export interface Tx {
26
26
  onCommit?(effect: () => void): void;
27
27
  }
28
28
 
29
+ /**
30
+ * A hold's options: `RepoOptions` without `tx`. A hold is taken in the transaction the call runs
31
+ * in, never one it names, so no driver can lock in one scope and release with another.
32
+ */
33
+ export type HoldOptions = Omit<RepoOptions, 'tx'> & { readonly tx?: never };
34
+
29
35
  export interface RepoOptions {
30
36
  readonly tx?: Tx;
31
37
  /**
@@ -267,6 +273,14 @@ export interface Repo<T = unknown> {
267
273
  fn: (tx: Tx) => Promise<R> | R,
268
274
  options?: RepoOptions,
269
275
  ): Promise<R>;
276
+ /**
277
+ * `lockKey`'s lock (same table, tenant and hashing) taken in the caller's OPEN transaction and
278
+ * held to its root's end (or a rollback to a savepoint it was taken in), with no callback and
279
+ * no savepoint of its own: one statement on Postgres. Outside a transaction it is `X_LOCK_HOLD_OUTSIDE_TX`. Optional, like `lockKey`.
280
+ */
281
+ holdKey?(key: string, options?: HoldOptions): Promise<void>;
282
+ /** `holdKey` over several keys, in `lockKeys`' sorted order, in one statement on Postgres. */
283
+ holdKeys?(keys: readonly string[], options?: HoldOptions): Promise<void>;
270
284
  }
271
285
 
272
286
  /**
@@ -1,8 +1,9 @@
1
- // Single responsibility: `lock`, `lockKey` and `lockKeys` on the typed handle. The refusal lives here because
2
- // the repository contract lets a hand-written driver omit both, so only this layer can say so.
1
+ // Single responsibility: `lock`, `lockKey`, `lockKeys`, `holdKey` and `holdKeys` on the typed handle. The
2
+ // refusal lives here because the repository contract lets a hand-written driver omit them, so only
3
+ // this layer can say so.
3
4
 
4
5
  import { lockUnsupported } from './lock-unsupported';
5
- import type { Repo, RepoOptions, Tx } from './repo';
6
+ import type { HoldOptions, Repo, RepoOptions, Tx } from './repo';
6
7
  import type { IdOf } from './types';
7
8
 
8
9
  export interface TableLocks<Row> {
@@ -34,6 +35,34 @@ export interface TableLocks<Row> {
34
35
  fn: (tx: Tx) => Promise<R> | R,
35
36
  options?: RepoOptions,
36
37
  ): Promise<R>;
38
+ /**
39
+ * `lockKey`'s lock (same table, tenant and hashing) taken in the transaction the caller already
40
+ * holds, and held to its root's COMMIT or ROLLBACK: no callback, no savepoint, one statement.
41
+ * A savepoint it was taken in that is released keeps it; one rolled back to releases it, as
42
+ * Postgres does for every lock taken after that savepoint.
43
+ *
44
+ * One way for each case: inside `withTransaction`, where the caller owns the rollback and a throw
45
+ * undoes the whole unit, `holdKey`. A callback whose writes must roll back on their own when its
46
+ * throw is caught and the outer transaction commits anyway, `lockKey` — that savepoint is what
47
+ * it costs. Outside a transaction it is `X_LOCK_HOLD_OUTSIDE_TX`: an autocommit lock would be
48
+ * released at once.
49
+ *
50
+ * ```ts
51
+ * await withTransaction(async () => {
52
+ * await db.members.holdKey('owners'); // select pg_advisory_xact_lock(…)
53
+ * await db.members.update(id, { role });
54
+ * }); // BEGIN, lock, update, COMMIT
55
+ * ```
56
+ */
57
+ holdKey(key: string, options?: HoldOptions): Promise<void>;
58
+ /**
59
+ * `holdKey` over several keys, taken in `lockKeys`' sorted order in one statement, so two
60
+ * transactions whose only overlapping keys are these never deadlock, in whatever order they name
61
+ * them. Keys already held from earlier calls in the same transaction are outside that order: two
62
+ * transactions holding `a` and `b` apiece still wait on each other. An empty list and more than
63
+ * 64 keys are refused.
64
+ */
65
+ holdKeys(keys: readonly string[], options?: HoldOptions): Promise<void>;
37
66
  }
38
67
 
39
68
  /** Called as methods and refused in an `async` body, so a class-shaped driver keeps its `this`. */
@@ -53,4 +82,12 @@ export const tableLocks = <Row>(
53
82
  if (repo.lockKeys === undefined) throw lockUnsupported(entity.$name, 'lockKeys');
54
83
  return repo.lockKeys(keys, fn, options);
55
84
  },
85
+ holdKey: async (key, options) => {
86
+ if (repo.holdKey === undefined) throw lockUnsupported(entity.$name, 'holdKey');
87
+ return repo.holdKey(key, options);
88
+ },
89
+ holdKeys: async (keys, options) => {
90
+ if (repo.holdKeys === undefined) throw lockUnsupported(entity.$name, 'holdKeys');
91
+ return repo.holdKeys(keys, options);
92
+ },
56
93
  });