@jskit-ai/resource-runtime 0.2.57 → 0.2.58

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.3.5 exactly (from 3.3.4), with json-rest-schema 1.0.21 in the lock. A read validates and parses only what it must (page parameters checked by one schema built once, temporal values by json-rest-schema's own checks, the response pass normalizing only values changed since the database pass), and json-rest-api's scopedQuery takes columns, the fields its derived table selects. A patch answering nothing or its id, and a delete, read the stored row only when something uses it (a hook, a precondition, a revision, a field setter, relationships, a cleared link or a full response); otherwise the UPDATE or DELETE carries the caller's scope in its WHERE, and on MySQL and MariaDB the read takes the id alone. patchMany's and deleteMany's visibility reads take only the ids unless a permission hook or a cleared link uses the rows. Errors are unchanged: a missing, hidden or another owner's row is json-rest-api's not-found error, a shared row outside a system context its refusal. A patch with onlyIf and changes but no lockVersion sends its UPDATE first and locks the row only when it changed nothing (#498).
5
6
  - Depends on json-rest-api 3.3.4 exactly (from 3.3.3): a write finds the relationships that reference its resource, for the revision of a versioned resource it reaches, in an index each API builds once per published schema (compileResourceSchemas, an AnyAPI publish or a failed load drop it), where it walked every resource's relationships on each write. A write's statements are unchanged.
6
7
  - `@jskit-ai/resource-runtime/server/anyapi` exports json-rest-api's AnyAPI storage, for tables an application defines while it runs, which no table resource describes: `AnyapiRegistry`, `JsonRestApi`, `RestApiAnyapiKnexPlugin`, `RestApiPlugin`, `RowPolicyPlugin` and `ensureAnyApiSchema`, the very objects of the json-rest-api copy the runtime's handles run on. json-rest-api knows the transactions `api.transaction` opened by identity, and AnyAPI its registry with `instanceof`, so an AnyAPI write given a handle's `txOptions.trx` joins that transaction only on this copy; an application imports these from here and declares no json-rest-api of its own, and `npm run jskit:update` moves its one copy with the catalog.
7
8
  - Depends on json-rest-api 3.3.3 exactly (from 3.3.2): on a descending sort, rows tied on its last key come in descending id order (the id that breaks ties takes the last key's direction), so MySQL and MariaDB read a descending page from an index leading with that key instead of sorting every row, and leave out the `IS NULL` term where the server already places NULLs last; and capabilities a start could not observe (the server not up yet) are observed again on the next storage call until that succeeds.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.57",
3
+ "version": "0.2.58",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -16,9 +16,9 @@
16
16
  "./locales/en.json": "./locales/en.json"
17
17
  },
18
18
  "dependencies": {
19
- "@jskit-ai/resource-core": "0.1.226",
20
- "@jskit-ai/resource-crud-core": "0.1.228",
21
- "json-rest-api": "3.3.4"
19
+ "@jskit-ai/resource-core": "0.1.227",
20
+ "@jskit-ai/resource-crud-core": "0.1.229",
21
+ "json-rest-api": "3.3.5"
22
22
  },
23
23
  "description": "The resource runtime: features own their tables through it and read and write them with scoped handles on json-rest-api.",
24
24
  "jskit": {
@@ -69,7 +69,7 @@
69
69
  }
70
70
  },
71
71
  "peerDependencies": {
72
- "@jskit-ai/database-runtime": "0.1.292",
73
- "@jskit-ai/kernel": "0.2.35"
72
+ "@jskit-ai/database-runtime": "0.1.293",
73
+ "@jskit-ai/kernel": "0.2.36"
74
74
  }
75
75
  }
@@ -204,6 +204,24 @@ function requirePatchConditions(name, lockVersionField, attributes, options) {
204
204
  }
205
205
  }
206
206
 
