@jskit-ai/resource-runtime 0.2.39 → 0.2.41

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.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.)
5
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.
6
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.
7
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.39",
3
+ "version": "0.2.41",
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.218",
19
- "@jskit-ai/resource-crud-core": "0.1.220",
20
- "json-rest-api": "3.3.1"
18
+ "@jskit-ai/resource-core": "0.1.219",
19
+ "@jskit-ai/resource-crud-core": "0.1.221",
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": {
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.276",
68
- "@jskit-ai/kernel": "0.2.27"
67
+ "@jskit-ai/database-runtime": "0.1.277",
68
+ "@jskit-ai/kernel": "0.2.28"
69
69
  }
70
70
  }
@@ -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)) {
@@ -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
+ });