@jskit-ai/resource-runtime 0.2.35 → 0.2.37

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,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - 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.
5
6
  - A row policy's `caller` for a user's context that says why it was made carries the reason: `{ kind: "user", userId, reason }`, as for the context `workspaces.roleContext` builds for installer and seed work. The reason grants nothing: the same read answers the same rows, refuses the same hidden fields and keeps the request row limits. A reason that is no text is none, and a context with a reason but no user is still anonymous.
6
7
  - `lockPages(filters, { ...txOptions, pageBy })` pages by a list filter's column, then the id: `pageBy` names a filter of the call whose search entry says `filterOperator: "in"`, on the table's own column, given a list. Each page locks up to `pageSize` rows of the values no page has passed, in that column's order, and the rest of the last value's rows follow in id order, that value alone, so on MySQL and MariaDB every statement reads one value's range after another of an index that holds the column after the ownership columns and the filters' other fixed columns, and examines and holds only the listed values' rows, where id order walks, and holds, every row of the owner it passes. Ten listed actions among 30 and among 300 send the same statements. A `pageBy` that names no such filter, or a filter given no list, is a TypeError before any statement; a value given otherwise than the column stores it throws rather than paging forever. Needs json-rest-api 3.1.11, whose `lockWhere` counts a list filter given one value as an equality when it picks its index.
7
8
  - Depends on json-rest-api 3.1.11 exactly (from 3.1.10): on MySQL and MariaDB `createMany`'s `onConflict` ignore and merge read their keys plainly, lock only the rows found and insert the rest with a plain INSERT, so two first saves of new keys in one gap no longer deadlock (20 rounds in each start order, ignore and merge, `upsertGaps.mysql.test.js`); that read is a plain read, which takes the transaction's snapshot when it has none yet, so lock before upserting. A lock's belongs-to fields are checked against their targets as last committed (a shared lock on MySQL and MariaDB), so a link to a target saved after the transaction's first plain read no longer reads null, and `lock` and `lockMany` read the primary key on MySQL and MariaDB, holding the listed rows alone. `lockOrCreate` still locks before it inserts, so its work reads what the record's previous holder committed; first uses of neighbouring ids can still deadlock on MySQL and MariaDB, and run again as before.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.35",
3
+ "version": "0.2.37",
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.217",
19
- "@jskit-ai/resource-crud-core": "0.1.219",
20
- "json-rest-api": "3.1.11"
18
+ "@jskit-ai/resource-core": "0.1.218",
19
+ "@jskit-ai/resource-crud-core": "0.1.220",
20
+ "json-rest-api": "3.2.0"
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.275",
68
- "@jskit-ai/kernel": "0.2.26"
67
+ "@jskit-ai/database-runtime": "0.1.276",
68
+ "@jskit-ai/kernel": "0.2.27"
69
69
  }
70
70
  }
@@ -157,6 +157,78 @@ async function lockWaitOf(knex, id, waiter) {
157
157
  assert.fail("the lock never waited for the writer");
158
158
  }
159
159
 