207
+ /**
208
+ * Refuses an onlyIf entry the UPDATE of a patch with changes could not compare: a field other than a stored one beside
209
+ * the id, or a value other than a scalar, a Date or null.
210
+ * @param {string} name The resource's name.
211
+ * @param {Record<string, { virtual?: boolean, computed?: boolean }>} schemaStructure
212
+ * @param {string} field
213
+ * @param {unknown} value
214
+ */
215
+ function requireOnlyIfValue(name, schemaStructure, field, value) {
216
+ const definition = schemaStructure[field];
217
+ if (field === "id" || !definition || definition.virtual || definition.computed) {
218
+ throw new TypeError(`${name}.patch() onlyIf.${field} is not a stored field.`);
219
+ }
220
+ if (value !== null && typeof value === "object" && !(value instanceof Date)) {
221
+ throw new TypeError(`${name}.patch() onlyIf.${field} must be a scalar, a Date or null.`);
222
+ }
223
+ }
224
+
207
225
  /**
208
226
  * The answer format a handle call asks for: "jsonapi" (the CRUD service's documents) or, by default, "plain" (records).
209
227
  * @param {string} name The resource's name.
@@ -256,5 +274,5 @@ function refuseTransactionPlace(name, { outermost, joinOnly }, joined) {
256
274
 
257
275
  export {
258
276
  formatOf, matchesNoRow, missingOf, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
259
- requirePatchConditions, requireReadParams, requireUpsertRows, passedOn, whereSelection
277
+ requireOnlyIfValue, requirePatchConditions, requireReadParams, requireUpsertRows, passedOn, whereSelection
260
278
  };
@@ -15,7 +15,7 @@ import { valueOnlyRaw } from "./rawExpression.js";
15
15
  import { GroupLimitError, PageSizeError, StaleRecordError, UnpagedQueryError } from "./errors.js";
16
16
  import {
17
17
  formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, refuseTransactionPlace, requireConditionValues, requireDefinedFilters, requireOwners,
18
- requirePatchConditions, requireReadParams, requireUpsertRows, whereSelection
18
+ requireOnlyIfValue, requirePatchConditions, requireReadParams, requireUpsertRows, whereSelection
19
19
  } from "./handleGuards.js";
20
20
  import {
21
21
  aggregateMeasures,
@@ -444,7 +444,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
444
444
  if (!isRecord(attributes)) {
445
445
  throw new TypeError(`${name}.patch() takes attributes as an object.`);
446
446
  }
447
- // Before any statement: a lockVersion or onlyIf patch locks the row first, and an afterWrite hook opens a transaction.
447
+ // Before any statement: a lockVersion patch locks the row first, and an afterWrite hook opens a transaction.
448
448
  checkBlobValues(resource, [attributes]);
449
449
  requirePatchConditions(name, lockVersionField, attributes, options);
450
450
  const { lockVersion, onlyIf, missing: missingOption, ...callOptions } = options;
@@ -456,16 +456,18 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
456
456
  if (lockVersion === undefined && onlyIf === undefined) {
457
457
  return patchRecord(id, attributes, callOptions, returning);
458
458
  }
459
- // A missing row throws, so the row's lock comes first, reading only the lock version. onlyIf is compared in SQL,
460
- // by the UPDATE that changes fields or, with no changes, by a read (holdsOnlyIf), so a hidden field, which no read
461
- // answers, is compared too, and an id compares however the caller gives it.
459
+ // A lockVersion patch, or an onlyIf one with no changes, locks the row first, reading only the lock version; an onlyIf
460
+ // one with changes locks it only when its UPDATE changed nothing. Either way a missing row throws. onlyIf is compared in
461
+ // SQL (by the UPDATE or holdsOnlyIf), so a hidden field, which no read answers, compares too, and an id however given.
462
462
  const compared = lockVersion === undefined ? [] : [lockVersionField];
463
+ const updateFirst = lockVersion === undefined && Object.keys(attributes).length > 0;
463
464
  return withTransaction(callOptions, async (transaction) => {
464
465
  // The patch's own format goes on to its write; work in a transaction receives only the context and transaction.
465
466
  const txOptions = { ...transaction, ...formatSetting(callOptions) };
466
- const [current] = await lockMany([id], { ...transaction, missing, fields: compared });
467
- if (!current) {
468
- return null;
467
+ const patched = updateFirst ? await patchIfPresent(id, attributes, txOptions, returning, onlyIf) : null;
468
+ const [current] = patched === null ? await lockMany([id], { ...transaction, missing, fields: compared }) : [];
469
+ if (updateFirst || !current) {
470
+ return patched;
469
471
  }
470
472
  if (lockVersion !== undefined && Number(current[lockVersionField]) !== lockVersion) {
471
473
  throw new StaleRecordError();
@@ -661,13 +663,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, h
661
663
  const adapter = api.knex.helpers.getStorageAdapter(name);
662
664
  let { query } = await scopedQuery({ filters: { id: [id] } }, options);
663
665
  for (const [field, value] of Object.entries(onlyIf)) {
664
- const definition = schemaStructure[field];
665
- if (field === "id" || !definition || definition.virtual || definition.computed) {
666
- throw new TypeError(`${name}.patch() onlyIf.${field} is not a stored field.`);
667
- }
668
- if (value !== null && typeof value === "object" && !(value instanceof Date)) {
669
- throw new TypeError(`${name}.patch() onlyIf.${field} must be a scalar, a Date or null.`);
670
- }
666
+ requireOnlyIfValue(name, schemaStructure, field, value);
671
667
  query = value === null ? query.whereNull(column(field)) : query.where(column(field), adapter.translateFilterValue(field, value));
672
668
  }
673
669
  return (await query.first(column("id"))) !== undefined;
@@ -0,0 +1,179 @@
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 { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
5
+ import { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
6
+
7
+ // A patch that answers nothing, or only the id, sends no read of the row's columns before its UPDATE: on an inbox that
8
+ // reads each message's full text and HTML for nothing (issue #498).
9
+
10
+ const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
11
+ const WORKSPACE_B = Object.freeze({ workspace: { id: "2" } });
12
+ // json-rest-api's not-found error, classified by its code (404 at the HTTP edge).
13
+ const notFound = (error) => error.code === "REST_API_RESOURCE" && error.subtype === "not_found";
14
+ // A mail's text and HTML at a realistic size: 64 KB each.
15
+ const WIDE_TEXT = "x".repeat(64 * 1024);
16
+
17
+ function messageResource(extra = {}) {
18
+ return defineTableResource({
19
+ name: "messages",
20
+ tableName: "messages",
21
+ ownership: "workspace",
22
+ defaultSort: ["id"],
23
+ schema: {
24
+ id: { type: "id", primary: true },
25
+ workspaceId: { type: "id", nullable: true, search: true, storage: { column: "workspace_id" } },
26
+ subject: { type: "string", required: true },
27
+ status: { type: "string", defaultTo: "new", search: true },
28
+ folder: { type: "string", nullable: true, search: true },
29
+ body: { type: "string", nullable: true },
30
+ html: { type: "string", nullable: true }
31
+ },
32
+ ...extra
33
+ });
34
+ }
35
+
36
+ async function createInbox(t, { owns = [messageResource()] } = {}) {
37
+ const knex = await createPackageTestKnex(t, { environment: process.env });
38
+ await knex.schema.createTable("messages", (table) => {
39
+ table.increments("id");
40
+ table.integer("workspace_id").nullable();
41
+ table.string("subject").notNullable();
42
+ table.string("status").notNullable().defaultTo("new");
43
+ table.string("folder").nullable();
44
+ // MEDIUMTEXT on MySQL and MariaDB, whose TEXT holds 64 KB; TEXT on PostgreSQL and SQLite.
45
+ table.text("body", "mediumtext");
46
+ table.text("html", "mediumtext");
47
+ table.index(["workspace_id"], "messages_workspace");
48
+ });
49
+ const runtime = await createTestResourceRuntime({ knex });
50
+ const { messages } = await runtime.own("inbox.feature", owns);
51
+ return { knex, messages };
52
+ }
53
+
54
+ // Inserts `count` wide messages for a workspace, a few at a time (each row is about 128 KB), and answers their ids.
55
+ async function addMessages(knex, workspaceId, count, { folder = "inbox" } = {}) {
56
+ const before = await knex("messages").max({ last: "id" }).first();
57
+ for (let start = 0; start < count; start += 10) {
58
+ const rows = Array.from({ length: Math.min(10, count - start) }, (_, index) => ({
59
+ workspace_id: workspaceId,
60
+ subject: `message ${start + index}`,
61
+ folder,
62
+ body: WIDE_TEXT,
63
+ html: WIDE_TEXT
64
+ }));
65
+ await knex("messages").insert(rows);
66
+ }
67
+ const ids = await knex("messages").where("id", ">", Number(before?.last ?? 0)).orderBy("id").pluck("id");
68
+ return ids.map(String);
69
+ }
70
+
71
+ // What a statement is: its first word (begin, select, update, commit...).
72
+ const kindOf = (sql) => String(sql).trim().split(/\s+/u)[0].toLowerCase();
73
+ // The columns a SELECT names, between its select and its from.
74
+ const selectList = (sql) => /^\s*select\s+([\s\S]*?)\s+from\s/iu.exec(sql)?.[1] ?? "";
75
+ // A read of a message's own columns: one that selects every column, or any column but the id.
76
+ const readsColumns = (sql) => kindOf(sql) === "select" && /\bmessages\b/u.test(sql) &&
77
+ /\*|subject|status|folder|body|html|workspace_id/u.test(selectList(sql));
78
+
79
+ test("a patch that answers nothing or its id reads none of the row's columns before its UPDATE, at any table size and row width", async (t) => {
80
+ const { knex, messages } = await createInbox(t);
81
+ const mysql = ["mysql", "mysql2"].includes(knex.client.config.client);
82
+ const [mine] = await addMessages(knex, 1, 1);
83
+ await addMessages(knex, 2, 1);
84
+ const options = { context: WORKSPACE_A };
85
+ let step = 0;
86
+ const calls = {
87
+ plain: (returning) => messages.patch(mine, { status: `triaged ${++step}` }, { ...options, returning }),
88
+ "missing: skip": (returning) => messages.patch(mine, { status: `triaged ${++step}` }, { ...options, missing: "skip", returning }),
89
+ onlyIf: (returning) => messages.patch(mine, { status: `triaged ${++step}` }, { ...options, onlyIf: { folder: "inbox" }, returning }),
90
+ "onlyIf, missing: skip": (returning) =>
91
+ messages.patch(mine, { status: `triaged ${++step}` }, { ...options, onlyIf: { folder: "inbox" }, missing: "skip", returning })
92
+ };
93
+ const measure = async () => {
94
+ const measured = {};
95
+ for (const [name, call] of Object.entries(calls)) {
96
+ for (const returning of ["none", "id"]) {
97
+ const { result, queries } = await countQueries(knex, () => call(returning));
98
+ assert.equal(result, returning === "id" ? mine : undefined, `${name}, returning ${returning}`);
99
+ measured[`${name}, returning ${returning}`] = queries;
100
+ }
101
+ }
102
+ return measured;
103
+ };
104
+
105
+ const few = await measure();
106
+ // The same calls on a table of 60 more wide messages, in both workspaces.
107
+ await addMessages(knex, 1, 30);
108
+ await addMessages(knex, 2, 30);
109
+ const many = await measure();
110
+ // Every call's statements, then what is wrong with them, so a failure shows every call at once.
111
+ const report = Object.entries(few).map(([call, queries]) => `${call}: ${queries.length} statements\n ${queries.join("\n ")}`).join("\n");
112
+ const problems = Object.entries(few).flatMap(([call, queries]) => {
113
+ const reads = queries.filter((sql) => kindOf(sql) === "select" && /\bmessages\b/u.test(sql));
114
+ return [
115
+ ...(queries.some(readsColumns) ? [`${call} reads the row's columns before its UPDATE`] : []),
116
+ // MySQL and MariaDB check the scope with a read of the id first, so an UPDATE never locks a row the caller cannot
117
+ // see (an UPDATE there locks each row it looks at before it checks the rest of its WHERE).
118
+ ...(reads.length > (mysql ? 1 : 0) ? [`${call} reads the table ${reads.length} times before its UPDATE`] : []),
119
+ ...(queries.filter((sql) => kindOf(sql) === "update").length === 1 ? [] : [`${call} sends no one UPDATE`]),
120
+ ...(many[call].map(kindOf).join() === queries.map(kindOf).join() ? [] : [`${call} sends ${many[call].map(kindOf).join(", ")} at 62 rows, ${queries.map(kindOf).join(", ")} at 2`])
121
+ ];
122
+ });
123
+ assert.deepEqual(problems, [], report);
124
+ const stored = await knex("messages").where({ id: mine }).first();
125
+ assert.equal(stored.status, `triaged ${step}`);
126
+ assert.equal(stored.body, WIDE_TEXT);
127
+ });
128
+
129
+ test("a patch that answers nothing or its id refuses another workspace's, a missing and a policy-hidden row as before, and keeps onlyIf's meaning", async (t) => {
130
+ const hiddenFolder = ({ query, column }) => {
131
+ query.where(column("folder"), "<>", "hidden");
132
+ return true;
133
+ };
134
+ const { knex, messages } = await createInbox(t, { owns: [{ resource: messageResource(), rowPolicy: hiddenFolder }] });
135
+ const [mine] = await addMessages(knex, 1, 1);
136
+ const [theirs] = await addMessages(knex, 2, 1);
137
+ const [hidden] = await addMessages(knex, 1, 1, { folder: "hidden" });
138
+ const options = { context: WORKSPACE_A };
139
+ for (const returning of ["none", "id"]) {
140
+ for (const id of [theirs, hidden, "999999"]) {
141
+ const label = `${id === theirs ? "another workspace's" : id === hidden ? "a hidden" : "a missing"} row, returning ${returning}`;
142
+ await assert.rejects(messages.patch(id, { status: "taken" }, { ...options, returning }), notFound, label);
143
+ await assert.rejects(messages.patch(id, { status: "taken" }, { ...options, returning, onlyIf: { folder: "inbox" } }), notFound, label);
144
+ assert.equal(await messages.patch(id, { status: "taken" }, { ...options, returning, missing: "skip" }), null, label);
145
+ assert.equal(await messages.patch(id, { status: "taken" }, { ...options, returning, missing: "skip", onlyIf: { folder: "inbox" } }), null, label);
146
+ }
147
+ // onlyIf that does not hold answers null and changes nothing, missing or not.
148
+ assert.equal(await messages.patch(mine, { status: "taken" }, { ...options, returning, onlyIf: { folder: "archive" } }), null);
149
+ assert.equal(await messages.patch(mine, { status: "taken" }, { ...options, returning, missing: "skip", onlyIf: { folder: "archive" } }), null);
150
+ // A patch that stores the values the row already holds still finds the row.
151
+ assert.equal(await messages.patch(mine, { status: "new" }, { ...options, returning }), returning === "id" ? mine : undefined);
152
+ // Inside a caller's transaction a refused row fails the patch and then the transaction, and a skipped one fails
153
+ // nothing.
154
+ await assert.rejects(messages.withTransaction(options, async (txOptions) => {
155
+ await assert.rejects(messages.patch(theirs, { status: "taken" }, { ...txOptions, returning }), (error) => notFound(error) && error.transactionOutcome === "pending");
156
+ }), (error) => notFound(error) && error.transactionOutcome === "rolledBack");
157
+ await messages.withTransaction(options, async (txOptions) => {
158
+ assert.equal(await messages.patch(theirs, { status: "taken" }, { ...txOptions, returning, missing: "skip" }), null);
159
+ assert.equal(await messages.patch(mine, { folder: "read" }, { ...txOptions, returning }), returning === "id" ? mine : undefined);
160
+ assert.equal(await messages.patch(mine, { folder: "inbox" }, { ...txOptions, returning }), returning === "id" ? mine : undefined);
161
+ });
162
+ }
163
+ const statuses = Object.fromEntries((await knex("messages").orderBy("id")).map((row) => [String(row.id), [row.status, row.folder]]));
164
+ assert.deepEqual(statuses, { [mine]: ["new", "inbox"], [theirs]: ["new", "inbox"], [hidden]: ["new", "hidden"] });
165
+ // The workspace's own rows still change.
166
+ assert.equal(await messages.patch(mine, { status: "done" }, { ...options, returning: "none" }), undefined);
167
+ assert.equal(await messages.patch(theirs, { status: "done" }, { context: WORKSPACE_B, returning: "id" }), theirs);
168
+ assert.deepEqual((await knex("messages").whereIn("id", [mine, theirs]).orderBy("id")).map(({ status }) => status), ["done", "done"]);
169
+ });
170
+
171
+ test("a shared row refuses a patch that answers nothing with the shared-row error, before any change", async (t) => {
172
+ const { knex, messages } = await createInbox(t, { owns: [messageResource({ ownership: "workspace_or_shared" })] });
173
+ const [shared] = await addMessages(knex, null, 1);
174
+ for (const returning of ["none", "id"]) {
175
+ await assert.rejects(messages.patch(shared, { status: "taken" }, { context: WORKSPACE_A, returning }), (error) =>
176
+ error.code === "REST_API_RESOURCE" && error.subtype === "forbidden" && /only be changed in a system context/u.test(error.message));
177
+ }
178
+ assert.equal((await knex("messages").where({ id: shared }).first()).status, "new");
179
+ });