@jskit-ai/resource-runtime 0.2.25 → 0.2.26

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/CHANGELOG.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.1.5 exactly (from 3.1.4), from the registry with its published integrity: a read-only builder (a `scopedQuery()`, a join source, a row policy's `ownTable()`) that json-rest-api's own query compiles as a subquery keeps its joins, where 3.1.4 dropped them and the subquery matched more rows than it should (a row policy or filter narrowing with `whereExists` over a joined subquery widened), and `lockByIds`/`lockWhere` take `lockMode: 'share'`.
6
+ - **Security.** A row policy's calls that are not where calls (`join`, `leftJoin`, `select` and the rest) now throw a TypeError naming the feature, the policy and the table, as the policy makes them. Its calls replay inside one `where` group, where Knex compiles predicates only and dropped a join without a word, so a policy that narrowed through a join narrowed nothing and its readers saw rows it meant to hide. A policy narrows through another table with `whereExists` over `ownTable(name)` (which may join the owner's tables) or over another owner's `joinSource({ alias }, options)`. Upgrading: a policy that called `join` now fails every read of its table; rewrite it as a `whereExists`.
7
+ - A row policy is told the call's options as `options`, `{ context, trx }` as the caller passed them (frozen), so a policy that reads another owner's join source passes them on: `requires.members.joinSource({ alias: "tm" }, options)` reads in the caller's scope and transaction.
8
+ - `lock`, `lockMany` and `lockWhere` take `lockMode: "share"`: `FOR SHARE` on PostgreSQL and `LOCK IN SHARE MODE` on MySQL and MariaDB, which other reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows must not change until the transaction ends (`workspaces.lock` and `memberships.lockByWorkspaceIdAndUserId` pass it on). Never write a row the transaction holds shared: two transactions that each hold it shared and then write it deadlock. `claim`, `patchWhere` and `lockOrCreate` refuse `"share"` with a TypeError saying why, and any other mode is still a TypeError before any statement.
9
+ - `withTransaction({ ...options, joinOnly: true }, work)` joins the caller's transaction and refuses, with a TypeError before the work runs, a call outside one, for work whose writes must commit or roll back with its caller's; with `outermost: true` too it is a TypeError.
5
10
  - Depends on json-rest-api 3.1.4 exactly (from 3.1.3), from the registry with its published integrity: a patch, put or patchMany that stores the values a row already holds answers the row as stored on MySQL and MariaDB (it answered the values this transaction first read), and AnyAPI storage checks its tables' columns with one statement at start-up.
6
11
  - A paged `aggregate()` (`page: { size, number }`) answers `{ rows, page: { size, number, hasMore, next } }`, as `query()` answers a page, instead of a bare array a caller could take for every group; read the next page while `page.hasMore`. An unpaged grouped aggregate still answers every group or throws `GroupLimitError`, whose message now says to read pages. Upgrading: a caller passing `page` reads the groups from `.rows`.
7
12
  - Depends on json-rest-api 3.1.3 exactly (from 3.1.2), from the registry with its published integrity: a write checks each linked target type with one read of the targets' ids (their minimal records only for a target resource with a `checkPermissions` hook), which also takes the shared lock on the belongs-to and polymorphic targets it stores, before `beforeSchemaValidate` rather than after the `beforeDataCall` hooks; in a system context a belongs-to its declared foreign key protects is left to that key, so a missing target there fails with the database's foreign key error instead of `not_found`. json-rest-api now asks for json-rest-schema ^1.0.20.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.25",
3
+ "version": "0.2.26",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -15,9 +15,9 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.211",
19
- "@jskit-ai/resource-crud-core": "0.1.213",
20
- "json-rest-api": "3.1.4"
18
+ "@jskit-ai/resource-core": "0.1.212",
19
+ "@jskit-ai/resource-crud-core": "0.1.214",
20
+ "json-rest-api": "3.1.5"
21
21
  },
22
22
  "description": "The resource runtime: features own their tables through it and read and write them with scoped handles on json-rest-api.",
23
23
  "jskit": {
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.269",
68
- "@jskit-ai/kernel": "0.2.20"
67
+ "@jskit-ai/database-runtime": "0.1.270",
68
+ "@jskit-ai/kernel": "0.2.21"
69
69
  }
70
70
  }
@@ -9,8 +9,8 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
9
9
  // while a join source is built asynchronously in the caller's scope, so a filtering hook builds the join sources the
10
10
  // read's filters use first, from the call's own options, and applyFilter takes a fresh copy of one each time it asks.
11
11
 
12
- // The call options a handle's json-rest-api context carries for the join sources its filters build: the caller's
13
- // context and transaction, as the caller passed them. Module-private, so nothing but a handle sets it.
12
+ // The call options a handle's json-rest-api context carries for the join sources its filters and its row policy build:
13
+ // the caller's context and transaction, as the caller passed them. Module-private, so nothing but a handle sets it.
14
14
  const CALL_OPTIONS = Symbol("jskit.resources.callOptions");
15
15
  // The join sources a read's filters use, built by the filtering hook: by resource name, filter and alias.
16
16
  const PREPARED_SOURCES = Symbol("jskit.resources.filterJoinSources");
@@ -30,6 +30,16 @@ function withCallOptions(jsonRestContext, options) {
30
30
  return jsonRestContext;
31
31
  }
32
32
 