160
+ // The index on the paths' workspace a policy names with forceIndex.
161
+ const PATHS_WORKSPACE = "fi_paths_workspace";
162
+ const pathResource = defineTableResource({
163
+ name: "paths",
164
+ tableName: "fi_paths",
165
+ ownership: "workspace",
166
+ schema: {
167
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
168
+ unitId: { type: "integer", required: true, storage: { column: "unit_id" } },
169
+ depth: { type: "integer", required: true }
170
+ }
171
+ });
172
+ const unitResource = defineTableResource({
173
+ name: "units",
174
+ tableName: "fi_units",
175
+ ownership: "workspace",
176
+ schema: {
177
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
178
+ name: { type: "string", required: true, search: true }
179
+ }
180
+ });
181
+
182
+ /**
183
+ * Units 1 to 3 of workspace 1, which Ada sees through their stored paths, and unit 4 of workspace 2. The row policy
184
+ * reads the paths through `how.reader` (an ownTable reader, or the paths' joinSource), with the workspace's index forced
185
+ * when `how.forced`. That index leaves the unit out and workspace 1 holds 300 of the 302 paths, so a read of its paths
186
+ * without the hint scans the table, workspace 2's two paths (between workspace 1's) included.
187
+ * @param {import("knex").Knex} knex
188
+ */
189
+ async function unitsOf(knex) {
190
+ await knex.schema.createTable("fi_paths", (table) => {
191
+ table.increments("id");
192
+ table.integer("workspace_id").nullable();
193
+ table.integer("unit_id").notNullable();
194
+ table.integer("depth").notNullable();
195
+ table.index(["workspace_id"], PATHS_WORKSPACE);
196
+ });
197
+ await knex.schema.createTable("fi_units", (table) => {
198
+ table.increments("id");
199
+ table.integer("workspace_id").nullable();
200
+ table.string("name").notNullable();
201
+ table.index(["workspace_id"], "fi_units_workspace");
202
+ });
203
+ const how = { reader: "ownTable", forced: false };
204
+ let resources;
205
+ async function seenThroughPaths({ query, caller, column, ownTable, options }) {
206
+ if (caller.kind !== "user") {
207
+ return caller.kind !== "anonymous";
208
+ }
209
+ if (how.reader === "joinSource") {
210
+ const paths = await resources.paths.joinSource({ alias: "p" }, options);
211
+ const reader = how.forced ? paths.query.forceIndex(PATHS_WORKSPACE) : paths.query;
212
+ query.whereIn(column("id"), reader.select(paths.column("unitId")));
213
+ } else {
214
+ const reader = how.forced ? ownTable("paths").forceIndex(PATHS_WORKSPACE) : ownTable("paths");
215
+ query.whereIn(column("id"), reader.select("fi_paths.unit_id").whereColumn("fi_paths.workspace_id", column("workspaceId")));
216
+ }
217
+ return true;
218
+ }
219
+ const runtime = await createTestResourceRuntime({ knex });
220
+ resources = await runtime.own("units.feature", [pathResource, { resource: unitResource, rowPolicy: seenThroughPaths }]);
221
+ await knex("fi_units").insert([1, 2, 3].map((id) => ({ id, workspace_id: 1, name: `U${id}` })).concat({ id: 4, workspace_id: 2, name: "U4" }));
222
+ const paths = (from, count) => Array.from({ length: count }, (_, index) => ({ workspace_id: 1, unit_id: 1 + ((from + index) % 3), depth: from + index }));
223
+ await knex("fi_paths").insert(paths(0, 150));
224
+ await knex("fi_paths").insert([{ workspace_id: 2, unit_id: 4, depth: 0 }, { workspace_id: 2, unit_id: 4, depth: 1 }]);
225
+ await knex("fi_paths").insert(paths(150, 150));
226
+ const otherPaths = (await knex("fi_paths").where({ workspace_id: 2 }).orderBy("id").pluck("id")).map(String);
227
+ return { units: resources.units, how, otherPaths };
228
+ }
229
+
230
+ const unitNames = (records) => records.map(({ name }) => name).sort();
231
+
160
232
  /**
161
233
  * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
162
234
  * The test's own empty database; `suffix` names it where the database needs a name.
@@ -250,6 +322,74 @@ function lockPolicyCases(connect) {
250
322
  }
251
323
  }]);
252
324
  }
325
+
326
+ for (const reader of ["ownTable", "joinSource"]) {
327
+ cases.push([`lockWhere through ${reader}, MySQL and MariaDB: unhinted, the policy's nested read locks another workspace's paths; with forceIndex, it leaves them free`, async (t) => {
328
+ const knex = await connect(t, `da_fi_${reader.toLowerCase()}`);
329
+ if (knex.client.config.client !== "mysql2") {
330
+ t.skip("PostgreSQL and SQLite have no index hints: the next case checks that they refuse one");
331
+ return;
332
+ }
333
+ const { units, how, otherPaths } = await unitsOf(knex);
334
+ await knex.raw("ANALYZE TABLE fi_paths, fi_units");
335
+ // Whether another transaction can lock a path now, without waiting.
336
+ const free = (id) => knex.transaction((probe) => probe("fi_paths").where({ id }).forUpdate().noWait()).then(() => true, (error) => {
337
+ if (/^ER_LOCK_(?:NOWAIT|WAIT_TIMEOUT)$/u.test(error.code ?? "")) return false;
338
+ throw error;
339
+ });
340
+ const seen = {};
341
+ for (const forced of [false, true]) {
342
+ Object.assign(how, { reader, forced });
343
+ const statements = [];
344
+ const record = (query) => statements.push(query);
345
+ knex.on("query", record);
346
+ const held = [];
347
+ let names;
348
+ try {
349
+ names = await units.withTransaction(asAda, async (tx) => {
350
+ const locked = await units.lockWhere({}, { ...tx, fields: ["name"] });
351
+ for (const id of otherPaths) {
352
+ if (!(await free(id))) held.push(id);
353
+ }
354
+ return unitNames(locked);
355
+ });
356
+ } finally {
357
+ knex.removeListener("query", record);
358
+ }
359
+ assert.deepEqual(names, ["U1", "U2", "U3"], `forced ${forced}`);
360
+ const lockRead = statements.find(({ sql }) => sql.includes("`fi_units`") && sql.includes("`fi_paths`") && / for update$/u.test(sql));
361
+ const [plan] = await knex.raw(`EXPLAIN ${lockRead.sql.replaceAll(" lock in share mode", "").replace(/ for update$/u, "")}`, lockRead.bindings);
362
+ t.diagnostic(`forced ${forced}: held ${held.length} of ${otherPaths.length}; plan ${plan.map((row) => `${row.table} ${row.type} ${row.key ?? "-"} ${row.rows}`).join(" | ")}`);
363
+ seen[forced] = { held, sql: lockRead.sql };
364
+ }
365
+ const hint = new RegExp(`force index \\(\`${PATHS_WORKSPACE}\`\\)`, "u");
366
+ assert.doesNotMatch(seen.false.sql, hint);
367
+ assert.deepEqual(seen.false.held, otherPaths, "unhinted: the nested scan holds workspace 2's paths");
368
+ assert.match(seen.true.sql, hint);
369
+ assert.deepEqual(seen.true.held, [], "hinted: workspace 2's paths stay free");
370
+ }]);
371
+ }
372
+
373
+ cases.push(["forceIndex on an ownTable reader or a joinSource's query throws a TypeError on PostgreSQL and SQLite, which have no index hints, and so fails the lock", async (t) => {
374
+ const knex = await connect(t, "da_fi_refused");
375
+ if (knex.client.config.client === "mysql2") {
376
+ t.skip("MySQL and MariaDB take the hint: the cases above check it");
377
+ return;
378
+ }
379
+ const { units, how } = await unitsOf(knex);
380
+ const refused = (error) => {
381
+ for (let current = error; current; current = current.cause) {
382
+ if (current instanceof TypeError && /^forceIndex is MySQL and MariaDB only: (?:PostgreSQL|SQLite) has no index hints/u.test(current.message)) return true;
383
+ }
384
+ return false;
385
+ };
386
+ for (const reader of ["ownTable", "joinSource"]) {
387
+ Object.assign(how, { reader, forced: true });
388
+ await assert.rejects(units.withTransaction(asAda, (tx) => units.lockWhere({}, { ...tx, fields: ["name"] })), refused, reader);
389
+ Object.assign(how, { reader, forced: false });
390
+ assert.deepEqual(unitNames(await units.withTransaction(asAda, (tx) => units.lockWhere({}, { ...tx, fields: ["name"] }))), ["U1", "U2", "U3"], reader);
391
+ }
392
+ }]);
253
393
  return cases;
254
394
  }
255
395