@jskit-ai/resource-runtime 0.2.38 → 0.2.40

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.3.2 exactly (from 3.3.1): on MariaDB a locking read with a list of 1,000 values or more (`in_predicate_conversion_threshold`), of the column's type, was planned as a join with a table of the values, which could read a key's leading columns and lock every row they matched: a `lockWhere` of 1,000 records' current revisions by record and revision number held every revision of those records. Every lock (`lock`, `lockMany`, `lockWhere`, `lockPages`, `claim`, a locking `aggregate`), its link checks and a write's lock of the records it links to now send a longer list as an OR of lists below the server's threshold, and hold the rows the list names alone; a write's lock of its targets reads their primary key on MySQL and MariaDB, so on MariaDB a list naming much of the table is no longer read by scanning it, holding every owner's rows.
6
+ - A lock's `include` reads its own rows' links through the primary key on MySQL and MariaDB (`FORCE INDEX (PRIMARY)`), in lists below MariaDB's `in_predicate_conversion_threshold`: on MariaDB a lock of 1,000 of a table's 2,400 rows with an include read its links by scanning the whole table and held every row, other owners' included, until commit, and now holds those rows alone. (MySQL 8.4 can still read a list that names a large share of a small table through the whole primary key, as json-rest-api's scoped-reads guide says.)
7
+ - Depends on json-rest-api 3.3.1 exactly (from 3.3.0): on MySQL and MariaDB a lock's to-one link check (in `lock`, `lockMany`, `lockWhere` and `lockPages`) reads the linked table through its primary key (`FORCE INDEX (PRIMARY)`) and holds the linked rows alone, where it could read and hold, until commit, every row of the caller's range of an index that starts with the ownership columns, or, on MariaDB with a long id list, every row of the table, other owners' rows too.
8
+ - `lockPages(filters, { ...txOptions, take })` takes `take`, as `queryAll` does (a whole number from 1, else a `TypeError` before any statement): the most rows the call locks, its own bound in a request or in background work, above or below the request row limit. Past it the call throws `RowLimitError` (400 `RESOURCE_ROW_LIMIT`) naming the take, before it hands over the page that passed it, so a lock never answers part of the set. Without `take` nothing changes: a request stops past the request row limit and background work locks without a bound.
5
9
  - Depends on json-rest-api 3.3.0 exactly (from 3.2.0): `aggregate({ measures, filters }, { ...txOptions, lockMode })`, with `lockMode` `"share"`, `"update"` or `"noKeyUpdate"`, reads one row of totals from one statement with that row lock on the rows they read, held until the transaction ends, so a save that checks a count or a sum keeps it as read: an update or delete of a counted row waits until commit (on MySQL and MariaDB an insert the totals would count waits too, as InnoDB locks the index range read; on PostgreSQL it goes on, and json-rest-api reads the totals again until no row joined them while it waited). No row is read into the application, however many match (json-rest-api totals 2,000 rows exactly in the statements it takes for 3), where `lockWhere` and a count read every id and stop at 1,000. With `lockMode`, `groupBy` or `page` is a `TypeError` (total each group with a measure's `where`) and a call outside a transaction is `RestApiLockOutsideTransactionError`, before any statement; json-rest-api refuses a filter on another table's field or a row policy that joins another table (rule `lock_single_table`) and, on MySQL and MariaDB, a read with no index that starts with the ownership columns, as `lockWhere` does. Its single-table refusal of every lock and claim (`lock_single_table`) now names the fix: filter on the resource's own fields, and have a row policy test another table in a subquery, not a join.
6
10
  - A request's user scope is the signed-in user on every route, as its workspace is: the user scope reads the context's `scopeValues.userId`, the route's visibility user and now the signed-in user (`resolveActorId`: the context's actor, else the request's user). So a `workspace` route (a CRUD feature that names `visibility: "workspace"`, a hand route's `callOptions()`, an action) reaches the signed-in member's own rows of a `user` or `workspace_user` table, and stamps them on its creates, where it threw `MissingScopeError` and an application set `scopeValues.userId` by hand; a `workspace_user` route reached them already. The input never names the user: an owner value in it that differs is refused, a signed-out request still names no user (`MissingScopeError`, whose message now says that a request reaches the signed-in user's own rows), and a job context from `forUser` or `forWorkspaceUser` is signed in as no one. Sources that name two different users throw the safety invariant, as the scope value and the visibility user did.
