@jskit-ai/resource-runtime 0.2.18 → 0.2.19

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.1.2 exactly (from 3.1.1), from the registry with its published integrity: json-rest-api bounds a blob field itself too (`maxBytes` required, a blob answered only where `fields` names it, at most 16 MiB of named blobs per read, none in an include, `queryAll` or HTTP response, many-row write statements chunked by blob bytes, and the MySQL/MariaDB column type chosen by `maxBytes`), its `contains`, `startsWith` and `endsWith` filters match `%`, `_` and `\` literally on every database, a relationship write checks and locks each related type's targets in one query, and an AnyAPI many-to-many read costs its own link rows instead of growing with the square of them.
6
+ - A search filter of an `owns` entry may read other owners' tables through their join sources: `joinSources: { alias: ({ requires, owned }) => owner }` names, by alias, the owner answering each (an owner API the feature requires, or one of its own handles), and its `applyFilter(query, value, { column, joinSource })` gets `joinSource(alias)`, that owner's `{ query, column }` for the caller's scope (its ownership, its row policy, never a hidden column), for a `whereExists` or `whereNotExists` tied to the row with `whereColumn`. A handle builds the join sources a read's filters use before the read, in the call's own context and transaction, so a handle's `query`, `queryAll`, `queryPages`, `aggregate` and `joinSource` take such a filter in one statement, on SQLite, PostgreSQL and MariaDB. A search for the rows that have, or lack, a related owner's rows no longer resolves that owner's ids first or keeps a raw-SQL exception. `own()` refuses at startup a `joinSources` that is not a record of functions under valid aliases, and such a filter with `oneOf` or without `applyFilter`; a read throws naming the filter when its picker answers no owner with `joinSource`. On MySQL and MariaDB `patchWhere`, `deleteWhere`, `lockWhere` and `claim` refuse such a filter as json-rest-api refuses a filter on another table's field (`RestApiValidationError`, rule `selection_cross_table`, the cause of a write's `RestApiWriteError`), since those databases read another table from the transaction's snapshot without locking it, as json-rest-api refuses a filter on another table's field; PostgreSQL and SQLite take it. The data-access guide's Layer 5 shows the filter and how an app switches a report or a pre-resolved id list to it.
7
+ - `lock`, `lockMany`, `lockWhere` and `claim` take `include` again, for belongs-to relationships: after the lock's own rows, the records they name are locked through each related table's own handle (its scope, its row policy, its hidden fields), in id order, with the call's lock mode, each included table once however many rows name it, and nested as a read's include nests them, `include: "batch.yard"` locking the yards after the batches. On MySQL and MariaDB the links are read with a locking read of the rows the lock holds, so a record committed after the transaction's first plain read is found and locked, which a plain read after the lock misses (`lockedReads.mysql.test.js`). A link to a record the caller may not see reads as in a read: its belongs-to field null, the relationship undefined. A collection, or a name that is no belongs-to relationship, is still a TypeError before any statement, now saying to lock a collection's rows with that table's own `lockWhere()`; `claim` refuses `include` named both in its params and its options. Upgrading: none; a read after the lock that only fetched the locked rows' parents may become the lock's `include`.
8
+ - `queryAll({ ..., take })` answers the first `take` records the filters match, in id order or `sort`, and reads no row past them: pages of `pageLimits().server` rows, the last no larger than the rows still wanted, each later page reported as `queryPages` reports its own so `expectFlatQueries()` allows it. `take` is the read's bound, so a request may name more than the request row limit (10,000 by default) and never gets `RowLimitError`; without it a request still stops at that limit. `take` is a whole number from 1, or a TypeError before any statement; `take: undefined` is no take. A request that needed the first N rows past the limit, or read every row only to keep the first few, names `take`.
5
9
  - **Breaking.** A blob field (`type: "blob"` with `maxBytes`) is checked and bounded, on SQLite, PostgreSQL and MariaDB. Every write (`create`, `findOrCreate`, `createMany`, `patch`, `patchMany`, `patchWhere`, `lockOrCreate`, upserts) checks its blob values first, before any statement (a transaction's BEGIN for an `afterWrite` hook, or the row lock of a `lockVersion` or `onlyIf` patch, included): a Buffer or a Uint8Array (stored as a Buffer) of at most `maxBytes`, or null; anything else is a `RestApiValidationError` on the field (rule `blob` or `max_bytes`, a 422). Every read leaves a blob out unless its `fields` names it, answers it as a Buffer and holds at most 16 MiB of the blobs it names, or one record's: `get` and `lock` read one record's, a `query` page and `lockMany`'s ids are refused past the records whose `maxBytes` fit 16 MiB, each `queryPages` page holds no more, and `queryAll`, `lockWhere` and `claim`, which read every matching row at once, refuse to name one. No read names an included table's blob, since an include holds any number of records, and `joinSource()` carries no blob column, so a report's `select("k.*")` reads none. A JSON:API `query` or `get` whose sparse fieldset names a blob is a 400 (`JSON_API_FIELDSET_INVALID`, message code `resource.blobFields`), since JSON holds no binary. Before, a blob was any value of any size, read by every list. Upgrading: a read that needs a blob names it, `get(id, { fields: ["image"] }, options)`, since `get` without `fields` no longer answers it; a read of every row that answered blobs reads them a page at a time with `queryPages`, or a record's with `get`; a page of blobs asks for no more records than fit 16 MiB; an included record's blob is read through its own table's handle; a JSON:API client leaves blobs out of its sparse fieldsets, and a route of its own serves one as the response body.
6
10
  - A report over two owners' rows, asking which of its rows have or lack the other owner's rows (`whereExists`, `whereNotExists` over that owner's `joinSource()`, tied with `whereColumn`) or counting them (a grouped join source joined in), is tested in one statement on SQLite, PostgreSQL and MariaDB, the other owner's ownership and row policy deciding which of its rows count. The data-access guide's Layer 5 shows it, and points rows matched by a related row's value to a cross-table search filter in a plain read.
7
11
  - **Breaking.** A search filter that reads another owner's table is tested, on SQLite, PostgreSQL and MariaDB, to match only the rows the caller's scope reads there: json-rest-api joins the table as its own read, so its ownership, its owner's row policy and the policies contributed to it apply, in `query`, `queryAll` and `aggregate`, each row once through a has-many path too. `own()` refuses, at startup and naming the filter, one that reads a `system` table from a table that is not `system` (a request would have read it, since only the handle asks for a system context) and one on a field the other table hides (it would tell a caller which rows hold a value it may not read); the message says to filter by the ids the other owner answers instead. Upgrading: a filter onto a `system` table becomes a filter on the table's own fields, or on the ids that table's owner answers through its owner API; a filter onto a hidden field filters on a field the other table shows.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.18",
3
+ "version": "0.2.19",
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.208",
19
19
  "@jskit-ai/resource-crud-core": "0.1.208",
20
- "json-rest-api": "3.1.1"
20
+ "json-rest-api": "3.1.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": {
@@ -0,0 +1,177 @@
1
+ import { RestApiValidationError } from "json-rest-api";
2
+ import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
3
+ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
4
+
5
+ // A search filter of an `owns` entry may read other tables through their owners' join sources: its `joinSources` name,
6
+ // by alias, which owner answers each (an owner API the feature requires, or one of its own handles), and its
7
+ // `applyFilter` gets `joinSource(alias)`, the caller's scoped rows of that table under the alias, for a whereExists or
8
+ // a whereNotExists tied to its own row. json-rest-api calls applyFilter synchronously, as Knex compiles the statement,
9
+ // while a join source is built asynchronously in the caller's scope, so a filtering hook builds the join sources the
10
+ // read's filters use first, from the call's own options, and applyFilter takes a fresh copy of one each time it asks.
11
+
12
+ // The call options a handle's json-rest-api context carries for the join sources its filters build: the caller's
13
+ // context and transaction, as the caller passed them. Module-private, so nothing but a handle sets it.
14
+ const CALL_OPTIONS = Symbol("jskit.resources.callOptions");
15
+ // The join sources a read's filters use, built by the filtering hook: by resource name, filter and alias.
16
+ const PREPARED_SOURCES = Symbol("jskit.resources.filterJoinSources");
17
+ const ALIAS = /^[A-Za-z_][A-Za-z0-9_]*$/u;
18
+ // The reads that choose rows to write or lock: on MySQL and MariaDB they read another table from the transaction's
19
+ // snapshot without locking it, as json-rest-api refuses for a filter on another table's field.
20
+ const SELECTING_PURPOSES = new Set(["bulk-write", "lock", "claim"]);
21
+
22
+ /**
23
+ * A handle call's json-rest-api context, carrying the call's own options (its context and transaction) for the join
24
+ * sources its filters build.
25
+ * @param {Record<PropertyKey, unknown>} jsonRestContext The context createJsonRestContext built for the call.
26
+ * @param {{ context?: object | null, trx?: object | null }} options
27
+ */
28
+ function withCallOptions(jsonRestContext, options) {
29
+ jsonRestContext[CALL_OPTIONS] = Object.freeze({ context: options.context ?? null, trx: options.trx ?? null });
30
+ return jsonRestContext;
31
+ }
32
+
33
+ /**
34
+ * The owns entry's search schema as json-rest-api takes it, and the filters in it that read join sources. Each such
35
+ * filter's `joinSources` is checked here, at startup, and taken out; its applyFilter is wrapped so that it receives
36
+ * `joinSource(alias)` beside json-rest-api's tools. The table resource's own search (its searchSchema and its fields'
37
+ * `search` records) names no feature, so a filter there that names join sources is a TypeError.
38
+ * @param {string} featureId
39
+ * @param {{ name: string, searchSchema?: unknown, schema?: Record<string, any> }} resource The table resource.
40
+ * @param {unknown} searchSchema The owns entry's searchSchema extra.
41
+ * @returns {{ searchSchema: unknown, declared: Array<[string, Readonly<Record<string, Function>>]> }}
42
+ */
43
+ function filterJoinSources(featureId, resource, searchSchema) {
44
+ const resourceName = resource.name;
45
+ const shared = [
46
+ ...Object.entries(isRecord(resource.searchSchema) ? resource.searchSchema : {}),
47
+ ...Object.entries(resource.schema ?? {}).filter(([, field]) => isRecord(field?.search)).map(([field, { search }]) => [field, search])
48
+ ];
49
+ for (const [filter, entry] of shared) {
50
+ if (isRecord(entry) && entry.joinSources !== undefined) {
51
+ throw new TypeError(
52
+ `Feature "${featureId}" filter "${filter}" of "${resourceName}" names joinSources in the table resource, which names no ` +
53
+ "feature to answer them; give the filter in the owns entry's searchSchema, whose feature's requires and handles do."
54
+ );
55
+ }
56
+ }
57
+ if (!isRecord(searchSchema)) {
58
+ return { searchSchema, declared: [] };
59
+ }
60
+ const declared = [];
61
+ const entries = Object.entries(searchSchema).map(([filter, entry]) => {
62
+ if (!isRecord(entry) || entry.joinSources === undefined) {
63
+ return [filter, entry];
64
+ }
65
+ const { joinSources, ...rest } = entry;
66
+ const label = `Feature "${featureId}" filter "${filter}" of "${resourceName}"`;
67
+ if (!isRecord(joinSources) || Object.keys(joinSources).length < 1) {
68
+ throw new TypeError(`${label} joinSources must name each join source by its alias: { alias: ({ requires, owned }) => owner }.`);
69
+ }
70
+ for (const [alias, pick] of Object.entries(joinSources)) {
71
+ if (!ALIAS.test(alias)) {
72
+ throw new TypeError(`${label} names the join source "${alias}", which is no alias: letters, digits and _, not first a digit.`);
73
+ }
74
+ // readable-check: allow method-probe - input validation: each join source is the owner's picker
75
+ if (typeof pick !== "function") {
76
+ throw new TypeError(`${label} join source "${alias}" must be a function answering its owner: ({ requires, owned }) => owner.`);
77
+ }
78
+ }
79
+ // readable-check: allow method-probe - input validation: a filter that reads join sources applies them itself
80
+ if (typeof rest.applyFilter !== "function" || rest.oneOf !== undefined) {
81
+ throw new TypeError(`${label} reads join sources, so it takes an applyFilter(query, value, { column, joinSource }) and no oneOf.`);
82
+ }
83
+ declared.push([filter, Object.freeze({ ...joinSources })]);
84
+ return [filter, { ...rest, applyFilter: preparedFilter(resourceName, filter, rest.applyFilter) }];
85
+ });
86
+ return { searchSchema: declared.length > 0 ? Object.fromEntries(entries) : searchSchema, declared };
87
+ }
88
+
89
+ /**
90
+ * A filter's applyFilter as json-rest-api calls it: the owner's, given `joinSource(alias)`, which answers a fresh copy
91
+ * of the join source the filtering hook built for this read, `{ query, column }`, each time it is called.
92
+ * @param {string} resourceName
93
+ * @param {string} filter
94
+ * @param {Function} applyFilter The owner's.
95
+ */
96
+ function preparedFilter(resourceName, filter, applyFilter) {
97
+ return function applyJoinSourceFilter(query, value, tools) {
98
+ const prepared = tools?.context?.[PREPARED_SOURCES]?.get(resourceName)?.get(filter);
99
+ if (!prepared) {
100
+ throw new TypeError(`${resourceName} filter "${filter}" reads join sources, which only a read through its handle builds.`);
101
+ }
102
+ const joinSource = (alias) => {
103
+ const source = prepared.get(alias);
104
+ if (!source) {
105
+ throw new TypeError(`${resourceName} filter "${filter}" names no join source "${alias}"; it names ${[...prepared.keys()].join(", ")}.`);
106
+ }
107
+ return Object.freeze({
108
+ query: source.query.clone(),
109
+ column: source.column
110
+ });
111
+ };
112
+ return applyFilter.call(this, query, value, { ...tools, joinSource });
113
+ };
114
+ }
115
+
116
+ /**
117
+ * The json-rest-api hooks of a resource whose filters read join sources: one filtering hook, before json-rest-api's
118
+ * own filters, that builds the join sources of each such filter the read uses, in the caller's scope (the call's own
119
+ * context and transaction, which its handle carries), through the owner each names. On MySQL and MariaDB a read that
120
+ * chooses rows to write or lock (patchWhere, deleteWhere, lockWhere, claim) refuses such a filter, whose join sources
121
+ * those databases read from the transaction's snapshot without locking them.
122
+ * @param {object} dependencies
123
+ * @param {string} dependencies.resourceName
124
+ * @param {ReadonlyArray<[string, Readonly<Record<string, Function>>]>} dependencies.declared The filters that read join
125
+ * sources, each with its join sources' pickers.
126
+ * @param {(pick: Function) => unknown} dependencies.ownerOf The owner a picker names, given the feature's requires and
127
+ * its own handles.
128
+ */
129
+ function joinSourceHooks({ resourceName, declared, ownerOf }) {
130
+ async function buildFilterJoinSources({ context }) {
131
+ const state = context?.knexQuery;
132
+ if (state?.scopeName !== resourceName || !isRecord(state.filters)) {
133
+ return;
134
+ }
135
+ const used = declared.filter(([filter]) => state.filters[filter] !== undefined);
136
+ if (used.length < 1) {
137
+ return;
138
+ }
139
+ if (SELECTING_PURPOSES.has(state.queryPurpose) && detectDialectFromClient(state.db) === "mysql") {
140
+ const [filter] = used[0];
141
+ const message = `${context.method} on '${resourceName}' filters "${filter}" through another table's join source, which MySQL and ` +
142
+ "MariaDB read from the transaction snapshot without locking it; filter on the row's own columns instead, for example " +
143
+ "on a link after locking its targets with lockMany()";
144
+ throw new RestApiValidationError(message, { fields: ["filters"], violations: [{ field: "filters", rule: "selection_cross_table", message }] });
145
+ }
146
+ const callOptions = context[CALL_OPTIONS];
147
+ if (!callOptions) {
148
+ throw new TypeError(`${resourceName} filter "${used[0][0]}" reads join sources, which only a read through its handle builds.`);
149
+ }
150
+ const options = { context: callOptions.context, trx: callOptions.trx };
151
+ context[PREPARED_SOURCES] ??= new Map();
152
+ const byFilter = new Map();
153
+ for (const [filter, sources] of used) {
154
+ const byAlias = new Map();
155
+ for (const [alias, pick] of Object.entries(sources)) {
156
+ const owner = /** @type {{ joinSource?: Function } | null | undefined} */ (ownerOf(pick));
157
+ // readable-check: allow method-probe - input validation: the picked owner answers join sources
158
+ if (typeof owner?.joinSource !== "function") {
159
+ throw new TypeError(`${resourceName} filter "${filter}" join source "${alias}" names no owner with joinSource({ alias }, options).`);
160
+ }
161
+ byAlias.set(alias, await owner.joinSource({ alias }, options));
162
+ }
163
+ byFilter.set(filter, byAlias);
164
+ }
165
+ context[PREPARED_SOURCES].set(resourceName, byFilter);
166
+ }
167
+
168
+ return {
169
+ knexQueryFiltering: {
170
+ functionName: "jskitFilterJoinSources",
171
+ beforeFunction: "polymorphicFiltersHook",
172
+ handler: buildFilterJoinSources
173
+ }
174
+ };
175
+ }
176
+
177
+ export { filterJoinSources, joinSourceHooks, withCallOptions };
@@ -11,7 +11,7 @@ import { returnBadRequestWhenJsonRestFieldsetInvalid } from "./resourceHost.js";
11
11
  * A handle's reads of every row its filters match: queryAll, which answers them at once, and queryPages, which hands
