@jskit-ai/resource-runtime 0.2.29 → 0.2.31

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,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.1.9 exactly (from 3.1.8): a handle's `patchWhere` and `deleteWhere` select their rows with a locking read on MySQL and MariaDB, so inside a transaction that has already read they write the rows committed since, as `UPDATE … WHERE` does (with MariaDB's `innodb_snapshot_isolation` on, the write fails with errno 1020 instead and `withTransaction` runs the work again when it opened the transaction); `lockWhere` takes `after`, which `lockPages` pages by (above); and `createMany`'s `onConflict` ignore takes rows that carry an id (above).
6
+ - `lockPages(filters, txOptions)` locks every row the filters select, a page at a time: `for await (const records of handle.lockPages(filters, txOptions))`. Each page is one locking read of up to `pageSize` rows (1 to 1,000, the default) in id order, after the last id of the page before (json-rest-api's `lockWhere` `after`), so the statements follow the pages: 3 pages among 25 rows and among 250 send the same statements. A locking read sees the latest committed rows whatever the transaction's snapshot, so work that joins a transaction that may already have read plainly (on MySQL and MariaDB the snapshot of a transaction's first plain read) reads a set larger than one `lockWhere` as it stands now. In a request it throws `RowLimitError` past the request row limit, as `queryPages` does; background work locks without one. It takes no `sort` or `limit`, and on MySQL and MariaDB needs an index that reads in id order after the ownership columns and the filters' equalities.
7
+ - `createMany(rows, { onConflict: { keys, action: "ignore" } })` takes rows that carry an id, for a table whose ids the code makes (a random `uuid`): a row its keys match writes nothing and keeps its stored id, a new row takes the id it brings, and an id that is already another row's, with other keys, fails the batch, on every database (json-rest-api skips only a clash on the keys' unique index). A merge still takes rows without an id, unless the id is its one key on a table with no owners.
8
+ - Depends on json-rest-api 3.1.8 exactly (from 3.1.7): a handle's `lockWhere` takes `sort` and `limit` (below); on MySQL and MariaDB a lock or read no longer reads the connection's schema at each call when the client's settings name a database (a `USE` on such a client's connection is not followed); and a read, in any context, reads no to-one link to a table with no ownership, no row policy and no filtering hook of the application's own whose declared foreign key protects it (SQLite still reads it).
9
+ - A row policy's `options.trx` names the transaction its read runs in. A write whose caller named no transaction runs in one json-rest-api opens for it, and its row policy runs inside it (the lookup before a patch, the read-back after a create), where `options.trx` was null: a handle call the policy made with its `options` (an owner API's role check, say) took a second connection, waiting on a one-connection pool until it gave up. It now joins the write's transaction, and the handle accepts it as one a handle opened. A policy that passes its `options` on, as the guide says, needs no change.
10
+ - `lockWhere(filters, { ...txOptions, sort, limit })` locks in an order the caller names and only as many rows as it needs, with json-rest-api 3.1.8. `sort` (fields, `"-field"` for descending, a list or one field) locks and answers the rows in that order, then by id, so two paths that lock overlapping rows take them in one order and wait for each other instead of deadlocking. `limit` (1 to 1,000) locks only the first rows of that order, by id without a `sort`, and lifts the 1,000-row refusal: a lock of one row by a unique key other than its id (`limit: 1`) is one statement, as `lock(id)` is, where PostgreSQL read twice. Without either, `lockWhere` locks as before. On MySQL and MariaDB the index `lockWhere` reads must read the rows in that order (after the ownership columns and the filters' single-value equalities, the sort's columns), or it refuses naming the columns, since InnoDB locks rows in the order it reads them.
5
11
  - Depends on json-rest-api 3.1.7 exactly (from 3.1.6): a handle's `aggregate` reads only the rows it groups. When its filters and row policy join no other table, json-rest-api groups the filtered query as it reads, so the database reads the rows the filters select through their index, however many other rows the table holds; it no longer groups the table's rows whose ids the filtered query selects (`where id in (select id … where <filters>)`), a read MySQL and MariaDB could make over the whole table, and PostgreSQL too on a partitioned table. A filter or row policy that joins another table keeps the id selection, so no row counts twice. Results are unchanged.
6
12
  - Depends on json-rest-api 3.1.6 exactly (from 3.1.5): within one transaction (a handle's `withTransaction`, or a write's own), json-rest-api answers a check of a row a write links to, or of a to-one link a response shows, from the transaction's own earlier check of that row in the same scope (the same ownership, row policy and filter values) under a lock at least as strong, until the transaction sends a statement that could change the answer: an insert or update of a table the check reads, an update of a column a remembered check names (such as `workspace_id`), a delete, a savepoint's rollback, or any other statement. A check that found no row is never remembered, and nothing carries from one transaction to the next. Installing one module (a form and a module, each published from a draft version, every row naming its author and publisher) in one transaction sent 55 statements and now sends 30; 32 modules in one transaction sent 1,698 and now send 836: its checks went from 1,024 to 162, the two users every row names checked twice instead of 480 times, and each module's own new rows 5 times instead of 17 (again only after a write to their table), on MariaDB 11.4 and PostgreSQL alike. `transactionChecks.test.js` (SQLite, and PostgreSQL in CI) and `transactionChecks.mysql.test.js` compare 1 and 32 modules, and show a transaction refusing a row it removed, moved out of the caller's scope or hid, another workspace's or user's row in the same transaction, a row an earlier transaction checked, and every link refused before.
7
13
  - 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'`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.29",
3
+ "version": "0.2.31",
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.213",
19
- "@jskit-ai/resource-crud-core": "0.1.215",
20
- "json-rest-api": "3.1.7"
18
+ "@jskit-ai/resource-core": "0.1.215",
19
+ "@jskit-ai/resource-crud-core": "0.1.217",
20
+ "json-rest-api": "3.1.9"
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.271",
68
- "@jskit-ai/kernel": "0.2.22"
67
+ "@jskit-ai/database-runtime": "0.1.273",
68
+ "@jskit-ai/kernel": "0.2.24"
69
69
  }
70
70
  }