7
11
  - Depends on json-rest-api 3.2.0 exactly (from 3.1.11): a row policy's `ownTable(name)` reader and a `joinSource()`'s `query` take `forceIndex(...names)` on MySQL and MariaDB, which makes the table the read reads (the owner's table inside a join source's derived tables) use the named indexes. A lock's row policy nests its reads in SELECTs that lock every row their plan examines, so a nested read the planner would answer by scanning a shared table, another workspace's rows included, names the index that leads with the owner's columns and examines only the caller's range. It takes plain index names only, sets the hint once, and throws a `TypeError` on PostgreSQL and SQLite, which have no index hints; the builders stay read-only.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.38",
3
+ "version": "0.2.40",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -17,7 +17,7 @@
17
17
  "dependencies": {
18
18
  "@jskit-ai/resource-core": "0.1.218",
19
19
  "@jskit-ai/resource-crud-core": "0.1.220",
20
- "json-rest-api": "3.3.0"
20
+ "json-rest-api": "3.3.2"
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": {
@@ -86,22 +86,27 @@ class PageSizeError extends TypeError {
86
86
  }
87
87
 
88
88
  /**
89
- * queryAll() or queryPages() in a request context reading past the request row limit: the request answers a 400 coded
90
- * RESOURCE_ROW_LIMIT, with a sentence the client can show in the user's language, instead of a 500.
89
+ * queryAll(), queryPages() or lockPages() in a request context reading past the request row limit, or lockPages()
90
+ * matching more rows than its `take`: the request answers a 400 coded RESOURCE_ROW_LIMIT, with a sentence the client
91
+ * can show in the user's language, instead of a 500.
91
92
  */
92
93
  class RowLimitError extends AppError {
93
94
  /**
94
95
  * @param {string} resourceName
95
- * @param {number} rowLimit
96
+ * @param {number} rowLimit The request row limit, or the call's `take` when `bound` is "take".
96
97
  * @param {unknown} [cause]
97
98
  * @param {"queryAll" | "queryPages" | "lockPages"} [caller]
99
+ * @param {"request" | "take"} [bound] Which limit `rowLimit` is.
98
100
  */
99
- constructor(resourceName, rowLimit, cause, caller = "queryAll") {
101
+ constructor(resourceName, rowLimit, cause, caller = "queryAll", bound = "request") {
100
102
  super(
101
103
  400,
102
- `${resourceName}.${caller}() read more than ${rowLimit} rows inside a request. Work over that many rows belongs ` +
103
- "in a background job: a feature with systemScope, working per workspace with systemContext(reason).forWorkspace(id), " +
104
- "where queryPages() reads them a page at a time.",
104
+ bound === "take"
105
+ ? `${resourceName}.${caller}() matched more than its take of ${rowLimit} rows, the most the call holds. Raise ` +
106
+ "take to the most rows the work can hold, or narrow the filters."
107
+ : `${resourceName}.${caller}() read more than ${rowLimit} rows inside a request. Work over that many rows belongs ` +
108
+ "in a background job: a feature with systemScope, working per workspace with systemContext(reason).forWorkspace(id), " +
109
+ "where queryPages() reads them a page at a time.",
105
110
  { cause, code: "RESOURCE_ROW_LIMIT", messageCode: "resource.rowLimit", messageParams: { rowLimit } }
106
111
  );
107
112
  this.name = "RowLimitError";
@@ -77,6 +77,17 @@ function aggregateTransactionOf(name, { groupBy, page }, options) {
77
77
  // The most rows one read of the locked rows' links names, as the lock itself reads its ids in chunks of 1,000.
78
78
  const LINKS_PER_READ = 1000;
79
79
 
80
+ /**
81
+ * The most ids one read of the locked rows' links names: LINKS_PER_READ, and on MariaDB fewer than the server's
82
+ * in_predicate_conversion_threshold, which json-rest-api reads as it starts. MariaDB turns an IN list that long into a
83
+ * join, which a locking read may plan through other rows than the listed ones, and lock them too.
84
+ * @param {{ knex: { capabilities?: { dbInfo?: { inPredicateConversionThreshold?: number } } } }} api
85
+ */
86
+ function linksPerRead(api) {
87
+ const threshold = api.knex.capabilities?.dbInfo?.inPredicateConversionThreshold;
88
+ return Number.isSafeInteger(threshold) && threshold > 1 ? Math.min(LINKS_PER_READ, threshold - 1) : LINKS_PER_READ;
89
+ }
90
+
80
91
  // The most rows a page of lockPages() locks: json-rest-api's most for one lockWhere.
81
92
  const MAX_LOCK_PAGE = 1000;
82
93
 
@@ -118,8 +129,9 @@ function lockedIncludes(resource, caller, include) {
118
129
  * record is visible. `include` names belongs-to relationships whose records the
119
130
  * lock locks too, after its own rows (see withLockedIncludes).
120
131
  * @param {object} dependencies
121
- * @param {{ knex: { instance: any, helpers: { getStorageAdapter(scopeName: string): any } } }} dependencies.api
122
- * The table's json-rest-api host, whose storage adapter names the table's columns.
132
+ * @param {{ knex: { instance: any, helpers: { getStorageAdapter(scopeName: string): any }, capabilities?: { dbInfo?: { inPredicateConversionThreshold?: number } } } }} dependencies.api
133
+ * The table's json-rest-api host, whose storage adapter names the table's columns and whose capabilities name the
134
+ * database server's limits.
123
135
  * @param {string} dependencies.name The resource's name.
124
136
  * @param {{ name: string, tableName: string, schema: Record<string, any> }} dependencies.resource
125
137
  * @param {() => Record<string, any>} dependencies.jsonRest The table's json-rest-api resource.
@@ -161,7 +173,10 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
161
173
  * The locked rows' links as the database holds them now, `{ [field]: id | null }` by row id, for the belongs-to
162
174
  * fields named: on MySQL and MariaDB a locking read (FOR SHARE, of rows this transaction already holds), which sees
163
175
  * them as locked whatever snapshot the transaction's plain reads keep; elsewhere a plain read, which sees them too.
164
- * The rows are the lock's own, so its scope already applied: only their links are read.
176
+ * The rows are the lock's own, so its scope already applied: only their links are read. The locking read goes
177
+ * through the primary key (FORCE INDEX), in id lists MariaDB keeps as lists (see linksPerRead), so it examines, and
178
+ * holds, those rows alone: left to choose, the optimizer reads a list that names much of the table by scanning the
179
+ * whole table, and InnoDB then holds every row it passed, every owner's, until the transaction ends.
165
180
  * @param {string[]} ids
166
181
  * @param {string[]} fields
167
182
  * @param {{ trx: any }} options
@@ -170,10 +185,14 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
170
185
  const adapter = api.knex.helpers.getStorageAdapter(name);
171
186
  const idColumn = adapter.getIdColumn();
172
187
  const locking = detectDialectFromClient(options.trx) === "mysql";
188
+ const table = locking && !adapter.isCanonical()
189
+ ? options.trx.raw("?? force index (primary)", [resource.tableName])
190
+ : resource.tableName;
191
+ const perRead = locking ? linksPerRead(api) : LINKS_PER_READ;
173
192
  const links = new Map();
174
- for (let start = 0; start < ids.length; start += LINKS_PER_READ) {
175
- const part = ids.slice(start, start + LINKS_PER_READ).map((id) => adapter.translateFilterValue("id", id));
176
- const read = options.trx(resource.tableName)
193
+ for (let start = 0; start < ids.length; start += perRead) {
194
+ const part = ids.slice(start, start + perRead).map((id) => adapter.translateFilterValue("id", id));
195
+ const read = options.trx.from(table)
177
196
  .whereIn(idColumn, part)
178
197
  .select({ id: idColumn, ...Object.fromEntries(fields.map((field) => [field, adapter.translateColumn(field)])) });
179
198
  for (const row of await (locking ? read.forShare() : read)) {
@@ -327,31 +346,38 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
327
346
  * rows first locks one row that governs them (their parent, say), and so does this work, before it reads. On MySQL
328
347
  * and MariaDB it needs an index that reads in id order after the ownership columns and the filters' single-value
329
348
  * equalities. In a request it throws RowLimitError past the request row limit, as queryPages() does; background
330
- * work locks without one. `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
349
+ * work locks without one. `take`, as queryAll()'s, names the call's own bound instead, in a request or background
350
+ * work: the most rows it locks, a whole number from 1, above the request row limit or below it. Past it, it throws
351
+ * RowLimitError naming take, before it hands over the page that passed it, so a lock never answers part of the set.
352
+ * `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
331
353
  * `pageBy` names a list filter of the filters (one whose search entry says `filterOperator: "in"`, on the table's
332
354
  * own column): the pages then follow that column, then the id, so on MySQL and MariaDB an index that starts with the
333
355
  * ownership columns, the filters' other single-value equalities and that column reads only the listed values' rows
334
356
  * (see listPages). Its values are given as the column stores them.
335
357
  * @param {object} filters
336
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number, pageBy?: string }} options
358
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number, pageBy?: string, take?: number }} options
337
359
  * @returns {AsyncGenerator<object[], void, undefined>}
338
360
  */
339
361
  async function* lockPages(filters, options) {
340
362
  requireDefinedFilters(name, "lockPages", filters);
341
- const { pageSize = MAX_LOCK_PAGE, sort, limit, pageBy, ...lockOptions } = options;
363
+ const { pageSize = MAX_LOCK_PAGE, sort, limit, pageBy, take, ...lockOptions } = options;
342
364
  if (sort !== undefined || limit !== undefined) {
343
365
  throw new TypeError(`${name}.lockPages() locks in id order, a page of pageSize rows at a time, so it takes no sort or limit.`);
344
366
  }
345
367
  if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > MAX_LOCK_PAGE) {
346
368
  throw new TypeError(`${name}.lockPages() pageSize is an integer from 1 to ${MAX_LOCK_PAGE}. Received: ${JSON.stringify(pageSize)}`);
347
369
  }
370
+ // take: undefined is no take, as for queryAll().
371
+ if (take !== undefined && (!Number.isSafeInteger(take) || /** @type {number} */ (take) < 1)) {
372
+ throw new TypeError(`${name}.lockPages() take is the most rows it locks, a whole number from 1. Received: ${JSON.stringify(take)}`);
373
+ }
348
374
  const pages = pageBy === undefined ? idPages(filters, pageSize, lockOptions) : listPages(filters, listFilterOf(pageBy, filters), pageSize, lockOptions);
349
- const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
375
+ const rowLimit = take ?? (isJobContext(options.context) ? undefined : settings.requestRowLimit);
350
376
  let rows = 0;
351
377
  for await (const page of pages) {
352
378
  rows += page.length;
353
379
  if (rowLimit !== undefined && rows > rowLimit) {
354
- throw new RowLimitError(name, rowLimit, undefined, "lockPages");
380
+ throw new RowLimitError(name, rowLimit, undefined, "lockPages", take === undefined ? "request" : "take");
355
381
  }
356
382
  if (page.length > 0) {
357
383
  yield page;
@@ -0,0 +1,172 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { createTestResourceRuntime } from "../src/test/index.js";
5
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
6
+
7
+ // A lock of a thousand rows on MariaDB holds those rows alone. InnoDB holds every row a locking read examines until
8
+ // the transaction ends, so each of the lock's reads names its rows through a key: the links a lock's include reads go
9
+ // through the primary key (left to choose, the optimizer scans a table that the list names much of, and holds every
10
+ // owner's rows), and a list filter of 1,000 values or more stays a list (MariaDB turns one that long into a join,
11
+ // which reads a key's leading columns and holds every row they match, every revision of the listed records below).
12
+ // MySQL 8.4 reads a list that names this large a share of a table through its whole primary key, and holds every row,
13
+ // as json-rest-api's scoped-reads guide says. Workspace 1 and workspace 2 each have 1,200 records with revisions 1 to 4 and a current one (10 for
14
+ // an even record, 11 for an odd one), and 1,200 tasks, each naming a stage of its own.
15
+
16
+ const RECORDS = 1200;
17
+ const WORKSPACE = Object.freeze({ context: Object.freeze({ workspace: Object.freeze({ id: "1" }) }) });
18
+ const currentOf = (record) => (record % 2 === 0 ? 10 : 11);
19
+
20
+ const workspaceId = { type: "id", nullable: true, storage: { column: "workspace_id" } };
21
+ const revisionResource = defineTableResource({
22
+ name: "revisions",
23
+ tableName: "revisions",
24
+ ownership: "workspace",
25
+ searchSchema: {
26
+ recordIds: { type: "array", actualField: "recordId", filterOperator: "in" },
27
+ numbers: { type: "array", actualField: "number", filterOperator: "in" }
28
+ },
29
+ schema: {
30
+ workspaceId,
31
+ recordId: { type: "integer", required: true, storage: { column: "record_id" } },
32
+ number: { type: "integer", required: true },
33
+ name: { type: "string", required: true }
34
+ }
35
+ });
36
+ const stageResource = defineTableResource({
37
+ name: "stages",
38
+ tableName: "stages",
39
+ ownership: "workspace",
40
+ schema: { workspaceId, name: { type: "string", required: true } }
41
+ });
42
+ const taskResource = defineTableResource({
43
+ name: "tasks",
44
+ tableName: "tasks",
45
+ ownership: "workspace",
46
+ schema: {
47
+ workspaceId,
48
+ stageId: { type: "id", nullable: true, belongsTo: "stages", as: "stage", storage: { column: "stage_id" } },
49
+ name: { type: "string", required: true }
50
+ }
51
+ });
52
+
53
+ async function database(t, suffix) {
54
+ const knex = await ownMysqlDatabase(t, suffix);
55
+ await knex.schema.createTable("revisions", (table) => {
56
+ table.increments("id");
57
+ table.integer("workspace_id").nullable();
58
+ table.integer("record_id").notNullable();
59
+ table.integer("number").notNullable();
60
+ table.string("name").notNullable();
61
+ table.unique(["workspace_id", "record_id", "number"], { indexName: "revisions_current" });
62
+ });
63
+ await knex.schema.createTable("stages", (table) => {
64
+ table.increments("id");
65
+ table.integer("workspace_id").nullable().index();
66
+ table.string("name").notNullable();
67
+ });
68
+ await knex.schema.createTable("tasks", (table) => {
69
+ table.increments("id");
70
+ table.integer("workspace_id").nullable().index();
71
+ table.integer("stage_id").nullable();
72
+ table.string("name").notNullable();
73
+ });
74
+ const insert = async (tableName, rows) => {
75
+ for (let start = 0; start < rows.length; start += 500) {
76
+ await knex(tableName).insert(rows.slice(start, start + 500));
77
+ }
78
+ };
79
+ const revisions = [];
80
+ const stages = [];
81
+ for (let record = 1; record <= RECORDS; record++) {
82
+ for (const workspace of [1, 2]) {
83
+ for (const number of [1, 2, 3, 4, currentOf(record)]) {
84
+ revisions.push({ workspace_id: workspace, record_id: record, number, name: `R${record}.${number}` });
85
+ }
86
+ stages.push({ workspace_id: workspace, name: `S${record}` });
87
+ }
88
+ }
89
+ await insert("revisions", revisions);
90
+ await insert("stages", stages);
91
+ await knex.raw("INSERT INTO tasks (workspace_id, stage_id, name) SELECT workspace_id, id, concat('T', name) FROM stages ORDER BY id");
92
+ await knex.raw("ANALYZE TABLE revisions, stages, tasks");
93
+ const runtime = await createTestResourceRuntime({ knex });
94
+ const handles = await runtime.own("history.feature", [revisionResource, stageResource, taskResource]);
95
+ const idOf = async (tableName, where) => String((await knex(tableName).where(where).first("id")).id);
96
+ return { knex, ...handles, idOf };
97
+ }
98
+
99
+ /**
100
+ * Whether another transaction can delete the row (a delete takes every index entry of it, as a lock read through a
101
+ * secondary index holds the entry) without waiting. It never commits.
102
+ */
103
+ async function free(knex, tableName, id) {
104
+ const rolledBack = new Error("rolled back");
105
+ try {
106
+ await knex.transaction(async (probe) => {
107
+ await probe.raw("SET SESSION innodb_lock_wait_timeout = 1");
108
+ await probe(tableName).where({ id }).delete();
109
+ throw rolledBack;
110
+ });
111
+ } catch (error) {
112
+ if (error === rolledBack) {
113
+ return true;
114
+ }
115
+ if (/^ER_LOCK_(NOWAIT|WAIT_TIMEOUT)$/u.test(error?.code ?? "")) {
116
+ return false;
117
+ }
118
+ throw error;
119
+ }
120
+ throw new Error("The probe committed.");
121
+ }
122
+
123
+ // 1,000 records' current revisions; and 1,200 records' revisions numbered 10, the even records' current ones, as
124
+ // lockWhere locks 1,000 rows at most.
125
+ test("lockWhere of 1,000 and 1,200 records' current revisions, the records given as numbers, holds those revisions alone", async (t) => {
126
+ const { knex, revisions, idOf } = await database(t, "da_ll_where");
127
+ for (const { count, numbers, matched } of [{ count: 1000, numbers: [10, 11], matched: 1000 }, { count: 1200, numbers: [10], matched: 600 }]) {
128
+ const recordIds = Array.from({ length: count }, (_, index) => index + 1);
129
+ const revision = (record, number, workspace = 1) => idOf("revisions", { workspace_id: workspace, record_id: record, number });
130
+ const rows = {
131
+ current: await revision(6, 10),
132
+ lastCurrent: await revision(count, 10),
133
+ past: await revision(6, 1),
134
+ lastPast: await revision(count, 2),
135
+ unlisted: count < RECORDS ? await revision(1100, 10) : await revision(5, 11),
136
+ otherWorkspace: await revision(6, 10, 2)
137
+ };
138
+ const held = await revisions.withTransaction(WORKSPACE, async (tx) => {
139
+ const locked = await revisions.lockWhere({ recordIds, numbers }, { ...tx, fields: ["name"] });
140
+ assert.equal(locked.length, matched);
141
+ const answer = {};
142
+ for (const [row, id] of Object.entries(rows)) {
143
+ answer[row] = !(await free(knex, "revisions", id));
144
+ }
145
+ return answer;
146
+ });
147
+ assert.deepEqual(held, { current: true, lastCurrent: true, past: false, lastPast: false, unlisted: false, otherWorkspace: false }, `${count} records`);
148
+ }
149
+ });
150
+
151
+ test("a lock of 1,000 tasks with their stages reads the tasks' links through the primary key, holding those tasks and stages alone", async (t) => {
152
+ const { knex, tasks, idOf } = await database(t, "da_ll_include");
153
+ const ids = (await knex("tasks").where({ workspace_id: 1 }).orderBy("id").limit(1000).pluck("id")).map(String);
154
+ const rows = {
155
+ task: ids[3],
156
+ unlistedTask: await idOf("tasks", { workspace_id: 1, name: `TS${RECORDS}` }),
157
+ otherWorkspaceTask: await idOf("tasks", { workspace_id: 2, name: "TS5" }),
158
+ unlinkedStage: await idOf("stages", { workspace_id: 1, name: `S${RECORDS}` }),
159
+ otherWorkspaceStage: await idOf("stages", { workspace_id: 2, name: "S5" })
160
+ };
161
+ const held = await tasks.withTransaction(WORKSPACE, async (tx) => {
162
+ const locked = await tasks.lockMany(ids, { ...tx, include: ["stage"] });
163
+ assert.equal(locked.length, 1000);
164
+ assert.ok(locked.every((task) => task.stage?.id === String(task.stageId)));
165
+ const answer = {};
166
+ for (const [row, id] of Object.entries(rows)) {
167
+ answer[row] = !(await free(knex, row.endsWith("Stage") ? "stages" : "tasks", id));
168
+ }
169
+ return answer;
170
+ });
171
+ assert.deepEqual(held, { task: true, unlistedTask: false, otherWorkspaceTask: false, unlinkedStage: false, otherWorkspaceStage: false });
172
+ });
@@ -3,6 +3,7 @@ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResourc
3
3
  import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
4
4
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
5
  import { createResourceHost } from "../../src/server/resourceHost.js";
6
+ import { RowLimitError } from "../../src/server/errors.js";
6
7
  import { createResourceRuntime } from "../../src/server/resourceRuntime.js";
7
8
 
8
9
  // lockWhere's sort and limit, on every database the runtime supports: the rows are locked in the sort's order, then by
@@ -224,6 +225,40 @@ function lockWhereOrderCases(connect) {
224
225
  }
225
226
  }],
226
227
 
228
+ ["lockPages with take locks up to take rows, past the request row limit, refuses more naming take in a request and in background work, and refuses a take that is no whole number from 1", async (t) => {
229
+ const knex = await connect(t, "da_lp_take");
230
+ // Seven rows of workspace 1, and a request row limit of five.
231
+ const { slots, system } = await slotsOf(knex, 7, { requestRowLimit: 5 });
232
+ const job = { context: system.forWorkspace("1") };
233
+ const sizes = (options, context = IN_WORKSPACE_A) =>
234
+ slots.withTransaction(context, async (tx) => (await pagesOf(slots.lockPages({}, { ...tx, pageSize: 3, ...options }))).map((page) => page.length));
235
+ // Under and at the bound, past the request row limit: every row, in a request and in background work.
236
+ for (const take of [9, 7]) {
237
+ assert.deepEqual(await sizes({ take }), [3, 3, 1], `take ${take}`);
238
+ assert.deepEqual(await sizes({ take }, job), [3, 3, 1], `take ${take} in background work`);
239
+ }
240
+ // take: undefined is no take: the request row limit, and none in background work.
241
+ await assert.rejects(sizes({ take: undefined }), (error) => error.code === "RESOURCE_ROW_LIMIT" && error.messageParams.rowLimit === 5);
242
+ assert.deepEqual(await sizes({}, job), [3, 3, 1]);
243
+ // Over the bound: RowLimitError naming take, before the page that passes it, in a request and in background work.
244
+ for (const context of [IN_WORKSPACE_A, job]) {
245
+ const read = [];
246
+ await assert.rejects(slots.withTransaction(context, async (tx) => {
247
+ for await (const page of slots.lockPages({}, { ...tx, pageSize: 3, take: 6 })) {
248
+ read.push(page.length);
249
+ }
250
+ }), (error) => error instanceof RowLimitError && error.code === "RESOURCE_ROW_LIMIT" && error.messageParams.rowLimit === 6 &&
251
+ /slots\.lockPages\(\) matched more than its take of 6 rows/u.test(error.message));
252
+ assert.deepEqual(read, [3, 3]);
253
+ }
254
+ // A take below the request row limit bounds a request too.
255
+ await assert.rejects(sizes({ take: 2 }), (error) => error.code === "RESOURCE_ROW_LIMIT" && error.messageParams.rowLimit === 2);
256
+ for (const take of [0, -1, 1.5, "7", null, Number.MAX_SAFE_INTEGER + 1]) {
257
+ await assert.rejects(sizes({ take }), (error) => error instanceof TypeError &&
258
+ /slots\.lockPages\(\) take is the most rows it locks, a whole number from 1/u.test(error.message), JSON.stringify(take));
259
+ }
260
+ }],
261
+
227
262
  ["lockPages throws, rather than page forever, when its storage answers the page before again", async (t) => {
228
263
  const knex = await connect(t, "da_lp_stuck");
229
264
  const { slots, system, api } = await slotsOf(knex, 4);