33
+ /**
34
+ * The call options a json-rest-api context carries (see withCallOptions): frozen `{ context, trx }`, or undefined for
35
+ * a context no handle built.
36
+ * @param {unknown} jsonRestContext
37
+ * @returns {Readonly<{ context: object | null, trx: object | null }> | undefined}
38
+ */
39
+ function callOptionsOf(jsonRestContext) {
40
+ return isRecord(jsonRestContext) ? /** @type {any} */ (jsonRestContext)[CALL_OPTIONS] : undefined;
41
+ }
42
+
33
43
  /**
34
44
  * The owns entry's search schema as json-rest-api takes it, and the filters in it that read join sources. Each such
35
45
  * filter's `joinSources` is checked here, at startup, and taken out; its applyFilter is wrapped so that it receives
@@ -174,4 +184,4 @@ function joinSourceHooks({ resourceName, declared, ownerOf }) {
174
184
  };
175
185
  }
176
186
 
177
- export { filterJoinSources, joinSourceHooks, withCallOptions };
187
+ export { callOptionsOf, filterJoinSources, joinSourceHooks, withCallOptions };
@@ -227,7 +227,30 @@ function matchesNoRow(filters, schemaInfo) {
227
227
  return Object.entries(filters).some(([key, value]) => Array.isArray(value) && value.length === 0 && search[key]?.filterOperator === "in");
228
228
  }
229
229
 
230
+ /**
231
+ * Refuses a withTransaction() call that runs where its setting says its work cannot, before the work runs: `outermost`
232
+ * work commits before it answers, so never inside the caller's transaction; `joinOnly` work commits or rolls back with
233
+ * the caller's, so never outside one, and never opens a transaction of its own. Both at once is a TypeError too.
234
+ * @param {string} name The resource's name.
235
+ * @param {{ outermost: boolean, joinOnly: boolean }} settings
236
+ * @param {boolean} joined Whether the call runs in its caller's transaction.
237
+ */
238
+ function refuseTransactionPlace(name, { outermost, joinOnly }, joined) {
239
+ if (outermost && joinOnly) {
240
+ throw new TypeError(`${name}.withTransaction() takes outermost or joinOnly, not both: outermost work opens its own transaction, joinOnly work never does.`);
241
+ }
242
+ if (outermost && joined) {
243
+ throw new TypeError(`${name}.withTransaction() outermost work commits before it answers, so it cannot run inside the caller's transaction.`);
244
+ }
245
+ if (joinOnly && !joined) {
246
+ throw new TypeError(
247
+ `${name}.withTransaction() joinOnly work commits or rolls back with its caller's transaction, and this call has none: ` +
248
+ "call it from inside the caller's withTransaction(options, work), passing on the txOptions it gives work."
249
+ );
250
+ }
251
+ }
252
+
230
253
  export {
231
- formatOf, matchesNoRow, missingOf, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners, requirePatchConditions,
232
- requireReadParams, requireUpsertRows, passedOn, whereSelection
254
+ formatOf, matchesNoRow, missingOf, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
255
+ requirePatchConditions, requireReadParams, requireUpsertRows, passedOn, whereSelection
233
256
  };
@@ -9,10 +9,22 @@ import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
9
9
  // reference it (a foreign key's check takes FOR KEY SHARE); MySQL, MariaDB and SQLite have no weaker exclusive lock and
10
10
  // lock as for "update".
11
11
  const LOCK_MODES = Object.freeze(["update", "noKeyUpdate"]);
12
+ // lock, lockMany and lockWhere also take "share": FOR SHARE (LOCK IN SHARE MODE on MySQL and MariaDB), which other
13
+ // reads and shared locks pass and writes and exclusive locks wait for, for a read check whose rows must not change until
14
+ // the transaction ends. A row held shared is never written in the same transaction: two transactions that each hold it
15
+ // shared and then write it deadlock.
16
+ const SHARED_LOCK_MODES = Object.freeze([...LOCK_MODES, "share"]);
17
+ // Why the methods that take or write their rows refuse "share".
18
+ const NO_SHARE = Object.freeze({
19
+ claim: "a claimed row is taken to be worked on, and a shared lock would let another worker claim it too",
20
+ patchWhere: "it writes the rows it selects, and two transactions that each hold a row shared and then write it deadlock",
21
+ lockOrCreate: "its work writes the record it locks, and two transactions that each hold it shared and then write it deadlock"
22
+ });
12
23
 
13
24
  /**
14
25
  * json-rest-api's lock mode for a locking read: none when the call names none, so json-rest-api takes its default.
15
- * Another value is a TypeError naming the handle method, before anything runs.
26
+ * Another value is a TypeError naming the handle method, before anything runs: "share" too for claim, patchWhere and
27
+ * lockOrCreate, which take or write their rows.
16
28
  * @param {string} name The resource's name.
17
29
  * @param {string} caller The handle method, for the message.
18
30
  * @param {unknown} lockMode
@@ -21,8 +33,13 @@ function lockModeOf(name, caller, lockMode) {
21
33
  if (lockMode === undefined) {
22
34
  return {};
23
35
  }
24
- if (!LOCK_MODES.includes(/** @type {string} */ (lockMode))) {
25
- throw new TypeError(`${name}.${caller}() lockMode is "update" (the default) or "noKeyUpdate". Received: ${JSON.stringify(lockMode)}`);
36
+ const refusal = Object.hasOwn(NO_SHARE, caller) ? NO_SHARE[/** @type {keyof typeof NO_SHARE} */ (caller)] : null;
37
+ if (lockMode === "share" && refusal) {
38
+ throw new TypeError(`${name}.${caller}() takes lockMode "update" (the default) or "noKeyUpdate", not "share": ${refusal}.`);
39
+ }
40
+ if (!(refusal ? LOCK_MODES : SHARED_LOCK_MODES).includes(/** @type {string} */ (lockMode))) {
41
+ const modes = refusal ? '"update" (the default) or "noKeyUpdate"' : '"update" (the default), "noKeyUpdate" or "share"';
42
+ throw new TypeError(`${name}.${caller}() lockMode is ${modes}. Received: ${JSON.stringify(lockMode)}`);
26
43
  }
27
44
  return { lockMode };
28
45
  }