12
12
  * them over a page at a time. Both read in cursor pages of `settings.serverPageSize` rows and, in a request context,
13
13
  * stop past `settings.requestRowLimit` rows; a system context, and the workspace and user contexts it derives, read
14
- * without a limit.
14
+ * without a limit. queryAll with `take` answers only the first `take` rows, and reads no further.
15
15
  * @param {object} dependencies
16
16
  * @param {{ knex: { instance: any } }} dependencies.api The table's json-rest-api, whose Knex sends its statements.
17
17
  * @param {string} dependencies.name The resource's name.
@@ -34,11 +34,18 @@ function createEveryRowReads({ api, name, resource, jsonRest, readFields, contex
34
34
  * id order (or `sort`). In a request it throws past the request row limit
35
35
  * (pageLimits().requestRows); a system context, and the workspace and user
36
36
  * contexts it derives, read without one, holding every row in memory:
37
- * queryPages() reads them a page at a time.
38
- * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} [params]
37
+ * queryPages() reads them a page at a time. With `take`, it answers the first
38
+ * `take` of them in that order and reads no further (see takeRows), in a request
39
+ * too, where `take` is the bound instead of the request row limit.
40
+ * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object, take?: number }} [params]
39
41
  * @param {{ context?: object | null, trx?: object | null }} [options]