@@ -93,7 +93,7 @@ class RowLimitError extends AppError {
93
93
  * @param {string} resourceName
94
94
  * @param {number} rowLimit
95
95
  * @param {unknown} [cause]
96
- * @param {"queryAll" | "queryPages"} [caller]
96
+ * @param {"queryAll" | "queryPages" | "lockPages"} [caller]
97
97
  */
98
98
  constructor(resourceName, rowLimit, cause, caller = "queryAll") {
99
99
  super(
@@ -92,20 +92,24 @@ function whereSelection(name, operation, filters, options) {
92
92
  }
93
93
 
94
94
  /**
95
- * An upsert matches rows by its conflict keys alone, so its rows carry no id, which could name another owner's
95
+ * An upsert matches rows by its conflict keys alone. A merge's rows carry no id, which could name another owner's
96
96
  * record, unless the id is the one key: json-rest-api allows that only on a table with no owners and no row policy.
97
+ * An ignore's rows may carry one, for a table whose ids the caller makes (a random uuid): a row its keys match writes
98
+ * nothing and keeps its stored id, a new row takes the given id, and an id that is already another row's fails the
99
+ * batch, as json-rest-api skips only a clash on the keys' unique index.
97
100
  * @param {string} name
98
101
  * @param {unknown[]} rows
99
- * @param {{ keys?: unknown }} onConflict
102
+ * @param {{ keys?: unknown, action?: unknown }} onConflict
100
103
  * @param {string | undefined} idProperty
101
104
  */
102
105
  function requireUpsertRows(name, rows, onConflict, idProperty) {
103
106
  const keys = Array.isArray(onConflict.keys) ? onConflict.keys : [];
104
107
  const byId = keys.length === 1 && (keys[0] === "id" || keys[0] === idProperty);
105
- if (!byId && rows.some((row) => isRecord(row) && Object.hasOwn(row, "id"))) {
108
+ if (!byId && onConflict.action !== "ignore" && rows.some((row) => isRecord(row) && Object.hasOwn(row, "id"))) {
106
109
  throw new TypeError(
107
- `${name}.createMany() with onConflict takes rows without an id; the conflict keys find the existing rows. ` +
108
- "Only onConflict: { keys: [\"id\"] }, on a table with no owners, matches rows by their id."
110
+ `${name}.createMany() with onConflict merge takes rows without an id; the conflict keys find the existing rows. ` +
111
+ "Only onConflict: { keys: [\"id\"] }, on a table with no owners, matches rows by their id, and an ignore's rows " +
112
+ "may carry the ids of the rows it inserts."
109
113
  );
110
114
  }
111
115
  }
@@ -1,4 +1,6 @@
1
1
  import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
2
+ import { isJobContext } from "./contexts.js";
3
+ import { RowLimitError } from "./errors.js";
2
4
  import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
3
5
  import { missingOf, requireDefinedFilters } from "./handleGuards.js";
4
6
  import { defaultFieldList, handleRecords, includedRelationships, sparseFieldset, textList } from "./handleRecords.js";
@@ -47,6 +49,9 @@ function lockModeOf(name, caller, lockMode) {
47
49
  // The most rows one read of the locked rows' links names, as the lock itself reads its ids in chunks of 1,000.
48
50
  const LINKS_PER_READ = 1000;
49
51
 
52
+ // The most rows a page of lockPages() locks: json-rest-api's most for one lockWhere.
53
+ const MAX_LOCK_PAGE = 1000;
54
+
50
55
  /**
51
56
  * The relationships a locking read includes, each a belongs-to field of the resource named by its relationship (`as`,
52
57
  * or the field's own name): `{ relationshipName, field, target, below }`, `below` the include paths under it. A lock
@@ -78,7 +83,7 @@ function lockedIncludes(resource, caller, include) {
78
83
  }
79
84
 
80
85
  /**
81
- * A handle's locking reads: lock, lockMany, lockWhere and claim. Each needs the
86
+ * A handle's locking reads: lock, lockMany, lockWhere, lockPages and claim. Each needs the
82
87
  * caller's transaction (`options.trx`), locks only rows the caller may see, and
83
88
  * reads the fields `options.fields` names, or every field a one-record read
84
89
  * answers, so a belongs-to field left out costs no check that its related
@@ -98,8 +103,9 @@ function lockedIncludes(resource, caller, include) {
98
103
  * owned tables by resource name, which lock included records.
99
104
  * @param {(name: string) => ({ schema: Record<string, any>, relationships?: Record<string, any> } | null)} dependencies.resourceNamed
100
105
  * The application's table resources by name, whose collections an included record leaves out.
106
+ * @param {{ requestRowLimit: number }} dependencies.settings The most rows lockPages() locks in a request context.
101
107
  */
102
- function createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed }) {
108
+ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed, settings }) {
103
109
  /**
104
110
  * The collections of a related table an included record leaves out, as a read's include does (see handleRecord):
105
111
  * every one it does not include itself.
@@ -258,19 +264,76 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
258
264
  }
259
265
 
260
266
  /**
261
- * Locks the caller's rows the filters select until the transaction ends, in id
262
- * order, and answers them; it waits for transactions holding them, so a row that
263
- * starts to match meanwhile is locked too. At most 1,000 rows (RestApiRowLimitError
264
- * past that). It does not lock rows inserted later: unique numbers take a unique
265
- * index, or a counter row taken with lock(). On MySQL it needs an index starting
266
- * with the ownership columns (no owners: with a filtered column), or it refuses.
267
+ * Locks the caller's rows the filters select until the transaction ends and answers them; it waits for
268
+ * transactions holding them, so a row that starts to match meanwhile is locked too. At most 1,000 rows
269
+ * (RestApiRowLimitError past that). It does not lock rows inserted later: unique numbers take a unique index, or a
270
+ * counter row taken with lock(). On MySQL it needs an index starting with the ownership columns (no owners: with a
271
+ * filtered column), or it refuses.
272
+ * Without `sort` or `limit` it locks in id order, on MySQL and MariaDB in the order of that index. `sort` (stored
273
+ * fields, "-" for descending) locks and answers the rows in that order, then by id, so every writer that locks
274
+ * them takes them in one order; `limit` locks only the first `limit` of them (1 to 1,000), by `sort` or else by
275
+ * id: `limit: 1` locks one row by a unique key in one statement, as lock(id) does. On MySQL and MariaDB either
276
+ * needs an index that reads in that order: after the ownership columns and the filters' single-value equalities,
277
+ * the sort's columns.
267
278
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
268
279
  * @param {object} filters
269
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
280
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], sort?: string | string[], limit?: number }} options
270
281
  */
271
282
  async function lockWhere(filters, options) {
272
283
  requireDefinedFilters(name, "lockWhere", filters);
273
- return lockRead("lockWhere", "lockWhere", { filters }, options);
284
+ return lockRead("lockWhere", "lockWhere", {
285
+ filters,
286
+ ...(options.sort === undefined ? {} : { sort: textList(options.sort) }),
287
+ ...(options.limit === undefined ? {} : { limit: options.limit })
288
+ }, options);
289
+ }
290
+
291
+ /**
292
+ * Locks every row the filters select, as lockWhere locks them, a page at a time: `for await (const records of
293
+ * lockPages(filters, txOptions))`. Each page is one locking read of up to `pageSize` rows (1 to 1,000, the
294
+ * default) in id order, after the last id of the page before, locked until the transaction ends. A locking read
295
+ * sees the latest committed rows whatever the transaction's snapshot, so this reads more rows than one lockWhere
296
+ * locks as they stand now, also inside a transaction that has already read plainly (MySQL and MariaDB keep the
297
+ * snapshot of a transaction's first plain read). The pages are locked one after another, and PostgreSQL keeps no
298
+ * new row out of a page already locked: when the whole set must stay as read until commit, every writer of those
299
+ * rows first locks one row that governs them (their parent, say), and so does this work, before it reads. On MySQL
300
+ * and MariaDB it needs an index that reads in id order after the ownership columns and the filters' single-value
301
+ * equalities. In a request it throws RowLimitError past the request row limit, as queryPages() does; background
302
+ * work locks without one. `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
303
+ * @param {object} filters
304
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number }} options
305
+ * @returns {AsyncGenerator<object[], void, undefined>}
306
+ */
307
+ async function* lockPages(filters, options) {
308
+ requireDefinedFilters(name, "lockPages", filters);
309
+ const { pageSize = MAX_LOCK_PAGE, sort, limit, ...lockOptions } = options;
310
+ if (sort !== undefined || limit !== undefined) {
311
+ throw new TypeError(`${name}.lockPages() locks in id order, a page of pageSize rows at a time, so it takes no sort or limit.`);
312
+ }
313
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > MAX_LOCK_PAGE) {
314
+ throw new TypeError(`${name}.lockPages() pageSize is an integer from 1 to ${MAX_LOCK_PAGE}. Received: ${JSON.stringify(pageSize)}`);
315
+ }
316
+ const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
317
+ let rows = 0;
318
+ for (let after; ;) {
319
+ const page = await lockRead("lockPages", "lockWhere", { filters, limit: pageSize, ...(after === undefined ? {} : { after }) }, lockOptions);
320
+ // A page after an id never holds it. A storage that ignored `after` would answer the first page again and
321
+ // again, and background work, which has no row limit, would page forever.
322
+ if (after !== undefined && page.some((record) => record.id === after)) {
323
+ throw new Error(`${name}.lockPages() read the row ${JSON.stringify(after)} again in the page after it: its storage does not page lockWhere by after, so its pages would never end.`);
324
+ }
325
+ rows += page.length;
326
+ if (rowLimit !== undefined && rows > rowLimit) {
327
+ throw new RowLimitError(name, rowLimit, undefined, "lockPages");
328
+ }
329
+ if (page.length > 0) {
330
+ yield page;
331
+ }
332
+ if (page.length < pageSize) {
333
+ return;
334
+ }
335
+ after = page.at(-1).id;
336
+ }
274
337
  }
275
338
 
276
339
  /**
@@ -300,6 +363,7 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
300
363
  lock,
301
364
  lockMany,
302
365
  lockWhere,
366
+ lockPages,
303
367
  claim
304
368
  });
305
369
  }
@@ -0,0 +1,43 @@
1
+ // The transactions handle calls may carry: those a handle's withTransaction opened (json-rest-api's own, which every
2
+ // handle call inside the work joins), and those a row policy's options name (see policyCallOptions).
3
+ const handleTransactions = new WeakSet();
4
+
5
+ /**
6
+ * Records a transaction a handle's withTransaction opened, for the handle calls inside its work.
7
+ * @param {object} trx
8
+ */
9
+ function trackHandleTransaction(trx) {
10
+ handleTransactions.add(trx);
11
+ }
12
+
13
+ // A call's options.trx, read or write, is one a handle's withTransaction opened, never a raw Knex transaction.
14
+ function requireHandleTransaction(name, options) {
15
+ if (options.trx && !handleTransactions.has(options.trx)) {
16
+ throw new TypeError(
17
+ `${name}: options.trx is not a transaction a handle opened. A raw Knex transaction or savepoint cannot carry ` +
18
+ "handle calls, reads included: run the work in withTransaction(options, work) and pass on the txOptions it gives work."
19
+ );
20
+ }
21
+ }
22
+
23
+ /**
24
+ * A row policy's options: the call's own, with the transaction its read runs in. A write whose caller named no
25
+ * transaction runs in one json-rest-api opens for it, and its row policy runs inside that one (the lookup before a
26
+ * patch, the read-back after a create): the policy's options name it, so the handle calls the policy passes them to
27
+ * join it instead of taking a second connection.
28
+ * @param {Readonly<{ context: object | null, trx: object | null }> | undefined} callOptions The call's own.
29
+ * @param {{ transaction?: object | null }} jsonRestContext The read's json-rest-api context.
30
+ */
31
+ function policyCallOptions(callOptions, jsonRestContext) {
32
+ const own = jsonRestContext.transaction;
33
+ if (!callOptions || callOptions.trx || !own) {
34
+ return callOptions;
35
+ }
36
+ handleTransactions.add(own);
37
+ return Object.freeze({
38
+ ...callOptions,
39
+ trx: own
40
+ });
41
+ }
42
+
43
+ export { policyCallOptions, requireHandleTransaction, trackHandleTransaction };
@@ -8,6 +8,7 @@ import { createEveryRowReads } from "./handleEveryRow.js";
8
8
  import { createHiddenFieldReads, createJoinSource, markHandleFunctions } from "./handleHidden.js";
9
9
  import { createLockReads, lockModeOf } from "./handleLocks.js";
10
10
  import { withCallOptions } from "./filterJoinSources.js";
11
+ import { requireHandleTransaction, trackHandleTransaction } from "./handleTransactions.js";
11
12
  import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
12
13
  import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
13
14
  import { valueOnlyRaw } from "./rawExpression.js";
@@ -69,19 +70,6 @@ function reportManyRow(resource, operation, rows, chunkSize) {
69
70
  }
70
71
  }
71
72
 
72
- // The transactions handles opened: json-rest-api's own, which every handle call inside the work joins.
73
- const handleTransactions = new WeakSet();
74
-
75
- // A call's options.trx, read or write, is one a handle's withTransaction opened, never a raw Knex transaction.
76
- function requireHandleTransaction(name, options) {
77
- if (options.trx && !handleTransactions.has(options.trx)) {
78
- throw new TypeError(
79
- `${name}: options.trx is not a transaction a handle opened. A raw Knex transaction or savepoint cannot carry ` +
80
- "handle calls, reads included: run the work in withTransaction(options, work) and pass on the txOptions it gives work."
81
- );
82
- }
83
- }
84
-
85
73
  // Opens a transaction for work. When work throws, json-rest-api rolls the transaction back and the caller gets the
86
74
  // error work threw, with its status and code, reporting the transaction's outcome ("rolledBack") as transactionOutcome
87
75
  // (not enumerable, so its serialized form is unchanged; a frozen error cannot carry it): a caller that retries a lost
@@ -96,7 +84,7 @@ async function openTransaction(api, options, work) {
96
84
  let own = null;
97
85
  try {
98
86
  return await api.transaction(async (trx) => {
99
- handleTransactions.add(trx);
87
+ trackHandleTransaction(trx);
100
88
  try {
101
89
  return await work(Object.freeze({ ...passedOn(options), trx }));
102
90
  } catch (error) {
@@ -169,8 +157,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
169
157
  const hiddenFields = createHiddenFieldReads({ resource, scopedQuery, column });
170
158
  // The table as a join source, with its visible columns only (see handleHidden.js).
171
159
  const joinSource = createJoinSource({ api, resource, jsonRest, scopedQuery, column });
172
- // lock, lockMany, lockWhere and claim (see handleLocks.js).
173
- const { lock, lockMany, lockWhere, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed });
160
+ // lock, lockMany, lockWhere, lockPages and claim (see handleLocks.js).
161
+ const { lock, lockMany, lockWhere, lockPages, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed, settings });
174
162
 
175
163
  /**
176
164
  * Runs work in the caller's transaction (`options.trx`), or in one it opens,
@@ -736,6 +724,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
736
724
  lock,
737
725
  lockMany,
738
726
  lockWhere,
727
+ lockPages,
739
728
  lockOrCreate: lockOrCreateRecord,
740
729
  claim,
741
730
  changeHorizon,
@@ -5,6 +5,7 @@ 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
7
  import { callOptionsOf, filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
8
+ import { policyCallOptions } from "./handleTransactions.js";
8
9
  import { createResourceHandle } from "./resourceHandle.js";
9
10
  import { resourceScopeOptions } from "./resourceHost.js";
10
11
 
@@ -176,8 +177,9 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
176
177
 
177
178
  // The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
178
179
  // Each gets who the call runs for as `caller` (see callerOf), its one way to tell: json-rest-api's own `system` flag
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
180
+ // is left out. Each gets the call's own options as `options`, `{ context, trx }` as the caller passed them, with the
181
+ // transaction the read runs in when the caller named none (see policyCallOptions), to pass on to an owner it reads
182
+ // (another owner's joinSource or handle call), never one built by hand. The owner's policy also gets the
181
183
  // owning feature's dependencies as `requires`; a contribution is a function its feature built in setup, with its own.
182
184
  function composedRowPolicy(featureId, entry, contributions, requires) {
183
185
  if (!entry.rowPolicy && !entry.acceptsContributions) {
@@ -187,7 +189,7 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
187
189
  const labelOf = (policyFeatureId, policy, relation) =>
188
190
  `Feature "${policyFeatureId}" row policy ${policy.name ? `${policy.name} ` : ""}${relation} "${resourceName}"`;
189
191
  return async function ownedRowPolicy(jsonRestArgs) {
190
- const args = { ...jsonRestArgs, options: callOptionsOf(jsonRestArgs.context) };
192
+ const args = { ...jsonRestArgs, options: policyCallOptions(callOptionsOf(jsonRestArgs.context), jsonRestArgs.context) };
191
193
  delete args.system;
192
194
  const caller = callerOf(args.context);
193
195
  if (entry.rowPolicy) {
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { countOnlyTableCases } from "./support/countOnlyTableCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of countOnlyTableCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { countOnlyTableCases } from "./support/countOnlyTableCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of countOnlyTableCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { lateRequiresCases } from "./support/lateRequiresCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of lateRequiresCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { lateRequiresCases } from "./support/lateRequiresCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of lateRequiresCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { lockWhereOrderCases } from "./support/lockWhereOrderCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of lockWhereOrderCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { lockWhereOrderCases } from "./support/lockWhereOrderCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of lockWhereOrderCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { policyTransactionCases } from "./support/policyTransactionCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of policyTransactionCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { policyTransactionCases } from "./support/policyTransactionCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of policyTransactionCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -418,7 +418,7 @@ test("an upsert on a table with no owners may key on the id alone; an owned tabl
418
418
  ]);
419
419
  await assert.rejects(
420
420
  resources.settings.createMany([{ id: "theme", value: "x" }], { ...system, onConflict: { keys: ["id", "value"], action: "merge" } }),
421
- /onConflict takes rows without an id/u
421
+ /onConflict merge takes rows without an id/u
422
422
  );
423
423
  // On a workspace table the conflict keys must hold the owner, so json-rest-api refuses the id alone.
424
424
  await assert.rejects(notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict: { keys: ["id"], action: "merge" } }));
@@ -430,8 +430,8 @@ test("an upsert finds rows by its conflict keys alone, never by an id, and stays
430
430
  await knex.schema.alterTable("notes", (table) => table.unique(["workspace_id", "title"]));
431
431
  const upsert = { keys: ["workspaceId", "title"], action: "merge", merge: ["status"] };
432
432
  await assert.rejects(
433
- notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict: { ...upsert, action: "ignore" } }),
434
- /onConflict takes rows without an id/u
433
+ notes.createMany([{ id: 1, title: "a" }], { context: WORKSPACE_A, onConflict: upsert }),
434
+ /onConflict merge takes rows without an id/u
435
435
  );
436
436
  await assert.rejects(
437
437
  notes.createMany([{ title: "a" }, { title: "a", status: "done" }], { context: WORKSPACE_A, onConflict: upsert }),
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { storedSourceCases } from "./support/storedSourceCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of storedSourceCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { storedSourceCases } from "./support/storedSourceCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of storedSourceCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,112 @@
1
+ import assert from "node:assert/strict";
2
+ import { randomUUID } from "node:crypto";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { createTestResourceRuntime } from "../../src/test/index.js";
5
+
6
+ // A table its feature counts but never reads back row by row (who took part in an anonymous survey): each row takes a
7
+ // random v4 uuid the caller makes, never a sequence, and a unique key on the workspace, the record and the user. A
8
+ // duplicate create hits that key. createMany's onConflict ignore makes a duplicate by those keys a no-op that keeps the
9
+ // stored id, gives a new row the id it brings, and fails on an id that is already another row's: the ignore covers only
10
+ // a clash on the keys' unique index, on MySQL and MariaDB as elsewhere. Each database's test file runs these cases on
11
+ // its own connection.
12
+
13
+ const WORKSPACE_A = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
14
+ const WORKSPACE_B = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "2" }) }) });
15
+ const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
16
+ const KEYS = Object.freeze(["workspaceId", "recordId", "userId"]);
17
+ const IGNORE = Object.freeze({ keys: KEYS, action: "ignore" });
18
+
19
+ // A unique key's violation, as each driver reports it, anywhere in the error's causes.
20
+ const DUPLICATE_CODES = new Set(["23505", "ER_DUP_ENTRY", "SQLITE_CONSTRAINT_UNIQUE", "SQLITE_CONSTRAINT_PRIMARYKEY"]);
21
+ function duplicateKey(error) {
22
+ for (let current = error; current; current = current.cause) {
23
+ if (DUPLICATE_CODES.has(current.code)) {
24
+ return true;
25
+ }
26
+ }
27
+ return false;
28
+ }
29
+
30
+ const participationResource = defineTableResource({
31
+ name: "participations",
32
+ tableName: "participations",
33
+ ownership: "workspace",
34
+ schema: {
35
+ id: { type: "uuid", primary: true },
36
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
37
+ recordId: { type: "integer", required: true, search: true, storage: { column: "record_id" } },
38
+ userId: { type: "integer", required: true, search: true, storage: { column: "user_id" } }
39
+ }
40
+ });
41
+
42
+ /** @param {import("knex").Knex} knex */
43
+ async function participationsOf(knex) {
44
+ await knex.schema.createTable("participations", (table) => {
45
+ table.uuid("id").primary();
46
+ table.integer("workspace_id").notNullable();
47
+ table.integer("record_id").notNullable();
48
+ table.integer("user_id").notNullable();
49
+ table.unique(["workspace_id", "record_id", "user_id"]);
50
+ });
51
+ const runtime = await createTestResourceRuntime({ knex });
52
+ const { participations } = await runtime.own("survey.feature", [participationResource]);
53
+ return participations;
54
+ }
55
+
56
+ /** The stored rows as `[id, workspace, user]`, by workspace and user. @param {import("knex").Knex} knex */
57
+ async function storedRows(knex) {
58
+ const rows = await knex("participations").orderBy(["workspace_id", "user_id"]).select("id", "workspace_id", "user_id");
59
+ return rows.map((row) => [String(row.id), Number(row.workspace_id), Number(row.user_id)]);
60
+ }
61
+
62
+ /**
63
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
64
+ * The test's own empty database; `suffix` names it where the database needs a name.
65
+ */
66
+ function countOnlyTableCases(connect) {
67
+ return [
68
+ ["a count-only table takes the caller's random v4 ids in a member's request, refuses a duplicate by its unique key, and answers counts", async (t) => {
69
+ const knex = await connect(t, "da_co_create");
70
+ const participations = await participationsOf(knex);
71
+ const ids = [randomUUID(), randomUUID(), randomUUID()];
72
+ await participations.create({ id: ids[0], recordId: 7, userId: 1 }, { ...WORKSPACE_A, returning: "none" });
73
+ await participations.create({ id: ids[1], recordId: 7, userId: 2 }, { ...WORKSPACE_A, returning: "none" });
74
+ await participations.create({ id: ids[2], recordId: 7, userId: 1 }, { ...WORKSPACE_B, returning: "none" });
75
+ // The same person twice for one record hits the unique key.
76
+ await assert.rejects(participations.create({ id: randomUUID(), recordId: 7, userId: 1 }, { ...WORKSPACE_A, returning: "none" }), duplicateKey);
77
+ assert.deepEqual(await storedRows(knex), [[ids[0], 1, 1], [ids[1], 1, 2], [ids[2], 2, 1]]);
78
+ assert.ok(ids.every((id) => V4.test(id)));
79
+ const [counted] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId: 7 } }, WORKSPACE_A);
80
+ assert.equal(counted.participants, 2);
81
+ }],
82
+
83
+ ["onConflict ignore keeps a duplicate's stored id, gives a new row its own id, and fails on an id that is another row's", async (t) => {
84
+ const knex = await connect(t, "da_co_ignore");
85
+ const participations = await participationsOf(knex);
86
+ const first = randomUUID();
87
+ const fresh = randomUUID();
88
+ await participations.createMany([{ id: first, recordId: 7, userId: 1 }], { ...WORKSPACE_A, onConflict: IGNORE });
89
+ // A duplicate by the keys writes nothing and keeps the stored id; a new row takes the id it brings.
90
+ await participations.createMany([{ id: randomUUID(), recordId: 7, userId: 1 }, { id: fresh, recordId: 7, userId: 2 }], { ...WORKSPACE_A, onConflict: IGNORE });
91
+ assert.deepEqual(await storedRows(knex), [[first, 1, 1], [fresh, 1, 2]]);
92
+ // An id that is already another row's, with other keys, fails loudly, in its workspace and in another.
93
+ for (const options of [WORKSPACE_A, WORKSPACE_B]) {
94
+ await assert.rejects(participations.createMany([{ id: first, recordId: 8, userId: 3 }], { ...options, onConflict: IGNORE }), duplicateKey, options.context.workspace.id);
95
+ }
96
+ assert.deepEqual(await storedRows(knex), [[first, 1, 1], [fresh, 1, 2]]);
97
+ // Inside one transaction the second ignore is a no-op too, and the transaction goes on.
98
+ await participations.withTransaction(WORKSPACE_A, async (tx) => {
99
+ await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 1 }], { ...tx, onConflict: IGNORE });
100
+ await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 1 }], { ...tx, onConflict: IGNORE });
101
+ await participations.createMany([{ id: randomUUID(), recordId: 9, userId: 2 }], { ...tx, onConflict: IGNORE });
102
+ });
103
+ const [counted] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId: 9 } }, WORKSPACE_A);
104
+ assert.equal(counted.participants, 2);
105
+ // A merge still takes rows without an id: the keys find the row it changes.
106
+ await assert.rejects(participations.createMany([{ id: randomUUID(), recordId: 7, userId: 1 }], { ...WORKSPACE_A, onConflict: { keys: KEYS, action: "merge" } }),
107
+ /onConflict merge takes rows without an id/u);
108
+ }]
109
+ ];
110
+ }
111
+
112
+ export { countOnlyTableCases };
@@ -0,0 +1,154 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
5
+ import { startTestFeatures } from "../../src/test/index.js";
6
+
7
+ // A ring a row policy closes, on every database the runtime supports: the audit history's row policy narrows through
8
+ // the evidence owner's join source, while the evidence owner records each change in the audit history. The audit
9
+ // feature late-requires the evidence's owner API, so the kernel starts the ring and resolves it once every feature has
10
+ // booted, and the policy reads it at call time. Each database's test file runs these cases on its own connection.
11
+
12
+ const evidenceFileResource = defineTableResource({
13
+ name: "evidenceFiles",
14
+ tableName: "evidence_files",
15
+ ownership: "workspace",
16
+ schema: {
17
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
18
+ name: { type: "string", required: true },
19
+ withdrawn: { type: "boolean", defaultTo: false }
20
+ }
21
+ });
22
+
23
+ const auditEntryResource = defineTableResource({
24
+ name: "auditEntries",
25
+ tableName: "audit_entries",
26
+ ownership: "workspace",
27
+ schema: {
28
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
29
+ evidenceFileId: { type: "id", required: true, storage: { column: "evidence_file_id" } },
30
+ action: { type: "string", required: true }
31
+ }
32
+ });
33
+
34
+ // A person sees an audit entry only while they see its evidence file, as the evidence owner's join source answers it.
35
+ async function auditEntriesPolicy({ query, caller, column, options, requires }) {
36
+ if (caller.kind !== "user") {
37
+ return caller.kind !== "anonymous";
38
+ }
39
+ const file = await requires.evidence.joinSource({ alias: "ef" }, options);
40
+ query.whereExists(file.query.select(1).whereColumn(file.column("id"), column("evidenceFileId")));
41
+ return true;
42
+ }
43
+
44
+ // A person does not see a withdrawn evidence file.
45
+ function evidenceFilesPolicy({ query, caller, column }) {
46
+ if (caller.kind === "user") {
47
+ query.where(column("withdrawn"), false);
48
+ }
49
+ return true;
50
+ }
51
+
52
+ /**
53
+ * The audit and evidence features. With `plainRing`, the audit feature requires the evidence's owner API as a plain
54
+ * requirement instead of a late one.
55
+ * @param {{ plainRing?: boolean }} [options]
56
+ */
57
+ function auditAndEvidence({ plainRing = false } = {}) {
58
+ const evidenceRequirement = { evidence: "evidence.files" };
59
+ const AuditFeature = defineFeature({
60
+ id: "audit",
61
+ owns: [{ resource: auditEntryResource, rowPolicy: auditEntriesPolicy }],
62
+ ...(plainRing ? { requires: evidenceRequirement } : { late: evidenceRequirement }),
63
+ provides: { history: "audit.history" },
64
+ setup: ({ resources }) => ({
65
+ history: Object.freeze({
66
+ record: (entry, options) => resources.auditEntries.create(entry, { ...options, returning: "none" }),
67
+ actions: async (options) => (await resources.auditEntries.queryAll({ sort: ["id"] }, options)).map(({ action }) => action)
68
+ })
69
+ })
70
+ });
71
+ const EvidenceFeature = defineFeature({
72
+ id: "evidence",
73
+ owns: [{ resource: evidenceFileResource, rowPolicy: evidenceFilesPolicy }],
74
+ systemScope: "file and withdraw evidence for a test's workspaces",
75
+ requires: { history: "audit.history" },
76
+ provides: { files: "evidence.files" },
77
+ setup: ({ resources, systemContext, history }) => {
78
+ const inWorkspace = (workspaceId) => ({ context: systemContext("file evidence").forWorkspace(workspaceId) });
79
+ return {
80
+ files: Object.freeze({
81
+ async add(name, workspaceId) {
82
+ const id = await resources.evidenceFiles.create({ name }, { ...inWorkspace(workspaceId), returning: "id" });
83
+ await history.record({ evidenceFileId: id, action: `added ${name}` }, inWorkspace(workspaceId));
84
+ return id;
85
+ },
86
+ async withdraw(id, name, workspaceId) {
87
+ await resources.evidenceFiles.patch(id, { withdrawn: true }, { ...inWorkspace(workspaceId), returning: "none" });
88
+ await history.record({ evidenceFileId: id, action: `withdrew ${name}` }, inWorkspace(workspaceId));
89
+ },
90
+ joinSource: (request, options) => resources.evidenceFiles.joinSource(request, options)
91
+ })
92
+ };
93
+ }
94
+ });
95
+ return [AuditFeature, EvidenceFeature];
96
+ }
97
+
98
+ async function createTables(knex) {
99
+ await knex.schema.createTable("evidence_files", (table) => {
100
+ table.increments("id");
101
+ table.integer("workspace_id").nullable().index();
102
+ table.string("name").notNullable();
103
+ table.boolean("withdrawn").notNullable().defaultTo(false);
104
+ });
105
+ await knex.schema.createTable("audit_entries", (table) => {
106
+ table.increments("id");
107
+ table.integer("workspace_id").nullable().index();
108
+ table.integer("evidence_file_id").notNullable().index();
109
+ table.string("action").notNullable();
110
+ });
111
+ }
112
+
113
+ const asPerson = (userId, workspaceId) => ({ context: { actor: { id: userId }, workspace: { id: workspaceId } } });
114
+
115
+ /**
116
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
117
+ * The test's own empty database; `suffix` names it where the database needs a name.
118
+ */
119
+ function lateRequiresCases(connect) {
120
+ return [
121
+ ["a row policy that narrows through an owner which requires its own feature starts with a late requirement, and reads only the rows the policy admits", async (t) => {
122
+ const knex = await connect(t, "rr_late_ring");
123
+ await createTables(knex);
124
+
125
+ // The same ring with a plain requirement is refused before any setup.
126
+ await assert.rejects(
127
+ startTestFeatures({ knex, features: auditAndEvidence({ plainRing: true }) }),
128
+ { message: "Provider capability cycle detected: audit -> evidence -> audit." }
129
+ );
130
+
131
+ const { capabilities, resources, stop } = await startTestFeatures({
132
+ knex,
133
+ features: auditAndEvidence(),
134
+ requires: { files: "evidence.files", history: "audit.history" }
135
+ });
136
+ t.after(stop);
137
+ const { files, history } = capabilities;
138
+ await files.add("contract.pdf", "1");
139
+ const photo = await files.add("photo.jpg", "1");
140
+ await files.withdraw(photo, "photo.jpg", "1");
141
+ await files.add("invoice.pdf", "2");
142
+
143
+ // A person in workspace 1 sees the contract's entry, not the withdrawn photo's two, in the read's one statement.
144
+ const read = await countQueries(knex, () => history.actions(asPerson("7", "1")));
145
+ assert.deepEqual([read.result, read.count], [["added contract.pdf"], 1]);
146
+ assert.deepEqual(await history.actions(asPerson("8", "2")), ["added invoice.pdf"]);
147
+ // Background work in workspace 1 sees every entry of its workspace.
148
+ const job = { context: resources.declareSystemScope("test.reader", "check a test's audit entries")("check").forWorkspace("1") };
149
+ assert.deepEqual(await history.actions(job), ["added contract.pdf", "added photo.jpg", "withdrew photo.jpg"]);
150
+ }]
151
+ ];
152
+ }
153
+
154
+ export { lateRequiresCases };
@@ -0,0 +1,196 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
3
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
+ import { createResourceHost } from "../../src/server/resourceHost.js";
6
+ import { createResourceRuntime } from "../../src/server/resourceRuntime.js";
7
+
8
+ // lockWhere's sort and limit, on every database the runtime supports: the rows are locked in the sort's order, then by
9
+ // id, and limit locks only the first of them, so a lock of one row by its unique key costs what lock(id) costs. And
10
+ // lockPages, which locks every row a page at a time in id order, each page one locking read that sees the latest rows.
11
+ // Each database's test file runs these cases on its own connection.
12
+
13
+ const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
14
+ const IN_WORKSPACE_A = Object.freeze({ context: WORKSPACE_A });
15
+
16
+ const slotResource = defineTableResource({
17
+ name: "slots",
18
+ tableName: "slots",
19
+ ownership: "workspace",
20
+ searchSchema: { codes: { type: "array", actualField: "code", filterOperator: "in" } },
21
+ schema: {
22
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
23
+ code: { type: "string", required: true, search: true },
24
+ turn: { type: "integer", required: true }
25
+ }
26
+ });
27
+
28
+ const codeOf = (index) => `C${String(index).padStart(4, "0")}`;
29
+
30
+ /**
31
+ * `count` slots in each of workspaces 1 and 2, codes C0000 up, their turns in the codes' reverse order, and a system
32
+ * scope for background work on them.
33
+ * @param {import("knex").Knex} knex
34
+ * @param {number} count
35
+ * @param {{ requestRowLimit?: number }} [settings]
36
+ */
37
+ async function slotsOf(knex, count, settings = {}) {
38
+ await knex.schema.createTable("slots", (table) => {
39
+ table.increments("id");
40
+ table.integer("workspace_id").nullable();
41
+ table.string("code").notNullable();
42
+ table.integer("turn").notNullable();
43
+ table.unique(["workspace_id", "code"]);
44
+ // An index that reads a workspace's rows in id order, which lockPages needs on MySQL and MariaDB.
45
+ table.index(["workspace_id"], "slots_workspace");
46
+ });
47
+ const rows = [1, 2].flatMap((workspace) => Array.from({ length: count }, (_, index) => ({ workspace_id: workspace, code: codeOf(index), turn: count - index })));
48
+ for (let start = 0; start < rows.length; start += 200) {
49
+ await knex("slots").insert(rows.slice(start, start + 200));
50
+ }
51
+ const api = await createResourceHost({ knex, logger: silentLogger });
52
+ const runtime = createResourceRuntime({ api, ...settings });
53
+ const { slots } = await runtime.own("slots.feature", [slotResource]);
54
+ const system = runtime.declareSystemScope("slots.feature", "count every workspace's slots")("count the slots");
55
+ return { slots, system, api };
56
+ }
57
+
58
+ /** Every page lockPages answers. Past 10 pages it throws, so a lockPages that never ends fails its case at once. */
59
+ async function pagesOf(pages) {
60
+ const all = [];
61
+ for await (const page of pages) {
62
+ all.push(page);
63
+ if (all.length > 10) {
64
+ throw new Error("lockPages answered more than 10 pages: its pages never end");
65
+ }
66
+ }
67
+ return all;
68
+ }
69
+
70
+ /**
71
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
72
+ * The test's own empty database; `suffix` names it where the database needs a name.
73
+ */
74
+ function lockWhereOrderCases(connect) {
75
+ return [
76
+ ["lockWhere locks and answers the rows in sort order, then id, and limit takes the first of them", async (t) => {
77
+ const knex = await connect(t, "da_lw_order");
78
+ const { slots } = await slotsOf(knex, 4);
79
+ const codes = (rows) => rows.map(({ code }) => code);
80
+ const every = { codes: [0, 1, 2, 3].map(codeOf) };
81
+ await slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
82
+ assert.deepEqual(codes(await slots.lockWhere(every, { ...tx, sort: ["-code"] })), ["C0003", "C0002", "C0001", "C0000"]);
83
+ assert.deepEqual(codes(await slots.lockWhere(every, { ...tx, sort: "-code", limit: 2 })), ["C0003", "C0002"]);
84
+ // A limit alone takes the lowest id: one of the unique key's rows is its one row.
85
+ assert.deepEqual(codes(await slots.lockWhere({ code: "C0001" }, { ...tx, limit: 1 })), ["C0001"]);
86
+ assert.deepEqual(await slots.lockWhere({ code: "C9999" }, { ...tx, limit: 1 }), []);
87
+ });
88
+ for (const options of [{ limit: 0 }, { limit: 1001 }, { sort: ["missing"] }]) {
89
+ await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, (tx) => slots.lockWhere(every, { ...tx, ...options })),
90
+ (error) => error.code === "REST_API_VALIDATION", JSON.stringify(options));
91
+ }
92
+ }],
93
+
94
+ ["lockWhere of one row with limit: 1 sends what lock(id) sends, among 4 rows and among 400", async (t) => {
95
+ const costs = [];
96
+ let client;
97
+ for (const count of [4, 400]) {
98
+ const knex = await connect(t, `da_lw_cost_${count}`);
99
+ client = knex.client.config.client;
100
+ const { slots } = await slotsOf(knex, count);
101
+ const [{ id }] = await knex("slots").where({ workspace_id: 1, code: "C0001" }).select("id");
102
+ const statements = async (lock) => {
103
+ // MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
104
+ await slots.withTransaction(IN_WORKSPACE_A, lock);
105
+ return slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
106
+ const { result, count: sent } = await countQueries(knex, () => lock(tx));
107
+ assert.equal([result].flat().length, 1);
108
+ return sent;
109
+ });
110
+ };
111
+ costs.push({
112
+ lock: await statements((tx) => slots.lock(String(id), tx)),
113
+ "lockWhere limit 1": await statements((tx) => slots.lockWhere({ code: "C0001" }, { ...tx, limit: 1 })),
114
+ lockWhere: await statements((tx) => slots.lockWhere({ code: "C0001" }, tx))
115
+ });
116
+ }
117
+ // SQLite's first lock in a transaction takes its write lock first. Without a limit, PostgreSQL reads again
118
+ // under its locks, for rows that started to match while it waited.
119
+ const one = client === "better-sqlite3" ? 2 : 1;
120
+ const expected = { lock: one, "lockWhere limit 1": one, lockWhere: client === "pg" ? 2 : one };
121
+ assert.deepEqual(costs, [expected, expected]);
122
+ }],
123
+
124
+ ["lockPages locks every row a page at a time in id order, the same statements for 3 pages among 25 rows and 250", async (t) => {
125
+ const sizes = [];
126
+ for (const [count, pageSize] of [[25, 10], [250, 100]]) {
127
+ const knex = await connect(t, `da_lp_pages_${count}`);
128
+ const { slots } = await slotsOf(knex, count);
129
+ const lockAll = (tx) => pagesOf(slots.lockPages({}, { ...tx, pageSize, fields: ["code"] }));
130
+ // MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
131
+ await slots.withTransaction(IN_WORKSPACE_A, lockAll);
132
+ const { result: pages, count: statements } = await slots.withTransaction(IN_WORKSPACE_A, (tx) => countQueries(knex, () => lockAll(tx)));
133
+ assert.deepEqual(pages.flat().map(({ code }) => code), Array.from({ length: count }, (_, index) => codeOf(index)));
134
+ sizes.push({ pages: pages.map((page) => page.length), statements });
135
+ }
136
+ assert.deepEqual(sizes.map(({ pages }) => pages), [[10, 10, 5], [100, 100, 50]]);
137
+ assert.equal(sizes[1].statements, sizes[0].statements);
138
+ }],
139
+
140
+ ["lockPages locks the rows committed since the transaction first read plainly", async (t) => {
141
+ const knex = await connect(t, "da_lp_current");
142
+ if (knex.client.config.client === "better-sqlite3") {
143
+ t.skip("SQLite has one writer, so no row commits while the transaction is open");
144
+ return;
145
+ }
146
+ const { slots } = await slotsOf(knex, 3);
147
+ const codes = await slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
148
+ // A plain read first: on MySQL and MariaDB it fixes the transaction's snapshot.
149
+ assert.equal((await slots.queryAll({}, tx)).length, 3);
150
+ await knex("slots").insert({ workspace_id: 1, code: "C0100", turn: 0 });
151
+ return (await pagesOf(slots.lockPages({}, { ...tx, pageSize: 2 }))).flat().map(({ code }) => code);
152
+ });
153
+ assert.deepEqual(codes, ["C0000", "C0001", "C0002", "C0100"]);
154
+ }],
155
+
156
+ ["lockPages throws at the request row limit, locks without one in background work, and refuses sort, limit and a bad pageSize", async (t) => {
157
+ const knex = await connect(t, "da_lp_limit");
158
+ const { slots, system } = await slotsOf(knex, 7, { requestRowLimit: 5 });
159
+ const read = [];
160
+ await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
161
+ for await (const page of slots.lockPages({}, { ...tx, pageSize: 3 })) {
162
+ read.push(page.length);
163
+ }
164
+ }), (error) => error.code === "RESOURCE_ROW_LIMIT" && /slots\.lockPages\(\) read more than 5 rows inside a request/u.test(error.message));
165
+ assert.deepEqual(read, [3]);
166
+ const job = await slots.withTransaction({ context: system.forWorkspace("1") }, (tx) => pagesOf(slots.lockPages({}, { ...tx, pageSize: 3 })));
167
+ assert.deepEqual(job.map((page) => page.length), [3, 3, 1]);
168
+ for (const options of [{ sort: ["code"] }, { limit: 2 }, { pageSize: 0 }, { pageSize: 1001 }, { pageSize: 1.5 }]) {
169
+ await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, (tx) => pagesOf(slots.lockPages({}, { ...tx, ...options }))),
170
+ (error) => error instanceof TypeError && /slots\.lockPages\(\)/u.test(error.message), JSON.stringify(options));
171
+ }
172
+ }],
173
+
174
+ ["lockPages throws, rather than page forever, when its storage answers the page before again", async (t) => {
175
+ const knex = await connect(t, "da_lp_stuck");
176
+ const { slots, system, api } = await slotsOf(knex, 4);
177
+ // A storage whose lockWhere ignores after, as json-rest-api's did before it took after, in background work,
178
+ // which has no row limit to stop it.
179
+ const storage = api.resources.slots;
180
+ const lockWhere = storage.lockWhere;
181
+ storage.lockWhere = (params, context) => lockWhere.call(storage, { ...params, after: undefined }, context);
182
+ const read = [];
183
+ await assert.rejects(slots.withTransaction({ context: system.forWorkspace("1") }, async (tx) => {
184
+ for await (const page of slots.lockPages({}, { ...tx, pageSize: 2 })) {
185
+ read.push(page.map(({ code }) => code));
186
+ if (read.length > 10) {
187
+ throw new Error("lockPages answered more than 10 pages: its pages never end");
188
+ }
189
+ }
190
+ }), /slots\.lockPages\(\) read the row "2" again in the page after it/u);
191
+ assert.deepEqual(read, [["C0000", "C0001"]]);
192
+ }]
193
+ ];
194
+ }
195
+
196
+ export { lockWhereOrderCases };
@@ -0,0 +1,115 @@
1
+ import assert from "node:assert/strict";
2
+ import knexLib from "knex";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { createTestResourceRuntime } from "../../src/test/index.js";
5
+
6
+ // A row policy that asks another owner through its handle, during a write whose caller gave no transaction:
7
+ // json-rest-api opens the write's own, the policy runs inside it (the lookup before a patch, the read-back after a
8
+ // create), and its options name that transaction, so the owner's read joins it. On a client with one connection a read
9
+ // outside it would wait for the connection the write holds until the pool gives up. Each database's test file runs
10
+ // these cases on its own connection.
11
+
12
+ const asPerson = (userId) => ({ context: { actor: { id: userId }, workspace: { id: "1" } } });
13
+
14
+ const memberResource = defineTableResource({
15
+ name: "teamMembers",
16
+ tableName: "team_members",
17
+ ownership: "workspace",
18
+ schema: {
19
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
20
+ userId: { type: "string", required: true, search: true, storage: { column: "user_id" } },
21
+ role: { type: "string", required: true, search: true }
22
+ }
23
+ });
24
+ const taskResource = defineTableResource({
25
+ name: "tasks",
26
+ tableName: "tasks",
27
+ ownership: "workspace",
28
+ schema: {
29
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
30
+ createdBy: { type: "string", required: true, storage: { column: "created_by" } },
31
+ title: { type: "string", required: true }
32
+ }
33
+ });
34
+
35
+ /**
36
+ * A client of `shared`'s database with one connection, which gives up waiting for it after 2 seconds; person 1 a
37
+ * member and person 2 a lead of workspace 1's team; tasks whose policy shows a lead every task and anyone else theirs,
38
+ * asking the teams' owner through its handle. `seen` records whether each of the owner's reads had a transaction.
39
+ * @param {import("knex").Knex} shared
40
+ */
41
+ async function teamsAndTasks(shared) {
42
+ const { config } = shared.client;
43
+ const knex = knexLib({ ...config, pool: { ...config.pool, min: 0, max: 1 }, acquireConnectionTimeout: 2000 });
44
+ await knex.schema.createTable("team_members", (table) => {
45
+ table.increments("id");
46
+ table.integer("workspace_id").nullable().index();
47
+ table.string("user_id").notNullable();
48
+ table.string("role").notNullable();
49
+ });
50
+ await knex.schema.createTable("tasks", (table) => {
51
+ table.increments("id");
52
+ table.integer("workspace_id").nullable().index();
53
+ table.string("created_by").notNullable();
54
+ table.string("title").notNullable();
55
+ });
56
+ await knex("team_members").insert([{ workspace_id: 1, user_id: "1", role: "member" }, { workspace_id: 1, user_id: "2", role: "lead" }]);
57
+ const runtime = await createTestResourceRuntime({ knex });
58
+ const { teamMembers } = await runtime.own("teams.feature", [{ resource: memberResource }]);
59
+ const seen = new Set();
60
+ const teams = {
61
+ async isLead(userId, options) {
62
+ seen.add(options.trx ? "in a transaction" : "in none");
63
+ return (await teamMembers.queryAll({ filters: { userId, role: "lead" }, take: 1 }, options)).length > 0;
64
+ }
65
+ };
66
+ const { tasks } = await runtime.own("tasks.feature", [{
67
+ resource: taskResource,
68
+ rowPolicy: async ({ query, caller, column, value, options, requires }) => {
69
+ if (caller.kind !== "user") {
70
+ return caller.kind !== "anonymous";
71
+ }
72
+ if (!(await requires.teams.isLead(caller.userId, options))) {
73
+ query.where(column("createdBy"), value("createdBy", caller.userId));
74
+ }
75
+ return true;
76
+ }
77
+ }], { requires: { teams } });
78
+ // What one call answers, and where the owner's reads ran during it.
79
+ const call = async (run) => {
80
+ seen.clear();
81
+ const result = await run();
82
+ return { result, seen: [...seen] };
83
+ };
84
+ return { knex, tasks, call };
85
+ }
86
+
87
+ /**
88
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
89
+ * The test's own empty database; `suffix` names it where the database needs a name.
90
+ */
91
+ function policyTransactionCases(connect) {
92
+ return [
93
+ ["a row policy that asks another owner's handle joins the transaction a write opened for a caller that named none", async (t) => {
94
+ const { knex, tasks, call } = await teamsAndTasks(await connect(t, "da_pt"));
95
+ try {
96
+ const inOne = ["in a transaction"];
97
+ const created = await call(() => tasks.create({ createdBy: "1", title: "first" }, asPerson("1")));
98
+ assert.deepEqual({ title: created.result.title, seen: created.seen }, { title: "first", seen: inOne });
99
+ const patched = await call(() => tasks.patch(created.result.id, { title: "second" }, asPerson("1")));
100
+ assert.deepEqual({ title: patched.result.title, seen: patched.seen }, { title: "second", seen: inOne });
101
+ // In the caller's own transaction, as before; and a read outside any reads the owner outside any too.
102
+ const inCallers = await call(() => tasks.withTransaction(asPerson("1"), (tx) => tasks.patch(created.result.id, { title: "third" }, tx)));
103
+ assert.deepEqual(inCallers.seen, inOne);
104
+ const read = await call(() => tasks.queryAll({}, asPerson("2")));
105
+ assert.deepEqual({ titles: read.result.map(({ title }) => title), seen: read.seen }, { titles: ["third"], seen: ["in none"] });
106
+ // The owner's answer still decides: person 3, no lead, made no task.
107
+ assert.deepEqual(await tasks.queryAll({}, asPerson("3")), []);
108
+ } finally {
109
+ await knex.destroy();
110
+ }
111
+ }]
112
+ ];
113
+ }
114
+
115
+ export { policyTransactionCases };
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
3
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { passedOn, resolveWorkspaceScopeValue } from "../../src/server/index.js";
5
+ import { createTestResourceRuntime } from "../../src/test/index.js";
6
+
7
+ // A row policy that reads another owner's rows as stored, on every database the runtime supports: the folders' owner
8
+ // answers its folders to the documents' policy through a join source under its own system scope, narrowed to the call's
9
+ // workspace, so a document in an open folder is visible to a person who may not see the folder itself, and never
10
+ // through another workspace's folder. Each database's test file runs these cases on its own connection.
11
+
12
+ const asPerson = (userId, workspaceId = "1") => ({ context: { actor: { id: userId }, workspace: { id: workspaceId } } });
13
+
14
+ const folderResource = defineTableResource({
15
+ name: "folders",
16
+ tableName: "folders",
17
+ ownership: "workspace",
18
+ schema: {
19
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
20
+ createdBy: { type: "string", required: true, storage: { column: "created_by" } },
21
+ status: { type: "string", required: true }
22
+ }
23
+ });
24
+ const documentResource = defineTableResource({
25
+ name: "documents",
26
+ tableName: "documents",
27
+ ownership: "workspace",
28
+ schema: {
29
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
30
+ folderId: { type: "id", required: true, storage: { column: "folder_id" } },
31
+ title: { type: "string", required: true }
32
+ }
33
+ });
34
+
35
+ /**
36
+ * Workspace 1's folders 1 (open, made by person 2) and 2 (closed, made by person 1), workspace 2's folder 3 (open);
37
+ * `count` documents in each folder of workspace 1 and, in workspace 1, as many naming workspace 2's folder.
38
+ */
39
+ async function foldersAndDocuments(knex, count) {
40
+ await knex.schema.createTable("folders", (table) => {
41
+ table.increments("id");
42
+ table.integer("workspace_id").nullable().index();
43
+ table.string("created_by").notNullable();
44
+ table.string("status").notNullable();
45
+ });
46
+ await knex.schema.createTable("documents", (table) => {
47
+ table.increments("id");
48
+ table.integer("workspace_id").nullable().index();
49
+ table.integer("folder_id").notNullable().index();
50
+ table.string("title").notNullable();
51
+ });
52
+ await knex("folders").insert([
53
+ { workspace_id: 1, created_by: "2", status: "open" },
54
+ { workspace_id: 1, created_by: "1", status: "closed" },
55
+ { workspace_id: 2, created_by: "2", status: "open" }
56
+ ]);
57
+ const documents = [1, 2, 3].flatMap((folderId) => Array.from({ length: count }, (_, index) => ({
58
+ workspace_id: 1, folder_id: folderId, title: `${folderId}-${String(index).padStart(3, "0")}`
59
+ })));
60
+ for (let start = 0; start < documents.length; start += 200) {
61
+ await knex("documents").insert(documents.slice(start, start + 200));
62
+ }
63
+ const runtime = await createTestResourceRuntime({ knex });
64
+ // A person sees the folders they made; background work sees its scope's.
65
+ const { folders } = await runtime.own("folders.feature", [{
66
+ resource: folderResource,
67
+ rowPolicy: ({ query, caller, column, value }) => {
68
+ if (caller.kind === "user") query.where(column("createdBy"), value("createdBy", caller.userId));
69
+ return caller.kind !== "anonymous";
70
+ }
71
+ }]);
72
+ const systemContext = runtime.declareSystemScope("folders.feature", "answer folders as stored to the documents' row policy");
73
+ // The folders' owner API: its folders as stored, in the caller's workspace, for another owner's row policy.
74
+ const folderStatuses = {
75
+ storedSource({ alias }, options) {
76
+ const context = systemContext("the documents' row policy reads each folder's status as stored")
77
+ .forWorkspace(resolveWorkspaceScopeValue(options.context));
78
+ return folders.joinSource({ alias }, { ...passedOn(options), context });
79
+ }
80
+ };
81
+ // A person sees the documents of the open folders, as stored: a folder they may not see counts too.
82
+ const { documents: documentsHandle } = await runtime.own("documents.feature", [{
83
+ resource: documentResource,
84
+ rowPolicy: async ({ query, caller, column, options, requires }) => {
85
+ if (caller.kind !== "user") return caller.kind !== "anonymous";
86
+ const folder = await requires.folders.storedSource({ alias: "f" }, options);
87
+ query.whereExists(folder.query.select(1).whereColumn(folder.column("id"), column("folderId")).where(folder.column("status"), "open"));
88
+ return true;
89
+ }
90
+ }], { requires: { folders: folderStatuses } });
91
+ return { folders, documents: documentsHandle };
92
+ }
93
+
94
+ /**
95
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
96
+ * The test's own empty database; `suffix` names it where the database needs a name.
97
+ */
98
+ function storedSourceCases(connect) {
99
+ return [
100
+ ["a row policy reads another owner's rows as stored in the call's workspace, and a page of them costs one statement among 3 and 300 documents", async (t) => {
101
+ const costs = [];
102
+ for (const count of [3, 300]) {
103
+ const knex = await connect(t, `da_ss_${count}`);
104
+ const { folders, documents } = await foldersAndDocuments(knex, count);
105
+ // Person 1 sees folder 2 only, yet the documents of folder 1, which is open; never those naming workspace 2's
106
+ // open folder 3, and never the closed folder 2's.
107
+ assert.deepEqual((await folders.queryAll({}, asPerson("1"))).map(({ id }) => id), ["2"]);
108
+ const { result, count: statements } = await countQueries(knex, () => documents.queryAll({ take: 20 }, asPerson("1")));
109
+ assert.equal(result.length, Math.min(count, 20));
110
+ assert.deepEqual([...new Set(result.map(({ folderId }) => String(folderId)))], ["1"]);
111
+ // In a transaction the stored read joins the caller's.
112
+ const inTransaction = await documents.withTransaction(asPerson("1"), (tx) => documents.queryAll({ take: 1 }, tx));
113
+ assert.deepEqual(inTransaction.map(({ folderId }) => String(folderId)), ["1"]);
114
+ costs.push(statements);
115
+ }
116
+ assert.deepEqual(costs, [1, 1]);
117
+ }]
118
+ ];
119
+ }
120
+
121
+ export { storedSourceCases };