@jskit-ai/resource-runtime 0.2.38 → 0.2.39

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,8 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - 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.
6
+ - `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
7
  - 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
8
  - 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
9
  - 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.39",
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.1"
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";
@@ -327,31 +327,38 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
327
327
  * rows first locks one row that governs them (their parent, say), and so does this work, before it reads. On MySQL
328
328
  * and MariaDB it needs an index that reads in id order after the ownership columns and the filters' single-value
329
329
  * 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.
330
+ * work locks without one. `take`, as queryAll()'s, names the call's own bound instead, in a request or background
331
+ * work: the most rows it locks, a whole number from 1, above the request row limit or below it. Past it, it throws
332
+ * RowLimitError naming take, before it hands over the page that passed it, so a lock never answers part of the set.
333
+ * `fields`, `lockMode` and `include` are lockWhere's; it takes no sort or limit.
331
334
  * `pageBy` names a list filter of the filters (one whose search entry says `filterOperator: "in"`, on the table's
332
335
  * own column): the pages then follow that column, then the id, so on MySQL and MariaDB an index that starts with the
333
336
  * ownership columns, the filters' other single-value equalities and that column reads only the listed values' rows
334
337
  * (see listPages). Its values are given as the column stores them.
335
338
  * @param {object} filters
336
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number, pageBy?: string }} options
339
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], pageSize?: number, pageBy?: string, take?: number }} options
337
340
  * @returns {AsyncGenerator<object[], void, undefined>}
338
341
  */
339
342
  async function* lockPages(filters, options) {
340
343
  requireDefinedFilters(name, "lockPages", filters);
341
- const { pageSize = MAX_LOCK_PAGE, sort, limit, pageBy, ...lockOptions } = options;
344
+ const { pageSize = MAX_LOCK_PAGE, sort, limit, pageBy, take, ...lockOptions } = options;
342
345
  if (sort !== undefined || limit !== undefined) {
343
346
  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
347
  }
345
348
  if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > MAX_LOCK_PAGE) {
346
349
  throw new TypeError(`${name}.lockPages() pageSize is an integer from 1 to ${MAX_LOCK_PAGE}. Received: ${JSON.stringify(pageSize)}`);
347
350
  }
351
+ // take: undefined is no take, as for queryAll().
352
+ if (take !== undefined && (!Number.isSafeInteger(take) || /** @type {number} */ (take) < 1)) {
353
+ throw new TypeError(`${name}.lockPages() take is the most rows it locks, a whole number from 1. Received: ${JSON.stringify(take)}`);
354
+ }
348
355
  const pages = pageBy === undefined ? idPages(filters, pageSize, lockOptions) : listPages(filters, listFilterOf(pageBy, filters), pageSize, lockOptions);
349
- const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
356
+ const rowLimit = take ?? (isJobContext(options.context) ? undefined : settings.requestRowLimit);
350
357
  let rows = 0;
351
358
  for await (const page of pages) {
352
359
  rows += page.length;
353
360
  if (rowLimit !== undefined && rows > rowLimit) {
354
- throw new RowLimitError(name, rowLimit, undefined, "lockPages");
361
+ throw new RowLimitError(name, rowLimit, undefined, "lockPages", take === undefined ? "request" : "take");
355
362
  }
356
363
  if (page.length > 0) {
357
364
  yield page;
@@ -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);