40
42
  */
41
43
  async function queryAll(params = {}, options = {}) {
44
+ if (params !== null && typeof params === "object" && Object.hasOwn(params, "take")) {
45
+ const { take, ...read } = params;
46
+ // take: undefined is no take, as an option left undefined is anywhere.
47
+ return take === undefined ? queryAll(read, options) : takeRows(read, take, options);
48
+ }
42
49
  const context = contextOf(options);
43
50
  const rowLimit = rowLimitOf(options);
44
51
  checkBlobReads(name, "queryAll", namedBlobs(resource, params.fields, resourceNamed), Infinity);
@@ -67,6 +74,55 @@ function createEveryRowReads({ api, name, resource, jsonRest, readFields, contex
67
74
  }
68
75
  }
69
76
 
77
+ /**
78
+ * queryAll() with `take`: the first `take` records the filters match, in id order (or `sort`), read in pages of at
79
+ * most pageLimits().server rows, the last page no larger than the rows still wanted, so nothing past the `take`-th
80
+ * row is read. `take` bounds the read, so a request reads past the request row limit when it names more, and never
81
+ * throws RowLimitError: name a bound the work can hold. The pages after the first are reported as queryPages()
82
+ * reports its own, so expectFlatQueries() allows them.
83
+ * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} params
84
+ * @param {unknown} take
85
+ * @param {{ context?: object | null, trx?: object | null }} options
86
+ */
87
+ async function takeRows(params, take, options) {
88
+ if (!Number.isSafeInteger(take) || /** @type {number} */ (take) < 1) {
89
+ throw new TypeError(`${name}.queryAll() take is the most records it answers, a whole number from 1. Received: ${JSON.stringify(take)}`);
90
+ }
91
+ const wanted = /** @type {number} */ (take);
92
+ const context = contextOf(options);
93
+ checkBlobReads(name, "queryAll", namedBlobs(resource, params.fields, resourceNamed), wanted);
94
+ const read = { ...params, fields: readFields(params, "list") };
95
+ const queryParams = readQueryParams(resource, read, { page: false, caller: "queryAll" });
96
+ const hidden = hiddenFields.named(params.fields, "plain");
97
+ if (matchesNoRow(params.filters, jsonRest().vars.schemaInfo)) {
98
+ return [];
99
+ }
100
+ const sort = queryParams.sort?.length ? queryParams.sort : ["id"];
101
+ const rows = [];
102
+ let after;
103
+ // One page: as many rows as are still wanted, up to a server page, after the last row of the page before.
104
+ const page = async () => {
105
+ const size = Math.min(settings.serverPageSize, wanted - rows.length);
106
+ const payload = await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().query(
107
+ {
108
+ queryParams: { ...queryParams, sort, page: after === undefined ? { size } : { size, after } },
109
+ pageSizeLimit: size,
110
+ transaction: options.trx || undefined,
111
+ format: "plain"
112
+ },
113
+ { ...context }
114
+ ));
115
+ rows.push(...payload.data);
116
+ const pagination = payload.meta?.pagination;
117
+ after = pagination?.hasMore === true && rows.length < wanted ? pagination.cursor?.next ?? undefined : undefined;
118
+ };
119
+ await page();
120
+ while (after !== undefined) {
121
+ await reportedPageRead(api.knex.instance, name, page);
122
+ }
123
+ return hiddenFields.add(handleRecords(resource, rows, read, resourceNamed), hidden, options);
124
+ }
125
+
70
126
  /**
71
127
  * The records queryAll() answers, handed over a page at a time, so work over
72
128
  * many rows holds one page in memory: `for await (const records of
@@ -1,6 +1,8 @@
1
+ import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
1
2
  import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
2
3
  import { missingOf, requireDefinedFilters } from "./handleGuards.js";
3
- import { handleRecords, sparseFieldset, textList } from "./handleRecords.js";
4
+ import { defaultFieldList, handleRecords, includedRelationships, sparseFieldset, textList } from "./handleRecords.js";
5
+ import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
4
6
 
5
7
  // The row lock a locking read takes. "update" (the default) is FOR UPDATE. "noKeyUpdate" is PostgreSQL's FOR NO KEY
6
8
  // UPDATE, which still keeps every other lock and write of the row out but lets other transactions insert rows that
@@ -25,26 +27,37 @@ function lockModeOf(name, caller, lockMode) {
25
27
  return { lockMode };
26
28
  }
27
29
 
30
+ // The most rows one read of the locked rows' links names, as the lock itself reads its ids in chunks of 1,000.
31
+ const LINKS_PER_READ = 1000;
32
+
28
33
  /**
29
- * Refuses `include` on a locking read, before anything runs: a lock answers only the rows it locks. A plain read of
30
- * their related records inside the transaction (json-rest-api's includes are plain reads) would see, on MySQL and
31
- * MariaDB, the snapshot of the transaction's first plain read rather than the rows as they are under the lock, so the
32
- * caller reads them itself, in the order that makes them current.
33
- * @param {string} name The resource's name.
34
+ * The relationships a locking read includes, each a belongs-to field of the resource named by its relationship (`as`,
35
+ * or the field's own name): `{ relationshipName, field, target, below }`, `below` the include paths under it. A lock
36
+ * includes the records its rows name, each locked after them; a collection, or a name that is no belongs-to
37
+ * relationship, is a TypeError before anything runs.
38
+ * @param {{ name: string, schema: Record<string, any> }} resource
34
39
  * @param {string} caller The handle method, for the message.
35
40
  * @param {unknown} include
36
41
  */