@@ -210,11 +227,12 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
210
227
  * left out with `missing: "skip"`. MySQL locks every listed id, a hidden one too: take ids from scoped reads.
211
228
  * `fields` names the fields the lock reads, so a belongs-to field left out costs no check that its related
212
229
  * record is visible; without it every field is read. `lockMode: "noKeyUpdate"` takes PostgreSQL's FOR NO KEY
213
- * UPDATE, so other transactions may still insert rows that reference the locked ones (see LOCK_MODES).
230
+ * UPDATE, so other transactions may still insert rows that reference the locked ones (see LOCK_MODES), and
231
+ * `lockMode: "share"` a shared lock, which other reads and shared locks pass, for rows this transaction only reads.
214
232
  * `include` names belongs-to relationships whose records are locked after the rows, through their own tables'
215
233
  * handles, and nested as a read's include nests them (see withLockedIncludes).
216
234
  * @param {unknown[]} ids
217
- * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
235
+ * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
218
236
  */
219
237
  async function lockMany(ids, options) {
220
238
  return lockRead("lockMany", "lockByIds", { ids, ...(options.missing ? { missing: options.missing } : {}) }, options);
@@ -231,7 +249,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
231
249
  * json-rest-api's not-found error, or answers null with `missing: "skip"`.
232
250
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
233
251
  * @param {unknown} id
234
- * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
252
+ * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
235
253
  */
236
254
  async function lock(id, options) {
237
255
  missingOf(name, "lock", options.missing);
@@ -248,7 +266,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
248
266
  * with the ownership columns (no owners: with a filtered column), or it refuses.
249
267
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
250
268
  * @param {object} filters
251
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
269
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
252
270
  */
253
271
  async function lockWhere(filters, options) {
254
272
  requireDefinedFilters(name, "lockWhere", filters);
@@ -13,8 +13,8 @@ import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
13
13
  import { valueOnlyRaw } from "./rawExpression.js";
14
14
  import { GroupLimitError, PageSizeError, StaleRecordError, UnpagedQueryError } from "./errors.js";
15
15
  import {
16
- formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners, requirePatchConditions,
17
- requireReadParams, requireUpsertRows, whereSelection
16
+ formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
17
+ requirePatchConditions, requireReadParams, requireUpsertRows, whereSelection
18
18
  } from "./handleGuards.js";
19
19
  import {
20
20
  aggregateMeasures,
@@ -180,12 +180,12 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
180
180
  * (`returning`, `missing`, `format`...), which was for the call it was named on. When work throws, the caller gets work's
181
181
  * own error; a failed write inside it, or a failed commit, arrives as
182
182
  * json-rest-api's RestApiWriteError with the transaction's outcome.
183
- * Settings ride in options: `{ ...options, retry: false }` runs work once, for
184
- * work that cannot be repeated (it calls a provider); `{ ...options,
185
- * outermost: true }` refuses a call inside a transaction, for work that must
186
- * commit before the caller goes on (mail sent after it, say).
183
+ * Settings ride in options: `{ ...options, retry: false }` runs work once, for work that cannot be repeated (it calls a
184
+ * provider); `{ ...options, outermost: true }` refuses a call inside a transaction, for work that must commit before
185
+ * the caller goes on (mail sent after it, say); `{ ...options, joinOnly: true }` refuses a call outside one, for work
186
+ * that must commit or roll back with its caller's (see refuseTransactionPlace).
187
187
  * @template T
188
- * @param {{ trx?: object | null, context?: object | null, retry?: boolean, outermost?: boolean }} options
188
+ * @param {{ trx?: object | null, context?: object | null, retry?: boolean, outermost?: boolean, joinOnly?: boolean }} options
189
189
  * @param {(txOptions: Readonly<{ context?: object | null, trx: object }>) => Promise<T> | T} work
190
190
  * @returns {Promise<T>}
191
191
  */
@@ -193,12 +193,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
193
193
  if (rest.length > 0) {
194
194
  throw new TypeError(`${name}.withTransaction() takes (options, work); settings ride in options: withTransaction({ ...options, retry: false }, work).`);
195
195
  }
196
- const { retry = true, outermost = false, ...callOptions } = options;
196
+ const { retry = true, outermost = false, joinOnly = false, ...callOptions } = options;
197
197
  requireHandleTransaction(name, callOptions);
198
- if (inTransaction(callOptions)) {
199
- if (outermost) {
200
- throw new TypeError(`${name}.withTransaction() outermost work commits before it answers, so it cannot run inside the caller's transaction.`);
201
- }
198
+ const joined = inTransaction(callOptions);
199
+ refuseTransactionPlace(name, { outermost, joinOnly }, joined);
200
+ if (joined) {
202
201
  return work(passedOn(callOptions));
203
202
  }
204
203
  const run = () => openTransaction(api, callOptions, work);
@@ -4,7 +4,7 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import { isTableResource } from "@jskit-ai/resource-core/shared/tableResource";
5
5
  import { callerOf, createSystemContext } from "./contexts.js";
6
6
  import { DuplicateOwnerError } from "./errors.js";
7
- import { filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
7
+ import { callOptionsOf, filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
8
8
  import { createResourceHandle } from "./resourceHandle.js";
9
9
  import { resourceScopeOptions } from "./resourceHost.js";
10
10
 
@@ -64,21 +64,39 @@ function crossTableFilters(scopeOptions) {
64
64
  }));
65
65
  }
66
66
 
67
+ // The calls a row policy makes on its query: where, andWhere and orWhere and their kin (whereIn, whereExists, whereNot,
68
+ // orWhereNull...). They replay inside one where group, where Knex compiles predicates only: a join there is dropped
69
+ // without a word, and the policy would no longer narrow the rows. Any other call is refused.
70
+ const POLICY_CALL = /^(?:where|andWhere|orWhere)/u;
71
+
67
72
  /**
68
73
  * Applies one row policy, the owner's or a contribution, inside its own
69
74
  * parenthesised group, so whatever it writes (an orWhere among it) only narrows
70
75
  * the rows ownership and the other policies left.
71
- * The policy writes to a recorder; its calls replay inside `query.where(...)`.
76
+ * The policy writes to a recorder; its calls replay inside `query.where(...)`. A call other than a where call (see
77
+ * POLICY_CALL) throws a TypeError naming the policy, when the policy makes it.
72
78
  * @param {Function} policy
73
79
  * @param {Record<string, any>} args
80
+ * @param {string} label The policy, for the message: its feature and the resource it narrows.
74
81
  */
75
- async function applyGrouped(policy, args) {
82
+ async function applyGrouped(policy, args, label) {
76
83
  const calls = [];
77
84
  const recorder = new Proxy({}, {
78
85
  get(_target, method) {
79
- if (method === "then") {
86
+ if (method === "then" || typeof method === "symbol") {
80
87
  return undefined;
81
88
  }
89
+ if (!POLICY_CALL.test(method)) {
90
+ return () => {
91
+ throw new TypeError(
92
+ `${label} calls query.${method}(), which a row policy cannot use: its calls run inside one where group, where ` +
93
+ "Knex compiles predicates only and drops a join, so the policy would no longer narrow the rows. A row policy " +
94
+ "narrows with where calls (where, andWhere, orWhere, whereIn, whereExists, whereNot and their kin). To narrow " +
95
+ "through another table, tie a subquery to the row: query.whereExists(ownTable(name).select(1).join(...)" +
96
+ ".whereColumn(...)), or the same over another owner's joinSource({ alias }, options)."
97
+ );
98
+ };
99
+ }
82
100
  return (...callArgs) => {
83
101
  calls.push([method, callArgs]);
84
102
  return recorder;
@@ -158,24 +176,30 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
158
176
 
159
177
  // The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
160
178
  // Each gets who the call runs for as `caller` (see callerOf), its one way to tell: json-rest-api's own `system` flag
161
- // is left out. The owner's policy also gets the owning feature's dependencies as `requires`; a contribution is a
162
- // function its feature built in setup, with its own.
179
+ // is left out. Each gets the call's own options as `options`, `{ context, trx }` as the caller passed them, to pass
180
+ // on to an owner it reads (another owner's joinSource), never one built by hand. The owner's policy also gets the
181
+ // owning feature's dependencies as `requires`; a contribution is a function its feature built in setup, with its own.
163
182
  function composedRowPolicy(featureId, entry, contributions, requires) {
164
183
  if (!entry.rowPolicy && !entry.acceptsContributions) {
165
184
  return undefined;
166
185
  }
186
+ const resourceName = entry.resource.name;
187
+ const labelOf = (policyFeatureId, policy, relation) =>
188
+ `Feature "${policyFeatureId}" row policy ${policy.name ? `${policy.name} ` : ""}${relation} "${resourceName}"`;
167
189
  return async function ownedRowPolicy(jsonRestArgs) {
168
- const args = { ...jsonRestArgs };
190
+ const args = { ...jsonRestArgs, options: callOptionsOf(jsonRestArgs.context) };
169
191
  delete args.system;
170
192
  const caller = callerOf(args.context);
171
193
  if (entry.rowPolicy) {
172
- const result = await applyGrouped(entry.rowPolicy, { ...args, caller, ownTable: ownTableReader(featureId, args.db), requires });
194
+ const policyArgs = { ...args, caller, ownTable: ownTableReader(featureId, args.db), requires };
195
+ const result = await applyGrouped(entry.rowPolicy, policyArgs, labelOf(featureId, entry.rowPolicy, "for"));
173
196
  if (result !== true) {
174
197
  return result;
175
198
  }
176
199
  }
177
200
  for (const contribution of contributions) {
178
- const result = await applyGrouped(contribution.policy, { ...args, caller, ownTable: ownTableReader(contribution.featureId, args.db) });
201
+ const policyArgs = { ...args, caller, ownTable: ownTableReader(contribution.featureId, args.db) };
202
+ const result = await applyGrouped(contribution.policy, policyArgs, labelOf(contribution.featureId, contribution.policy, "contributed to"));
179
203
  if (result !== true) {
180
204
  return result;
181
205
  }
@@ -154,3 +154,39 @@ test("a lock's include reads the records committed after the transaction's snaps
154
154
  assert.deepEqual(read.locked.map(({ guest, ticketId, ticket }) => [guest, ticketId !== null && ticketId === ticket?.id, ticket?.number ?? null]), [["first", true, "T1"]]);
155
155
  assert.deepEqual(read.after, []);
156
156
  });
157
+
158
+ test("lock, lockMany and lockWhere with lockMode share let another transaction share-lock the row, and hold its writes and exclusive locks", async (t) => {
159
+ const { seats, bookings } = await database(t, "da_lr_share");
160
+ const [seatId] = await seats.createMany([{ code: "A1" }], { ...WORKSPACE, returning: "ids" });
161
+ const bookingId = await bookings.create({ seatId, guest: "first" }, { ...WORKSPACE, returning: "id" });
162
+ // What another transaction does while the row is held shared: it gives up after 1 s (ER_LOCK_WAIT_TIMEOUT) when it
163
+ // would wait.
164
+ const meanwhile = (work) => bookings.withTransaction({ ...WORKSPACE, retry: false }, async (tx) => {
165
+ await tx.trx.raw("SET SESSION innodb_lock_wait_timeout = 1");
166
+ await work(tx);
167
+ }).then(() => "proceeds", (error) => error.code);
168
+ const others = {
169
+ "shared lock": (tx) => bookings.lock(bookingId, { ...tx, lockMode: "share" }),
170
+ "exclusive lock": (tx) => bookings.lock(bookingId, tx),
171
+ write: (tx) => bookings.patch(bookingId, { guest: "other" }, { ...tx, returning: "none" })
172
+ };
173
+ const lockers = {
174
+ lock: (tx) => bookings.lock(bookingId, tx),
175
+ lockMany: (tx) => bookings.lockMany([bookingId], tx),
176
+ lockWhere: (tx) => bookings.lockWhere({ seatIds: [seatId] }, tx)
177
+ };
178
+ const outcomes = {};
179
+ for (const [name, locker] of Object.entries(lockers)) {
180
+ outcomes[name] = await bookings.withTransaction(WORKSPACE, async (tx) => {
181
+ assert.deepEqual((await locker({ ...tx, lockMode: "share" })).length ?? 1, 1, name);
182
+ const seen = {};
183
+ for (const [what, work] of Object.entries(others)) {
184
+ seen[what] = await meanwhile(work);
185
+ }
186
+ return seen;
187
+ });
188
+ }
189
+ const shared = { "shared lock": "proceeds", "exclusive lock": "ER_LOCK_WAIT_TIMEOUT", write: "ER_LOCK_WAIT_TIMEOUT" };
190
+ assert.deepEqual(outcomes, { lock: shared, lockMany: shared, lockWhere: shared });
191
+ assert.deepEqual((await bookings.queryAll({}, WORKSPACE)).map(({ guest }) => guest), ["first"]);
192
+ });
@@ -343,3 +343,49 @@ test("a lock or patchWhere with lockMode noKeyUpdate lets another transaction ad
343
343
  ])));
344
344
  assert.equal(Number((await knex("entries").count({ count: "*" }).first()).count), 6);
345
345
  });
346
+
347
+ test("lock, lockMany and lockWhere with lockMode share let another transaction read and share-lock the row, and hold its writes and exclusive locks", { skip }, async (t) => {
348
+ const { knex, slots } = await database(t);
349
+ const [slot] = (await slots.createMany([{ status: "open" }], { ...WORKSPACE, returning: "ids" })).map(String);
350
+ // What another transaction does while the row is held shared: it gives up after 500 ms (55P03) when it would wait.
351
+ const meanwhile = async (work) => {
352
+ const { error } = await settle(() => knex.transaction(async (trx) => {
353
+ await trx.raw("SET LOCAL lock_timeout = '500ms'");
354
+ await work(trx);
355
+ }));
356
+ return error ? error.code : "proceeds";
357
+ };
358
+ const others = {
359
+ read: (trx) => trx("slots").where({ id: slot }),
360
+ "shared lock": (trx) => trx("slots").where({ id: slot }).forShare(),
361
+ "exclusive lock": (trx) => trx("slots").where({ id: slot }).forUpdate(),
362
+ write: (trx) => trx("slots").where({ id: slot }).update({ taken_by: "other" })
363
+ };
364
+ const lockers = {
365
+ lock: (txOptions) => slots.lock(slot, txOptions),
366
+ lockMany: (txOptions) => slots.lockMany([slot], txOptions),
367
+ lockWhere: (txOptions) => slots.lockWhere({ status: "open" }, txOptions)
368
+ };
369
+ const outcomes = {};
370
+ for (const [name, locker] of Object.entries(lockers)) {
371
+ const statements = [];
372
+ const recorded = ({ sql }) => statements.push(sql);
373
+ outcomes[name] = await slots.withTransaction(WORKSPACE, async (txOptions) => {
374
+ knex.on("query", recorded);
375
+ try {
376
+ await locker({ ...txOptions, lockMode: "share" });
377
+ } finally {
378
+ knex.off("query", recorded);
379
+ }
380
+ assert.ok(statements.some((sql) => /\bfor share\b/iu.test(sql)) && !statements.some((sql) => /\bfor (?:no key )?update\b/iu.test(sql)), `${name}: ${statements.join(" | ")}`);
381
+ const seen = {};
382
+ for (const [what, work] of Object.entries(others)) {
383
+ seen[what] = await meanwhile(work);
384
+ }
385
+ return seen;
386
+ });
387
+ }
388
+ const shared = { read: "proceeds", "shared lock": "proceeds", "exclusive lock": "55P03", write: "55P03" };
389
+ assert.deepEqual(outcomes, { lock: shared, lockMany: shared, lockWhere: shared });
390
+ assert.equal((await knex("slots").where({ id: slot }).first()).taken_by, null);
391
+ });
@@ -514,7 +514,12 @@ test("lockOrCreate() runs work on the locked record, creating it first when miss
514
514
  knex.on("query", counted);
515
515
  await assert.rejects(resources.counters.lockOrCreate({ id: "moded", value: 0 }, { ...options, lockMode: "share" }, bump), {
516
516
  name: "TypeError",
517
- message: 'counters.lockOrCreate() lockMode is "update" (the default) or "noKeyUpdate". Received: "share"'
517
+ message: 'counters.lockOrCreate() takes lockMode "update" (the default) or "noKeyUpdate", not "share": its work writes the record it ' +
518
+ "locks, and two transactions that each hold it shared and then write it deadlock."
519
+ });
520
+ await assert.rejects(resources.counters.lockOrCreate({ id: "moded", value: 0 }, { ...options, lockMode: "exclusive" }, bump), {
521
+ name: "TypeError",
522
+ message: 'counters.lockOrCreate() lockMode is "update" (the default) or "noKeyUpdate". Received: "exclusive"'
518
523
  });
519
524
  knex.off("query", counted);
520
525
  assert.deepEqual(statements, []);
@@ -775,6 +780,30 @@ test("withTransaction() rethrows its work's own error, and takes its settings in
775
780
  await assert.rejects(notes.withTransaction({ ...txOptions, outermost: true }, () => null), /cannot run inside the caller's transaction/u);
776
781
  assert.equal(await notes.withTransaction(txOptions, () => "joined"), "joined");
777
782
  });
783
+ // joinOnly work commits or rolls back with its caller's transaction, so a call outside one is refused before the work
784
+ // runs, and inside one it joins: its write rolls back with the caller's.
785
+ let ran = false;
786
+ await assert.rejects(notes.withTransaction({ context: WORKSPACE_A, joinOnly: true }, () => {
787
+ ran = true;
788
+ }), {
789
+ name: "TypeError",
790
+ message: "notes.withTransaction() joinOnly work commits or rolls back with its caller's transaction, and this call has none: call " +
791
+ "it from inside the caller's withTransaction(options, work), passing on the txOptions it gives work."
792
+ });
793
+ assert.equal(ran, false);
794
+ await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, async (txOptions) => {
795
+ await notes.withTransaction({ ...txOptions, joinOnly: true }, async (joined) => {
796
+ assert.equal(joined.trx, txOptions.trx);
797
+ assert.equal(Object.hasOwn(joined, "joinOnly"), false);
798
+ await notes.create({ title: "joined, then undone" }, joined);
799
+ });
800
+ throw failure;
801
+ }), (error) => error === failure);
802
+ assert.equal((await notes.queryAll({}, { context: WORKSPACE_A })).length, 0);
803
+ await assert.rejects(notes.withTransaction({ context: WORKSPACE_A, outermost: true, joinOnly: true }, () => null), {
804
+ name: "TypeError",
805
+ message: "notes.withTransaction() takes outermost or joinOnly, not both: outermost work opens its own transaction, joinOnly work never does."
806
+ });
778
807
  });
779
808
 
780
809
  test("findOrCreate() answers the record with the id, creating it only when it is missing", async (t) => {
@@ -843,28 +872,41 @@ test("locks need a transaction and take only the caller's rows", async (t) => {
843
872
  await assert.rejects(notes.withTransaction({ context: WORKSPACE_A }, (txOptions) => notes.lock(other.id, txOptions)), notFound);
844
873
  });
845
874
 
846
- test("every lock and patchWhere take lockMode \"update\" or \"noKeyUpdate\" and reach the same rows; another is refused before any statement", async (t) => {
875
+ test("every lock and patchWhere take lockMode \"update\" or \"noKeyUpdate\", and lock, lockMany and lockWhere \"share\", reaching the same rows; another is refused before any statement", async (t) => {
847
876
  const { knex, notes } = await createFixture(t);
848
877
  const [a] = await notes.createMany([{ title: "a", status: "queued" }], { context: WORKSPACE_A, returning: "ids" });
849
878
  const statements = [];
850
879
  const counted = ({ sql }) => statements.push(sql);
851
880
  await notes.withTransaction({ context: WORKSPACE_A }, async (txOptions) => {
852
- for (const lockMode of ["update", "noKeyUpdate"]) {
881
+ for (const lockMode of ["update", "noKeyUpdate", "share"]) {
853
882
  const options = { ...txOptions, lockMode };
854
883
  assert.equal((await notes.lock(a, options)).title, "a", lockMode);
855
884
  assert.deepEqual((await notes.lockMany([a], options)).map(({ title }) => title), ["a"], lockMode);
856
885
  assert.deepEqual((await notes.lockWhere({ status: "queued" }, options)).map(({ title }) => title), ["a"], lockMode);
886
+ if (lockMode === "share") continue;
857
887
  assert.deepEqual((await notes.claim({ filters: { status: "queued" } }, options)).map(({ title }) => title), ["a"], lockMode);
858
888
  assert.equal(await notes.patchWhere({ status: "queued" }, { title: "a" }, { ...options, returning: "count" }), 1, lockMode);
859
889
  }
860
890
  knex.on("query", counted);
861
- const options = { ...txOptions, lockMode: "share" };
862
- const refused = (method) => ({ name: "TypeError", message: `notes.${method}() lockMode is "update" (the default) or "noKeyUpdate". Received: "share"` });
863
- await assert.rejects(notes.lock(a, options), refused("lock"));
864
- await assert.rejects(notes.lockMany([a], options), refused("lockMany"));
865
- await assert.rejects(notes.lockWhere({ status: "queued" }, options), refused("lockWhere"));
866
- await assert.rejects(notes.claim({ filters: { status: "queued" } }, options), refused("claim"));
867
- await assert.rejects(notes.patchWhere({ status: "queued" }, { title: "b" }, options), refused("patchWhere"));
891
+ const shared = { ...txOptions, lockMode: "share" };
892
+ const writes = "two transactions that each hold a row shared and then write it deadlock";
893
+ await assert.rejects(notes.claim({ filters: { status: "queued" } }, shared), {
894
+ name: "TypeError",
895
+ message: 'notes.claim() takes lockMode "update" (the default) or "noKeyUpdate", not "share": a claimed row is taken to be worked ' +
896
+ "on, and a shared lock would let another worker claim it too."
897
+ });
898
+ await assert.rejects(notes.patchWhere({ status: "queued" }, { title: "b" }, shared), {
899
+ name: "TypeError",
900
+ message: `notes.patchWhere() takes lockMode "update" (the default) or "noKeyUpdate", not "share": it writes the rows it selects, and ${writes}.`
901
+ });
902
+ const exclusive = { ...txOptions, lockMode: "exclusive" };
903
+ const refused = (method, modes) => ({ name: "TypeError", message: `notes.${method}() lockMode is ${modes}. Received: "exclusive"` });
904
+ const withShare = '"update" (the default), "noKeyUpdate" or "share"';
905
+ await assert.rejects(notes.lock(a, exclusive), refused("lock", withShare));
906
+ await assert.rejects(notes.lockMany([a], exclusive), refused("lockMany", withShare));
907
+ await assert.rejects(notes.lockWhere({ status: "queued" }, exclusive), refused("lockWhere", withShare));
908
+ await assert.rejects(notes.claim({ filters: { status: "queued" } }, exclusive), refused("claim", '"update" (the default) or "noKeyUpdate"'));
909
+ await assert.rejects(notes.patchWhere({ status: "queued" }, { title: "b" }, exclusive), refused("patchWhere", '"update" (the default) or "noKeyUpdate"'));
868
910
  knex.off("query", counted);
869
911
  // Nothing reached the database, so the transaction goes on (on PostgreSQL a failed statement would end it).
870
912
  assert.equal((await notes.lock(a, txOptions)).title, "a");
@@ -1158,6 +1200,151 @@ test("row policies read their own tables read-only, and contributions only narro
1158
1200
  assert.deepEqual(records.map(({ name }) => name), ["general", "banned"]);
1159
1201
  });
1160
1202
 
1203
+ // Teams with members, and documents filed under a team, each table in its workspace. Ada (7) is in the active team,
1204
+ // Grace (8) only in the archived one.
1205
+ async function teamDocuments(t, { owns, documentsPolicy, contribution }) {
1206
+ const knex = await testKnex(t);
1207
+ await knex.schema.createTable("teams", (table) => {
1208
+ table.increments("id");
1209
+ table.integer("workspace_id");
1210
+ table.string("status");
1211
+ });
1212
+ await knex.schema.createTable("team_members", (table) => {
1213
+ table.increments("id");
1214
+ table.integer("workspace_id");
1215
+ table.integer("team_id");
1216
+ table.integer("user_id");
1217
+ });
1218
+ await knex.schema.createTable("documents", (table) => {
1219
+ table.increments("id");
1220
+ table.integer("workspace_id");
1221
+ table.integer("team_id");
1222
+ table.string("title");
1223
+ });
1224
+ await knex("teams").insert([{ workspace_id: 1, status: "active" }, { workspace_id: 1, status: "archived" }, { workspace_id: 2, status: "active" }]);
1225
+ await knex("team_members").insert([
1226
+ { workspace_id: 1, team_id: 1, user_id: 7 },
1227
+ { workspace_id: 1, team_id: 2, user_id: 7 },
1228
+ { workspace_id: 1, team_id: 2, user_id: 8 },
1229
+ { workspace_id: 2, team_id: 3, user_id: 8 }
1230
+ ]);
1231
+ await knex("documents").insert([
1232
+ { workspace_id: 1, team_id: 1, title: "plan" },
1233
+ { workspace_id: 1, team_id: 2, title: "old plan" },
1234
+ { workspace_id: 2, team_id: 3, title: "elsewhere" }
1235
+ ]);
1236
+ const owned = (name, tableName, fields) => defineTableResource({
1237
+ name,
1238
+ tableName,
1239
+ ownership: "workspace",
1240
+ defaultSort: ["id"],
1241
+ schema: {
1242
+ id: { type: "id", primary: true },
1243
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
1244
+ ...fields
1245
+ }
1246
+ });
1247
+ const teamsTable = owned("teams", "teams", { status: { type: "string" } });
1248
+ const membersTable = owned("teamMembers", "team_members", {
1249
+ teamId: { type: "integer", storage: { column: "team_id" } },
1250
+ userId: { type: "integer", storage: { column: "user_id" } }
1251
+ });
1252
+ const documentsTable = owned("documents", "documents", { teamId: { type: "integer", storage: { column: "team_id" } }, title: { type: "string" } });
1253
+ const runtime = await createTestResourceRuntime({ knex });
1254
+ const documentsEntry = { resource: documentsTable, rowPolicy: documentsPolicy, acceptsContributions: Boolean(contribution) };
1255
+ if (owns === "together") {
1256
+ const handles = await runtime.own("documents.feature", [documentsEntry, teamsTable, membersTable]);
1257
+ return { knex, ...handles };
1258
+ }
1259
+ const teams = await runtime.own("teams.feature", [teamsTable, membersTable]);
1260
+ const { documents } = await runtime.own("documents.feature", [documentsEntry], { requires: { members: teams.teamMembers } });
1261
+ if (contribution) {
1262
+ teams.contributeRowPolicy("documents", contribution);
1263
+ }
1264
+ return { knex, documents, ...teams };
1265
+ }
1266
+
1267
+ const ADA = Object.freeze({ ...WORKSPACE_A, actor: Object.freeze({ id: "7" }) });
1268
+ const GRACE = Object.freeze({ ...WORKSPACE_A, actor: Object.freeze({ id: "8" }) });
1269
+
1270
+ test("a row policy narrows with where calls only: a join, which Knex would drop from the policy's where group, throws naming the policy", async (t) => {
1271
+ const joinedTeams = ({ query, column, caller }) => {
1272
+ query.join("team_members as tm", "tm.team_id", column("teamId")).where("tm.user_id", caller.userId);
1273
+ return true;
1274
+ };
1275
+ const owner = await teamDocuments(t, { owns: "together", documentsPolicy: joinedTeams });
1276
+ for (const read of [() => owner.documents.queryAll({}, { context: ADA }), () => owner.documents.scopedQuery({}, { context: ADA })]) {
1277
+ await assert.rejects(read(), {
1278
+ name: "TypeError",
1279
+ message: /^Feature "documents\.feature" row policy joinedTeams for "documents" calls query\.join\(\), which a row policy cannot use: .* query\.whereExists\(ownTable\(name\)/u
1280
+ });
1281
+ }
1282
+ // A contribution is held to the same, by its own feature's name; select and its kin are no where call either.
1283
+ const firstTeamOnly = ({ query }) => {
1284
+ query.select("team_id").where("team_id", 1);
1285
+ return true;
1286
+ };
1287
+ const contributed = await teamDocuments(t, { documentsPolicy: () => true, contribution: firstTeamOnly });
1288
+ await assert.rejects(contributed.documents.queryAll({}, { context: ADA }), {
1289
+ name: "TypeError",
1290
+ message: /^Feature "teams\.feature" row policy firstTeamOnly contributed to "documents" calls query\.select\(\), which a row policy cannot use/u
1291
+ });
1292
+ });
1293
+
1294
+ test("a row policy narrows through a join with whereExists over its own tables, which keeps the join's narrowing", async (t) => {
1295
+ // The subquery joins the member's team and keeps only active ones in the join's own condition: a subquery compiled
1296
+ // without its join would let Ada see the archived team's document too.
1297
+ const activeTeamMember = ({ query, column, caller, ownTable }) => {
1298
+ if (caller.kind !== "user") {
1299
+ return caller.kind !== "anonymous";
1300
+ }
1301
+ query.whereExists(ownTable("teamMembers")
1302
+ .select(1)
1303
+ .join("teams", (join) => join.on("teams.id", "team_members.team_id").andOnVal("teams.status", "=", "active"))
1304
+ .whereColumn("team_members.team_id", column("teamId"))
1305
+ .where("team_members.user_id", caller.userId));
1306
+ return true;
1307
+ };
1308
+ const { documents } = await teamDocuments(t, { owns: "together", documentsPolicy: activeTeamMember });
1309
+ const titles = async (context) => (await documents.queryAll({}, { context })).map(({ title }) => title);
1310
+ assert.deepEqual(await titles(ADA), ["plan"]);
1311
+ assert.deepEqual(await titles(GRACE), []);
1312
+ assert.deepEqual(await titles(WORKSPACE_A), []);
1313
+ });
1314
+
1315
+ test("a row policy is told the call's options, and reads another owner's join source in the caller's scope and transaction", async (t) => {
1316
+ const seen = [];
1317
+ const teamDocumentsPolicy = async ({ query, column, caller, options, requires }) => {
1318
+ seen.push(options);
1319
+ if (caller.kind !== "user") {
1320
+ return caller.kind !== "anonymous";
1321
+ }
1322
+ const member = await requires.members.joinSource({ alias: "tm" }, options);
1323
+ query.whereExists(member.query.select(1).whereColumn(member.column("teamId"), column("teamId")).where(member.column("userId"), caller.userId));
1324
+ return true;
1325
+ };
1326
+ const { knex, documents, teamMembers } = await teamDocuments(t, { documentsPolicy: teamDocumentsPolicy });
1327
+ // A document of workspace 1 filed under workspace 2's team, where Grace is a member.
1328
+ await knex("documents").insert({ workspace_id: 1, team_id: 3, title: "misfiled" });
1329
+ const titles = async (options) => (await documents.queryAll({}, options)).map(({ title }) => title);
1330
+ assert.deepEqual(await titles({ context: ADA }), ["plan", "old plan"]);
1331
+ assert.deepEqual(seen, [{ context: ADA, trx: null }]);
1332
+ assert.ok(Object.isFrozen(seen[0]));
1333
+ // Grace's membership of workspace 2's team stays there: the join source reads in the caller's workspace.
1334
+ assert.deepEqual(await titles({ context: GRACE }), ["old plan"]);
1335
+ // Inside a transaction the join source reads there: Grace sees the active team's document as soon as her uncommitted
1336
+ // membership exists, and a write's read-back runs the policy with the transaction too.
1337
+ seen.length = 0;
1338
+ await documents.withTransaction({ context: GRACE }, async (txOptions) => {
1339
+ await teamMembers.create({ teamId: 1, userId: 8 }, txOptions);
1340
+ assert.deepEqual(await titles(txOptions), ["plan", "old plan"]);
1341
+ assert.equal((await documents.create({ teamId: 1, title: "draft" }, txOptions)).title, "draft");
1342
+ assert.ok(seen.length >= 2);
1343
+ assert.ok(seen.every((options) => options.trx === txOptions.trx && options.context === GRACE));
1344
+ });
1345
+ assert.deepEqual(await titles({ context: ADA }), ["plan", "old plan", "draft"]);
1346
+ });
1347
+
1161
1348
  test("a row policy is told who the call runs for: a system context, a job it derived, a signed-in user or no one", async (t) => {
1162
1349
  const seen = [];
1163
1350
  const { notes, runtime } = await createFixture(t, {