@jskit-ai/resource-runtime 0.2.57 → 0.2.59

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
+ - `joinSource({ alias, filters, columns }, options)` takes `columns`, the visible fields a report reads: its derived table then lists those, the id and the ownership fields alone, where it listed every visible column, so a report reading two fields of a wide table no longer spells out the columns it does not read in its statement. A name that is no visible field (a hidden field other than the ownership fields, a blob, a virtual or unknown field) throws a TypeError when the source is built, before any statement, and `column(field)` throws for a field `columns` does not list. The rows stay the caller's scoped rows, `filters` still narrow by any search field, and without `columns` the statement is unchanged.
6
+ - 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
7
  - 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
8
  - `@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
9
  - 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.59",
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
  };
@@ -175,7 +175,9 @@ function isAsyncGenerator(value) {
175
175
  * statement. It answers `{ query, column }`: the rows scopedQuery() gives under `alias` (the caller's ownership, the
176
176
  * row policy and `filters` applied) with the stored columns a read answers and the ownership fields, hidden or not,
177
177
  * since a report joins on them and they name the caller's own scope; never another hidden column, and never a blob,
178
- * so a report's `select("alias.*")` holds no unbounded bytes. `column(field)`
178
+ * so a report's `select("alias.*")` holds no unbounded bytes. `columns`, when given, lists the visible fields the report
179
+ * reads: the derived table then carries those, the id and the ownership fields alone, so a source of a wide table that
180
+ * a report reads two fields of names four columns in its statement, not every one. `column(field)`
179
181
  * names each under that alias. A CRUD feature's repository answers it to any feature, where it
180
182
  * refuses scopedQuery(). The builder comes wrapped, since a builder is thenable.
181
183
  * @param {object} dependencies
@@ -188,26 +190,50 @@ function isAsyncGenerator(value) {
188
190
  function createJoinSource({ api, resource, jsonRest, scopedQuery, column }) {
189
191
  const { name } = resource;
190
192
  /**
191
- * @param {{ alias: string, filters?: object }} params
193
+ * The fields a join source's `columns` lists, each a visible field the source carries.
194
+ * @param {unknown} columns
195
+ * @param {string[]} visible The fields a source carries without `columns`, but the id.
196
+ */
197
+ function listedColumns(columns, visible) {
198
+ if (!Array.isArray(columns)) {
199
+ throw new TypeError(`${name}.joinSource() columns must list the visible fields the report reads. Received: ${JSON.stringify(columns)}`);
200
+ }
201
+ for (const field of columns) {
202
+ if (field !== "id" && !visible.includes(/** @type {string} */ (field))) {
203
+ throw new TypeError(
204
+ `${name}.joinSource() columns names ${JSON.stringify(field)}, which is not a visible field of ${name}: a join ` +
205
+ "source carries the stored fields a read answers, the id and the ownership fields; never another hidden " +
206
+ "field, a blob or a virtual field."
207
+ );
208
+ }
209
+ }
210
+ return new Set(/** @type {string[]} */ (columns));
211
+ }
212
+
213
+ /**
214
+ * @param {{ alias: string, filters?: object, columns?: string[] }} params `columns`: the visible fields the report
215
+ * reads, beside the id and the ownership fields, which the source always carries; without it, every visible field.
192
216
  * @param {{ context?: object | null, trx?: object | null }} [options]
193
217
  * @returns {Promise<Readonly<{ query: any, column: (field: string) => string }>>}
194
218
  */
195
- return async function joinSource({ alias, filters } = {}, options = {}) {
219
+ return async function joinSource({ alias, filters, columns } = {}, options = {}) {
196
220
  if (typeof alias !== "string" || !alias) {
197
221
  throw new TypeError(`${name}.joinSource() needs the alias the report joins the ${name} under.`);
198
222
  }
199
- const { query } = await scopedQuery({ alias, ...(filters === undefined ? {} : { filters }) }, options);
200
223
  const { schemaStructure, ownershipFields = [] } = jsonRest().vars.schemaInfo;
201
224
  const joinKeys = new Set(ownershipFields);
202
- const carried = Object.keys(schemaStructure).filter((field) => {
225
+ const visible = Object.keys(schemaStructure).filter((field) => {
203
226
  const definition = schemaStructure[field];
204
227
  return field !== "id" && (definition.hidden !== true || joinKeys.has(field)) &&
205
228
  definition.virtual !== true && !definition.belongsToPolymorphic && resource.schema[field]?.type !== "blob";
206
229
  });
207
- // The scoped rows' visible columns and ownership fields, as a derived table under the alias: nothing a caller adds
208
- // reaches the others.
230
+ const listed = columns === undefined ? null : listedColumns(columns, visible);
231
+ const carried = ["id", ...(listed ? visible.filter((field) => joinKeys.has(field) || listed.has(field)) : visible)];
232
+ const { query } = await scopedQuery({ alias, ...(filters === undefined ? {} : { filters }) }, options);
233
+ // The scoped rows' visible columns (those `columns` lists, when given) and ownership fields, as a derived table
234
+ // under the alias: nothing a caller adds reaches the others.
209
235
  const source = readOnlyQueryBuilder(
210
- (options.trx || api.knex.instance).from(query.select(["id", ...carried].map((field) => column(field, alias))).as(alias)),
236
+ (options.trx || api.knex.instance).from(query.select(carried.map((field) => column(field, alias))).as(alias)),
211
237
  { resourceType: name }
212
238
  );
213
239
  JOIN_SOURCES.add(source);
@@ -220,6 +246,12 @@ function createJoinSource({ api, resource, jsonRest, scopedQuery, column }) {
220
246
  if (resource.schema[field]?.hidden === true && !joinKeys.has(field)) {
221
247
  throw new TypeError(`${name}.joinSource() carries no hidden field but its ownership fields, so it has no column for "${field}".`);
222
248
  }
249
+ if (listed && !carried.includes(field)) {
250
+ throw new TypeError(
251
+ `${name}.joinSource() was given columns ${JSON.stringify([...listed])}, so it carries no column for "${field}" ` +
252
+ "(only those, the id and the ownership fields): name it in columns."
253
+ );
254
+ }
223
255
  return column(field, alias);
224
256
  }
225
257
  });
@@ -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,121 @@
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 { createPackageTestKnex, createTestResourceRuntime } from "../src/test/index.js";
5
+
6
+ // SQLite in memory, or on a DB_CLIENT=pg or mysql2 run a schema or database of its own (see createPackageTestKnex).
7
+ const testKnex = (t) => createPackageTestKnex(t, { environment: process.env });
8
+
9
+ const WORKSPACE_A = Object.freeze({ workspace: { id: "1" } });
10
+ // The columns a narrow join source of the pins carries: the id, the ownership field and the two fields it lists.
11
+ const NARROW = ["p.id", "p.workspace_id", "p.workflow_record_id", "p.module_version_id"];
12
+
13
+ // A wide table another owner's report reads two fields of: pins with a hidden owner and a hidden secret, two in
14
+ // workspace 1 and one in workspace 2.
15
+ async function createPinFixture(t) {
16
+ const knex = await testKnex(t);
17
+ await knex.schema.createTable("jc_record_pins", (table) => {
18
+ table.increments("id");
19
+ table.integer("workspace_id").notNullable();
20
+ table.integer("workflow_record_id").notNullable();
21
+ table.integer("module_version_id").notNullable();
22
+ table.string("label").notNullable();
23
+ table.string("note");
24
+ table.string("pin_secret");
25
+ table.index(["workspace_id"], "jc_record_pins_workspace");
26
+ });
27
+ await knex("jc_record_pins").insert([
28
+ { workspace_id: 1, workflow_record_id: 10, module_version_id: 100, label: "A", note: "first", pin_secret: "s1" },
29
+ { workspace_id: 1, workflow_record_id: 11, module_version_id: 101, label: "B", note: null, pin_secret: "s2" },
30
+ { workspace_id: 2, workflow_record_id: 12, module_version_id: 102, label: "C", note: "other", pin_secret: "s3" }
31
+ ]);
32
+ const resource = defineTableResource({
33
+ name: "recordPins",
34
+ tableName: "jc_record_pins",
35
+ ownership: "workspace",
36
+ schema: {
37
+ workspaceId: { type: "id", required: true, hidden: true, storage: { column: "workspace_id" } },
38
+ workflowRecordId: { type: "integer", required: true, search: true, storage: { column: "workflow_record_id" } },
39
+ moduleVersionId: { type: "integer", required: true, storage: { column: "module_version_id" } },
40
+ label: { type: "string", required: true, search: true },
41
+ note: { type: "string", nullable: true },
42
+ pinSecret: { type: "string", nullable: true, hidden: true, storage: { column: "pin_secret" } }
43
+ }
44
+ });
45
+ const runtime = await createTestResourceRuntime({ knex });
46
+ const { recordPins } = await runtime.own("pins.feature", [resource]);
47
+ const system = runtime.declareSystemScope("pins.feature", "report every workspace's pins")("count the pins");
48
+ return { pins: recordPins, system, options: { context: WORKSPACE_A } };
49
+ }
50
+
51
+ /**
52
+ * A report's statement over a source, without identifier quotes, and the select list of each SELECT in it.
53
+ * @param {{ query: any, column: (field: string) => string }} source
54
+ */
55
+ function statementOf(source) {
56
+ const { sql, bindings } = source.query.select({ record: source.column("id") }).toSQL();
57
+ const text = sql.replace(/[`"]/gu, "");
58
+ return { text, bindings, lists: [...text.matchAll(/select (.+?) from /gu)].map(([, list]) => list) };
59
+ }
60
+
61
+ test("a join source given columns selects only those, the id and the ownership fields, in the statement it builds without them", async (t) => {
62
+ const { pins, options } = await createPinFixture(t);
63
+ // Without columns, the source's derived table lists every visible field and the ownership field, never the secret.
64
+ const every = statementOf(await pins.joinSource({ alias: "p" }, options));
65
+ const visible = every.lists.find((list) => list.includes("p.label"));
66
+ assert.ok(visible, every.text);
67
+ assert.deepEqual(visible.split(", ").sort(), [...NARROW, "p.label", "p.note"].sort());
68
+ assert.ok(!every.text.includes("pin_secret"), every.text);
69
+
70
+ // With them, that list holds the listed fields, the id and the ownership field: the same derived tables, scope and
71
+ // bindings otherwise.
72
+ const narrow = statementOf(await pins.joinSource({ alias: "p", columns: ["workflowRecordId", "moduleVersionId"] }, options));
73
+ const listed = visible.split(", ").filter((column) => NARROW.includes(column)).join(", ");
74
+ assert.equal(narrow.text, every.text.replace(visible, listed));
75
+ assert.deepEqual(narrow.bindings, every.bindings);
76
+ for (const left of ["p.label", "p.note", "pin_secret"]) {
77
+ assert.ok(!narrow.text.includes(left), narrow.text);
78
+ }
79
+ // The scope's own ownership field and the id need no naming, and naming them changes nothing.
80
+ const named = statementOf(await pins.joinSource({ alias: "p", columns: ["id", "workspaceId", "moduleVersionId", "workflowRecordId"] }, options));
81
+ assert.equal(named.text, narrow.text);
82
+ });
83
+
84
+ test("a join source refuses a columns entry that is no visible field, a hidden one included, before it reads anything", async (t) => {
85
+ const { pins, options } = await createPinFixture(t);
86
+ await assert.rejects(pins.joinSource({ alias: "p", columns: ["workflowRecordId", "secret_column"] }, options),
87
+ /recordPins\.joinSource\(\) columns names "secret_column", which is not a visible field of recordPins/u);
88
+ await assert.rejects(pins.joinSource({ alias: "p", columns: ["pinSecret"] }, options),
89
+ /recordPins\.joinSource\(\) columns names "pinSecret", which is not a visible field of recordPins: a join source carries the stored fields a read answers, the id and the ownership fields; never another hidden field/u);
90
+ await assert.rejects(pins.joinSource({ alias: "p", columns: "label" }, options),
91
+ /recordPins\.joinSource\(\) columns must list the visible fields the report reads/u);
92
+ });
93
+
94
+ test("a join source given columns has no column for a field it does not list, and names the id, the ownership fields and the listed ones", async (t) => {
95
+ const { pins, options } = await createPinFixture(t);
96
+ const source = await pins.joinSource({ alias: "p", columns: ["workflowRecordId", "moduleVersionId"] }, options);
97
+ assert.throws(() => source.column("label"),
98
+ /recordPins\.joinSource\(\) was given columns \["workflowRecordId","moduleVersionId"\], so it carries no column for "label" \(only those, the id and the ownership fields\): name it in columns/u);
99
+ assert.throws(() => source.column("pinSecret"), /recordPins\.joinSource\(\) carries no hidden field but its ownership fields, so it has no column for "pinSecret"/u);
100
+ assert.deepEqual(["id", "workspaceId", "workflowRecordId", "moduleVersionId"].map((field) => source.column(field)),
101
+ ["p.id", "p.workspace_id", "p.workflow_record_id", "p.module_version_id"]);
102
+ });
103
+
104
+ test("a join source given columns still answers the caller's scoped rows alone, its filters applied on fields it does not list", async (t) => {
105
+ const { pins, system, options } = await createPinFixture(t);
106
+ const rowsOf = async (source) => (await source.query.select("p.*").orderBy(source.column("id")))
107
+ .map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, Number(value)])));
108
+
109
+ const narrow = await pins.joinSource({ alias: "p", columns: ["workflowRecordId"] }, options);
110
+ assert.deepEqual(await rowsOf(narrow), [
111
+ { id: 1, workspace_id: 1, workflow_record_id: 10 },
112
+ { id: 2, workspace_id: 1, workflow_record_id: 11 }
113
+ ]);
114
+ const filtered = await pins.joinSource({ alias: "p", filters: { label: "B" }, columns: ["workflowRecordId"] }, options);
115
+ assert.deepEqual(await rowsOf(filtered), [{ id: 2, workspace_id: 1, workflow_record_id: 11 }]);
116
+ // Another workspace's pin stays out of a report's subquery over the source; a system context reads every workspace's.
117
+ const outside = await pins.joinSource({ alias: "p", filters: { label: "C" }, columns: ["moduleVersionId"] }, options);
118
+ assert.deepEqual(await rowsOf(outside), []);
119
+ const everyWorkspace = await pins.joinSource({ alias: "p", columns: ["moduleVersionId"] }, { context: system });
120
+ assert.deepEqual((await rowsOf(everyWorkspace)).map((row) => [row.workspace_id, row.module_version_id]), [[1, 100], [1, 101], [2, 102]]);
121
+ });
@@ -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
+ });