37
- function refuseInclude(name, caller, include) {
38
- if (include === undefined) {
39
- return;
40
- }
41
- throw new TypeError(
42
- `${name}.${caller}() locks only its own rows and reads no included records, so it takes no include. Read the ` +
43
- "related records after the lock, in the same transaction: queryAll({ filters: { id: ids }, include }, txOptions) " +
44
- "or the related table's read by id list. On MySQL and MariaDB a plain read inside a transaction sees the snapshot " +
45
- "of the transaction's first plain read: take the lock before any plain read, so the reads after it see what the " +
46
- "lock's previous holder committed, and lock a related row the work depends on with its own lockMany()."
47
- );
42
+ function lockedIncludes(resource, caller, include) {
43
+ const links = new Map(Object.entries(resource.schema)
44
+ .filter(([, definition]) => typeof definition?.belongsTo === "string")
45
+ .map(([field, definition]) => [definition.as || field, { field, target: definition.belongsTo }]));
46
+ return [...includedRelationships(include)].map(([relationshipName, below]) => {
47
+ const link = links.get(relationshipName);
48
+ if (!link) {
49
+ throw new TypeError(
50
+ `${resource.name}.${caller}() includes "${relationshipName}", which is no belongs-to relationship of ` +
51
+ `${resource.name}: a lock includes only the records its rows name, and locks each of them after its rows. ` +
52
+ "Lock a collection's rows with that table's own lockWhere() in the same transaction."
53
+ );
54
+ }
55
+ return Object.freeze({
56
+ relationshipName,
57
+ ...link,
58
+ below
59
+ });
60
+ });
48
61
  }
49
62
 
50
63
  /**
@@ -52,27 +65,135 @@ function refuseInclude(name, caller, include) {
52
65
  * caller's transaction (`options.trx`), locks only rows the caller may see, and
53
66
  * reads the fields `options.fields` names, or every field a one-record read
54
67
  * answers, so a belongs-to field left out costs no check that its related
55
- * record is visible.
68
+ * record is visible. `include` names belongs-to relationships whose records the
69
+ * lock locks too, after its own rows (see withLockedIncludes).
56
70
  * @param {object} dependencies
71
+ * @param {{ knex: { instance: any, helpers: { getStorageAdapter(scopeName: string): any } } }} dependencies.api
72
+ * The table's json-rest-api host, whose storage adapter names the table's columns.
57
73
  * @param {string} dependencies.name The resource's name.
58
- * @param {{ name: string, schema: Record<string, any> }} dependencies.resource
59
- * @param {() => Record<string, (params: object, context: object) => Promise<{ data: unknown[] }>>} dependencies.jsonRest
60
- * The table's json-rest-api resource.
74
+ * @param {{ name: string, tableName: string, schema: Record<string, any> }} dependencies.resource
75
+ * @param {() => Record<string, any>} dependencies.jsonRest The table's json-rest-api resource.
61
76
  * @param {(params: { fields?: unknown }, kind: "view") => unknown} dependencies.readFields The fields a read names.
62
77
  * @param {(options: object) => object} dependencies.contextOf The call's json-rest-api context, after its scope checks.
63
78
  * @param {import("./types.js").HiddenFieldReads} dependencies.hiddenFields The hidden
64
79
  * fields `options.fields` names, read after the lock.
80
+ * @param {(name: string) => ({ lockMany: Function } | null)} dependencies.handleNamed The handles of the application's
81
+ * owned tables by resource name, which lock included records.
82
+ * @param {(name: string) => ({ schema: Record<string, any>, relationships?: Record<string, any> } | null)} dependencies.resourceNamed
83
+ * The application's table resources by name, whose collections an included record leaves out.
65
84
  */
66
- function createLockReads({ name, resource, jsonRest, readFields, contextOf, hiddenFields }) {
85
+ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed }) {
86
+ /**
87
+ * The collections of a related table an included record leaves out, as a read's include does (see handleRecord):
88
+ * every one it does not include itself.
89
+ * @param {string} target
90
+ * @param {string[]} below The include paths under the relationship.
91
+ */
92
+ function collectionsLeftOut(target, below) {
93
+ const included = includedRelationships(below);
94
+ return Object.keys(resolveJsonRestCollectionRelationships(resourceNamed(target))).filter((relationshipName) => !included.has(relationshipName));
95
+ }
96
+
97
+ /**
98
+ * The fields a locking read with includes names: the caller's own, or every field a one-record read answers, less
99
+ * the included relationships, whose links withLockedIncludes reads itself.
100
+ * @param {unknown} fields
101
+ * @param {ReadonlyArray<{ relationshipName: string, field: string }>} includes
102
+ */
103
+ function fieldsBeside(fields, includes) {
104
+ const left = new Set(includes.flatMap(({ relationshipName, field }) => [relationshipName, field]));
105
+ const named = fields === undefined ? defaultFieldList(jsonRest().vars.schemaInfo) : fields;
106
+ return Array.isArray(named) ? named.filter((field) => !left.has(field)) : named;
107
+ }
108
+
109
+ /**
110
+ * The locked rows' links as the database holds them now, `{ [field]: id | null }` by row id, for the belongs-to
111
+ * fields named: on MySQL and MariaDB a locking read (FOR SHARE, of rows this transaction already holds), which sees
112
+ * them as locked whatever snapshot the transaction's plain reads keep; elsewhere a plain read, which sees them too.
113
+ * The rows are the lock's own, so its scope already applied: only their links are read.
114
+ * @param {string[]} ids
115
+ * @param {string[]} fields
116
+ * @param {{ trx: any }} options
117
+ */
118
+ async function currentLinks(ids, fields, options) {
119
+ const adapter = api.knex.helpers.getStorageAdapter(name);
120
+ const idColumn = adapter.getIdColumn();
121
+ const locking = detectDialectFromClient(options.trx) === "mysql";
122
+ const links = new Map();
123
+ for (let start = 0; start < ids.length; start += LINKS_PER_READ) {
124
+ const part = ids.slice(start, start + LINKS_PER_READ).map((id) => adapter.translateFilterValue("id", id));
125
+ const read = options.trx(resource.tableName)
126
+ .whereIn(idColumn, part)
127
+ .select({ id: idColumn, ...Object.fromEntries(fields.map((field) => [field, adapter.translateColumn(field)])) });
128
+ for (const row of await (locking ? read.forShare() : read)) {
129
+ links.set(String(row.id), Object.fromEntries(fields.map((field) => [field, row[field] == null ? null : String(row[field])])));
130
+ }
131
+ }
132
+ return links;
133
+ }
134
+
135
+ /**
136
+ * The locked records with each included record locked and nested under its relationship, as a read's include
137
+ * nests it: through the related table's own handle (its scope, its row policy, its hidden fields), in id order,
138
+ * after the lock's rows, with `missing: "skip"`, in the call's lock mode, each included type once however many rows
139
+ * name it, and the paths below it included the same way. The links come from currentLinks, so a record committed
140
+ * after the transaction's first plain read is found and locked. A link to a record the caller may not see reads as
141
+ * a read's does: the belongs-to field null, the relationship undefined.
142
+ * @param {Array<Record<string, any>>} records
143
+ * @param {ReadonlyArray<{ relationshipName: string, field: string, target: string, below: string[] }>} includes
144
+ * @param {{ context?: object | null, trx: any, lockMode?: string }} options
145
+ */
146
+ async function withLockedIncludes(records, includes, options) {
147
+ if (records.length < 1) {
148
+ return records;
149
+ }
150
+ const links = await currentLinks(records.map(({ id }) => String(id)), includes.map(({ field }) => field), options);
151
+ const answered = records.map((record) => ({ ...record }));
152
+ for (const { relationshipName, field, target, below } of includes) {
153
+ const handle = handleNamed(target);
154
+ if (!handle) {
155
+ throw new TypeError(`${name} includes "${relationshipName}" from "${target}", which no feature owns.`);
156
+ }
157
+ const linked = (record) => links.get(String(record.id))?.[field] ?? null;
158
+ const ids = [...new Set(answered.map(linked).filter((id) => id !== null))];
159
+ const locked = ids.length < 1 ? [] : await handle.lockMany(ids, {
160
+ context: options.context,
161
+ trx: options.trx,
162
+ missing: "skip",
163
+ ...(options.lockMode === undefined ? {} : { lockMode: options.lockMode }),
164
+ ...(below.length > 0 ? { include: below } : {})
165
+ });
166
+ const leftOut = collectionsLeftOut(target, below);
167
+ const byId = new Map(locked.map((record) => {
168
+ const shaped = { ...record };
169
+ for (const relationshipName of leftOut) {
170
+ delete shaped[relationshipName];
171
+ }
172
+ return [String(record.id), shaped];
173
+ }));
174
+ // As a read answers it: a record it may not see, or none, leaves the link null and the relationship undefined.
175
+ for (const record of answered) {
176
+ const related = byId.get(String(linked(record)));
177
+ if (relationshipName !== field) {
178
+ record[field] = related === undefined ? null : String(related.id);
179
+ }
180
+ record[relationshipName] = related;
181
+ }
182
+ }
183
+ return answered;
184
+ }
185
+
67
186
  // A locking read (json-rest-api's lockByIds, lockWhere or claim) of the fields options.fields names, as records, in the
68
- // lock mode options.lockMode names. `caller` is the handle method, for the messages.
69
- async function lockRead(caller, method, read, options) {
70
- refuseInclude(name, caller, options.include);
187
+ // lock mode options.lockMode names, with the records `include` names locked after it. `caller` is the handle method,
188
+ // for the messages.
189
+ async function lockRead(caller, method, read, options, include = options.include) {
190
+ const includes = lockedIncludes(resource, caller, include);
71
191
  // lock() and lockMany() hold their ids' blobs, lockWhere() and claim() any number of rows, so they name none.
72
192
  checkBlobReads(name, caller, namedBlobs(resource, options.fields, () => null), method === "lockByIds" ? read.ids.length : Infinity);
73
193
  const mode = lockModeOf(name, caller, options.lockMode);
74
194
  const hidden = hiddenFields.named(options.fields, "plain");
75
- const fields = readFields({ fields: options.fields }, "view");
195
+ const named = readFields({ fields: options.fields }, "view");
196
+ const fields = includes.length > 0 ? fieldsBeside(named, includes) : named;
76
197
  const { data } = await jsonRest()[method]({
77
198
  ...read,
78
199
  ...mode,
@@ -80,7 +201,8 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
80
201
  format: "plain",
81
202
  ...(fields ? { queryParams: { fields: sparseFieldset(resource, fields) } } : {})
82
203
  }, contextOf(options));
83
- return hiddenFields.add(handleRecords(resource, data, { fields }), hidden, options);
204
+ const records = await hiddenFields.add(handleRecords(resource, data, { fields }), hidden, options);
205
+ return includes.length > 0 ? withLockedIncludes(records, includes, options) : records;
84
206
  }
85
207
 
86
208
  /**
@@ -89,8 +211,10 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
89
211
  * `fields` names the fields the lock reads, so a belongs-to field left out costs no check that its related
90
212
  * record is visible; without it every field is read. `lockMode: "noKeyUpdate"` takes PostgreSQL's FOR NO KEY
91
213
  * UPDATE, so other transactions may still insert rows that reference the locked ones (see LOCK_MODES).
214
+ * `include` names belongs-to relationships whose records are locked after the rows, through their own tables'
215
+ * handles, and nested as a read's include nests them (see withLockedIncludes).
92
216
  * @param {unknown[]} ids
93
- * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" }} options
217
+ * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
94
218
  */
95
219
  async function lockMany(ids, options) {
96
220
  return lockRead("lockMany", "lockByIds", { ids, ...(options.missing ? { missing: options.missing } : {}) }, options);
@@ -107,7 +231,7 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
107
231
  * json-rest-api's not-found error, or answers null with `missing: "skip"`.
108
232
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
109
233
  * @param {unknown} id
110
- * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate" }} options
234
+ * @param {{ context?: object | null, trx: object, missing?: "throw" | "skip", fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
111
235
  */
112
236
  async function lock(id, options) {
113
237
  missingOf(name, "lock", options.missing);
@@ -124,7 +248,7 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
124
248
  * with the ownership columns (no owners: with a filtered column), or it refuses.
125
249
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
126
250
  * @param {object} filters
127
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" }} options
251
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
128
252
  */
129
253
  async function lockWhere(filters, options) {
130
254
  requireDefinedFilters(name, "lockWhere", filters);
@@ -135,20 +259,23 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
135
259
  * Takes up to `take` (default 1) of the rows the filters select that no
136
260
  * other transaction holds, in `sort` order, locked until the transaction ends.
137
261
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
138
- * @param {{ filters: object, sort?: string | string[], take?: number }} params
139
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" }} options
262
+ * `include` (in params or options, not both) locks and nests the records the rows name, as lockMany's does.
263
+ * @param {{ filters: object, sort?: string | string[], take?: number, include?: string | string[] }} params
264
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate", include?: string | string[] }} options
140
265
  */
141
266
  async function claim({ filters, sort, take, include } = {}, options, ...rest) {
142
267
  if (rest.length > 0) {
143
- throw new TypeError(`${name}.claim() takes ({ filters, sort, take }, options).`);
268
+ throw new TypeError(`${name}.claim() takes ({ filters, sort, take, include }, options).`);
269
+ }
270
+ if (include !== undefined && options?.include !== undefined) {
271
+ throw new TypeError(`${name}.claim() takes include once: in its params or in its options, not both.`);
144
272
  }
145
- refuseInclude(name, "claim", include);
146
273
  requireDefinedFilters(name, "claim", filters);
147
274
  return lockRead("claim", "claim", {
148
275
  filters,
149
276
  ...(take === undefined ? {} : { limit: take }),
150
277
  ...(sort === undefined ? {} : { sort: textList(sort) })
151
- }, options);
278
+ }, options, include ?? options.include);
152
279
  }
153
280
 
154
281
  return Object.freeze({
@@ -68,13 +68,23 @@ function requestedFields(params, quiet, schemaInfo) {
68
68
  return params.fields;
69
69
  }
70
70
  const left = new Set(skipped.flatMap(({ fieldName, relationshipName }) => [fieldName, relationshipName]));
71
- const { outputFields, outputRelationships, idProperty } = schemaInfo();
71
+ return defaultFieldList(schemaInfo()).filter((field) => !left.has(field));
72
+ }
73
+
74
+ /**
75
+ * Every field a read that names none answers, as a list a read can name: the attributes json-rest-api answers by
76
+ * default (none hidden, none normally hidden, blobs among those) and every relationship.
77
+ * @param {{ outputFields: Record<string, any>, outputRelationships: Record<string, any>, idProperty?: string }} schemaInfo
78
+ * json-rest-api's compiled schema of the resource.
79
+ * @returns {string[]}
80
+ */
81
+ function defaultFieldList({ outputFields, outputRelationships, idProperty }) {
72
82
  return [
73
83
  ...Object.entries(outputFields)
74
84
  .filter(([field, definition]) => field !== "id" && field !== idProperty && !definition?.hidden && !definition?.normallyHidden)
75
85
  .map(([field]) => field),
76
86
  ...Object.keys(outputRelationships)
77
- ].filter((field) => !left.has(field));
87
+ ];
78
88
  }
79
89
 
80
90
  /**
@@ -455,6 +465,8 @@ function patchAnswer(id, record, returning) {
455
465
 
456
466
  export {
457
467
  aggregateMeasures,
468
+ defaultFieldList,
469
+ includedRelationships,
458
470
  MANY_RETURNING,
459
471
  SINGLE_RETURNING,
460
472
  handleRecords,