@jskit-ai/resource-runtime 0.2.17 → 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/locales/en.json +3 -1
  3. package/package.json +6 -6
  4. package/src/server/errors.js +29 -5
  5. package/src/server/filterJoinSources.js +177 -0
  6. package/src/server/handleBlobs.js +139 -0
  7. package/src/server/handleEveryRow.js +188 -0
  8. package/src/server/handleHidden.js +46 -4
  9. package/src/server/handleLocks.js +173 -19
  10. package/src/server/handleRecords.js +16 -3
  11. package/src/server/index.js +1 -0
  12. package/src/server/manyRowChannel.js +44 -0
  13. package/src/server/resourceHandle.js +64 -52
  14. package/src/server/resourceHost.js +5 -5
  15. package/src/server/resourceRuntime.js +67 -20
  16. package/src/server/types.js +5 -0
  17. package/src/test/expectFlatQueries.js +23 -11
  18. package/src/test/index.js +2 -2
  19. package/test/blobFields.mysql.test.js +8 -0
  20. package/test/blobFields.test.js +8 -0
  21. package/test/crossTableFilters.mysql.test.js +8 -0
  22. package/test/crossTableFilters.test.js +8 -0
  23. package/test/filterJoinSources.mysql.test.js +8 -0
  24. package/test/filterJoinSources.test.js +8 -0
  25. package/test/hiddenFields.test.js +41 -0
  26. package/test/lockIncludes.mysql.test.js +8 -0
  27. package/test/lockIncludes.test.js +8 -0
  28. package/test/lockedReads.mysql.test.js +156 -0
  29. package/test/pagedReads.mysql.test.js +8 -0
  30. package/test/pagedReads.test.js +8 -0
  31. package/test/reportsAcrossOwners.mysql.test.js +8 -0
  32. package/test/reportsAcrossOwners.test.js +8 -0
  33. package/test/resourceRuntime.test.js +55 -2
  34. package/test/support/blobFieldsCases.js +226 -0
  35. package/test/support/crossTableFiltersCases.js +180 -0
  36. package/test/support/filterJoinSourcesCases.js +256 -0
  37. package/test/support/lockIncludesCases.js +158 -0
  38. package/test/support/mysqlDatabase.js +35 -0
  39. package/test/support/pagedReadsCases.js +168 -0
  40. package/test/support/reportsAcrossOwnersCases.js +201 -0
  41. package/test/testHelpers.test.js +128 -3
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
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`.
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.
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.
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.
12
+ - **Breaking.** A grouped `aggregate` never answers part of its groups. Without `page` it asked json-rest-api for its default page (20 groups) and dropped the `hasMore` that said more were left, so a total per user, per month or per workspace silently lost every group past the 20th. It now asks for the most one statement answers, `pageLimits().request` (the resource's `queryMaxLimit`), and throws `GroupLimitError` (a 400 coded `RESOURCE_GROUP_LIMIT`, message code `resource.groupLimit`) when there are more. `page: { size, number }` reads them in pages, a page shorter than `size` being the last; a `page` without `size` is a TypeError. Upgrading: a grouped aggregate that can have more groups than `queryMaxLimit` reads them in pages, `page: { size, number }`, until a page answers fewer than `size`; one that passed `page` without `size` names it.
13
+ - `queryPages(params, options)` reads what `queryAll` reads a page at a time, `for await (const records of handle.queryPages(params, options))`, so a job over a table of any size holds one page in memory. Each page is one statement of up to `pageLimits().server` rows, plus the reads of its includes and of the hidden fields it names, and starts after the sort values of the page before: a job may change what its filters match as it goes, and no row still to come is skipped or read twice while it leaves the sort fields' values (the id, by default) alone. In a request it throws `RowLimitError` at the request row limit, as `queryAll` does, before answering the page that passes it. `expectFlatQueries()` allows each later page's own statements, which the handle reports as a many-row write reports its later chunks, so a paged read measures flat however few rows its pages hold. `withoutHiddenFields` strips hidden fields from each page it hands another feature, and refuses a hidden field its fields name, from `queryPages` or an owner's method of any other name, as a rejected promise that is also pages that throw, so `await` and `for await` both get the refusal and none is left unhandled; another async iterable it answers, such as a Node stream, passes as it is. `pageLimits()` also answers `requestRows`, the request row limit, and `RowLimitError` names the call that hit it and points to `queryPages`.
14
+ - A test pins how `startTestFeatures` meets a capability cycle between two table owners, one of them through an `optional` require: it refuses them before any setup with the kernel's `Provider capability cycle detected: children -> parents -> children.`, as the server's boot does. The data-access guide says what such a cycle is, how it shows up and how to keep requires pointing one way.
15
+ - **Breaking.** `lock`, `lockMany`, `lockWhere` and `claim` refuse `include` (in their options, or in `claim`'s params; `include: []` too) with a TypeError before any statement, saying how to read the related records: they read no included records and dropped it silently, so a caller got its locked rows without their relations and no word. The related records come from a read after the lock in the same transaction; on MySQL and MariaDB that read is current only when the lock came before the transaction's first plain read, which `lockedReads.mysql.test.js` shows with two transactions on one seat. Upgrading: drop `include` from the lock, and read the related records after it in the same transaction, `queryAll({ filters: { id: ids }, include }, txOptions)` or the related table's read by id list.
16
+ - An `owns` entry's `rowPolicy` receives the owning feature's dependencies (the capabilities it requires, and its optional ones), by local name, as `requires`, the same values its setup receives, beside `caller` and `ownTable`. `own(featureId, owns, { requires })` takes them, and defineFeature passes them; a policy needing another feature's capability had no way to reach it. A contributed row policy is unchanged: its feature builds it in setup, with its own.
17
+ - **Breaking.** A many-row call (`createMany`, `patchMany`, `patchWhere`, `deleteWhere`) refuses a `chunkSize` that is not a whole number of at least 100 rows, with a `TypeError` naming the call, before any statement; one left out is still 500. A chunk of 1 or 5 rows sent a statement every row or few, as a loop of single-row writes does, and `expectFlatQueries()` allowed those statements as the call's later chunks, so it passed a write that grew with its rows. Upgrading: a call that passed a smaller `chunkSize` passes 100 or more, or none.
18
+ - `expectFlatQueries()` counts only the measured path's own statements and many-row reports, from `run` and the async work it starts: a test or a background loop running beside it in the same process no longer changes the count. The many-row channel is process-wide, so another test's chunked write was taken for the path's own later chunks, which could hide statements that grow with the rows.
5
19
  - The resource runtime answers `tableResource(name)`: the table resource a feature owns under that name, or null. The CRUD contracts registry checks at boot, through it, what each contract's includes list of the tables they include.
6
20
  - The MariaDB many-row race tests read `INNODB_TRX` every 150 ms, where they polled it every 25 ms: InnoDB refreshes its copy of that table only when nothing has read it for 0.1 s, so the tests read the copy from before the writers reached the row's lock until their 10 s bound ran out, on any server whose test user may read it (CI's root).
7
21
  - Depends on json-rest-api 3.1.1 exactly (from 3.1.0), from the registry with its published integrity: a sort on the ID, or on a required attribute stored in its own table, carries no null placement, so PostgreSQL and MariaDB read a descending page from an index instead of sorting every matching row.
package/locales/en.json CHANGED
@@ -10,7 +10,9 @@
10
10
  }
11
11
  },
12
12
  "resource": {
13
- "rowLimit": "This request would read more than {rowLimit} rows. Ask for fewer and try again."
13
+ "rowLimit": "This request would read more than {rowLimit} rows. Ask for fewer and try again.",
14
+ "groupLimit": "This request would total more than {groupLimit} groups. Ask for fewer and try again.",
15
+ "blobFields": "This request asks for {fields}, which a JSON answer cannot hold. Leave them out and try again."
14
16
  }
15
17
  }
16
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -15,9 +15,9 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.207",
19
- "@jskit-ai/resource-crud-core": "0.1.207",
20
- "json-rest-api": "3.1.1"
18
+ "@jskit-ai/resource-core": "0.1.208",
19
+ "@jskit-ai/resource-crud-core": "0.1.208",
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": {
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.265",
68
- "@jskit-ai/kernel": "0.2.16"
67
+ "@jskit-ai/database-runtime": "0.1.266",
68
+ "@jskit-ai/kernel": "0.2.17"
69
69
  }
70
70
  }
@@ -85,26 +85,49 @@ class PageSizeError extends TypeError {
85
85
  }
86
86
 
87
87
  /**
88
- * queryAll() in a request context reading past the request row limit: the request answers a 400 coded
88
+ * queryAll() or queryPages() in a request context reading past the request row limit: the request answers a 400 coded
89
89
  * RESOURCE_ROW_LIMIT, with a sentence the client can show in the user's language, instead of a 500.
90
90
  */
91
91
  class RowLimitError extends AppError {
92
92
  /**
93
93
  * @param {string} resourceName
94
94
  * @param {number} rowLimit
95
- * @param {unknown} cause
95
+ * @param {unknown} [cause]
96
+ * @param {"queryAll" | "queryPages"} [caller]
96
97
  */
97
- constructor(resourceName, rowLimit, cause) {
98
+ constructor(resourceName, rowLimit, cause, caller = "queryAll") {
98
99
  super(
99
100
  400,
100
- `${resourceName}.queryAll() read more than ${rowLimit} rows inside a request. Work over that many rows belongs ` +
101
- "in a background job: a feature with systemScope, working per workspace with systemContext(reason).forWorkspace(id).",
101
+ `${resourceName}.${caller}() read more than ${rowLimit} rows inside a request. Work over that many rows belongs ` +
102
+ "in a background job: a feature with systemScope, working per workspace with systemContext(reason).forWorkspace(id), " +
103
+ "where queryPages() reads them a page at a time.",
102
104
  { cause, code: "RESOURCE_ROW_LIMIT", messageCode: "resource.rowLimit", messageParams: { rowLimit } }
103
105
  );
104
106
  this.name = "RowLimitError";
105
107
  }
106
108
  }
107
109
 
110
+ /**
111
+ * A grouped aggregate() without a page that has more groups than one statement answers: it throws a 400 coded
112
+ * RESOURCE_GROUP_LIMIT, with a sentence the client can show in the user's language, rather than answer part of them.
113
+ */
114
+ class GroupLimitError extends AppError {
115
+ /**
116
+ * @param {string} resourceName
117
+ * @param {number} groupLimit
118
+ */
119
+ constructor(resourceName, groupLimit) {
120
+ super(
121
+ 400,
122
+ `${resourceName}.aggregate() has more than ${groupLimit} groups, the most one statement answers. Read them in pages, ` +
123
+ `page: { size, number } with size up to ${groupLimit} and number from 1, until a page answers fewer than size ` +
124
+ "rows, or narrow the filters.",
125
+ { code: "RESOURCE_GROUP_LIMIT", messageCode: "resource.groupLimit", messageParams: { groupLimit } }
126
+ );
127
+ this.name = "GroupLimitError";
128
+ }
129
+ }
130
+
108
131
  /** patch() with lockVersion on a record someone else changed since it was read. */
109
132
  class StaleRecordError extends AppError {
110
133
  constructor() {
@@ -127,6 +150,7 @@ class DuplicateOwnerError extends Error {
127
150
 
128
151
  export {
129
152
  DuplicateOwnerError,
153
+ GroupLimitError,
130
154
  MissingScopeError,
131
155
  PageSizeError,
132
156
  RowLimitError,
@@ -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 };
@@ -0,0 +1,139 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { RestApiValidationError } from "json-rest-api";
3
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
4
+ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
5
+
6
+ // A blob field (`type: "blob"`, with the `maxBytes` defineTableResource requires) is a value the process holds whole:
7
+ // a write takes bytes within the limit, checked before any statement, a read answers it only when its fields name it,
8
+ // and no read holds more than BLOB_READ_BYTES of them, but one record's, or answers them as JSON.
9
+
10
+ // The most bytes of named blobs one read holds when it answers more than one record: query() pages and lockMany() ids
11
+ // are refused past it, and queryPages() pages shrink until their blobs fit.
12
+ const BLOB_READ_BYTES = 16 * 1024 * 1024;
13
+
14
+ /**
15
+ * The resource's blob fields.
16
+ * @param {{ schema: Record<string, any> }} resource
17
+ * @returns {string[]}
18
+ */
19
+ function blobFields(resource) {
20
+ return Object.keys(resource.schema).filter((field) => resource.schema[field]?.type === "blob");
21
+ }
22
+
23
+ /**
24
+ * Checks each blob value a write sends, at the top of the write, before any statement (a transaction's BEGIN, a lock):
25
+ * null, or a Buffer or Uint8Array of at most the field's maxBytes. Anything else is a validation error on the field
26
+ * (422 at the HTTP edge). A row that is not a record is left to the write, which refuses it.
27
+ * @param {{ name: string, schema: Record<string, any> }} resource
28
+ * @param {ReadonlyArray<unknown>} rows The write's attributes, one record each.
29
+ */
30
+ function checkBlobValues(resource, rows) {
31
+ const fields = blobFields(resource);
32
+ for (const row of rows.filter(isRecord)) {
33
+ for (const field of fields) {
34
+ const value = row[field];
35
+ if (value === undefined || value === null) {
36
+ continue;
37
+ }
38
+ const refuse = (rule, message) => {
39
+ throw new RestApiValidationError(`${resource.name}.${field} ${message}`, { fields: [field], violations: [{ field, rule, message }] });
40
+ };
41
+ if (!(value instanceof Uint8Array)) {
42
+ refuse("blob", "is a blob, whose value is a Buffer or a Uint8Array.");
43
+ }
44
+ if (value.byteLength > resource.schema[field].maxBytes) {
45
+ refuse("max_bytes", `holds at most ${resource.schema[field].maxBytes} bytes; this value has ${value.byteLength}.`);
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A write's data with each Uint8Array blob as a Buffer, as every driver takes it.
53
+ * @param {{ schema: Record<string, any> }} resource
54
+ * @param {Record<string, unknown>} data The write's own copy of its attributes, which this changes in place.
55
+ */
56
+ function blobBuffers(resource, data) {
57
+ for (const field of blobFields(resource)) {
58
+ const value = data[field];
59
+ if (value instanceof Uint8Array && !Buffer.isBuffer(value)) {
60
+ data[field] = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
61
+ }
62
+ }
63
+ return data;
64
+ }
65
+
66
+ /**
67
+ * The blob fields a read's `fields` names, of the resource (a list of names, or its entry in a sparse fieldset) and of
68
+ * any other resource a sparse fieldset names, an included one, each as `{ label, maxBytes, included }`.
69
+ * @param {{ name: string, schema: Record<string, any> }} resource
70
+ * @param {unknown} fields
71
+ * @param {(name: string) => ({ name: string, schema: Record<string, any> } | null)} resourceNamed
72
+ */
73
+ function namedBlobs(resource, fields, resourceNamed) {
74
+ const lists = Array.isArray(fields) || typeof fields === "string" ? [[resource, String(fields).split(",")]]
75
+ : isRecord(fields) ? Object.entries(fields).map(([name, list]) => [name === resource.name ? resource : resourceNamed(name), String(list).split(",")])
76
+ : [];
77
+ return lists.flatMap(([table, list]) => (table === null ? [] : list
78
+ .map((field) => String(field).trim())
79
+ .filter((field) => table.schema[field]?.type === "blob")
80
+ .map((field) => ({ label: `${table.name}.${field}`, maxBytes: table.schema[field].maxBytes, included: table !== resource }))));
81
+ }
82
+
83
+ const labelsOf = (blobs) => blobs.map(({ label }) => label).join(", ");
84
+
85
+ /**
86
+ * Checks the blobs a read names before anything runs, so that it holds at most BLOB_READ_BYTES of them, or one
87
+ * record's, and answers the most rows of them that fit. `rows` is the most rows the read answers: 1 for get() and
88
+ * lock(), the page size for query(), the ids for lockMany(), Infinity for a read of every matching row (queryAll,
89
+ * lockWhere, claim), which names none. A blob of an included table is refused, since an include holds any number of
90
+ * records.
91
+ * @param {string} name The resource's name.
92
+ * @param {string} caller The handle method, for the message.
93
+ * @param {ReadonlyArray<{ label: string, maxBytes: number, included: boolean }>} blobs
94
+ * @param {number} [rows]
95
+ * @returns {number} The most rows a read of them holds: Infinity when it names none.
96
+ */
97
+ function checkBlobReads(name, caller, blobs, rows = 1) {
98
+ const included = blobs.filter((blob) => blob.included);
99
+ if (included.length > 0) {
100
+ throw new TypeError(
101
+ `${name}.${caller}() fields name ${labelsOf(included)}, a blob of an included table, of whose records an include ` +
102
+ "holds any number: read it through that table's own handle, one record's with get() or a page at a time with queryPages()."
103
+ );
104
+ }
105
+ const bytes = blobs.reduce((sum, { maxBytes }) => sum + maxBytes, 0);
106
+ const fit = bytes > 0 ? Math.max(1, Math.floor(BLOB_READ_BYTES / bytes)) : Infinity;
107
+ if (rows === Infinity && bytes > 0) {
108
+ throw new TypeError(
109
+ `${name}.${caller}() reads every matching row at once, so it reads no blob (${labelsOf(blobs)}): ` +
110
+ "read blobs a page at a time with queryPages(), whose pages hold at most 16 MiB of them, or one record's with get()."
111
+ );
112
+ }
113
+ if (rows > fit) {
114
+ throw new TypeError(
115
+ `${name}.${caller}() reads up to ${rows} records, and ${fit} of them already hold 16 MiB of ${labelsOf(blobs)}: ` +
116
+ `read at most ${fit} at a time, or read them a page at a time with queryPages().`
117
+ );
118
+ }
119
+ return fit;
120
+ }
121
+
122
+ /**
123
+ * Refuses blob fields in a JSON:API read, whose JSON holds no binary: a 400, since a client's sparse fieldset names them.
124
+ * @param {string} name The resource's name.
125
+ * @param {ReadonlyArray<{ label: string }>} blobs
126
+ */
127
+ function refuseBlobsInJson(name, blobs) {
128
+ if (blobs.length > 0) {
129
+ const fields = labelsOf(blobs);
130
+ throw new AppError(
131
+ 400,
132
+ `${name} answers JSON:API documents, whose JSON holds no binary, so their fields name no blob (${fields}). ` +
133
+ "A route of its own serves a blob: it reads it with get(id, { fields }) and answers it as the response body.",
134
+ { code: "JSON_API_FIELDSET_INVALID", messageCode: "resource.blobFields", messageParams: { fields } }
135
+ );
136
+ }
137
+ }
138
+
139
+ export { blobBuffers, blobFields, checkBlobReads, checkBlobValues, namedBlobs, refuseBlobsInJson };
@@ -0,0 +1,188 @@
1
+ import { RestApiRowLimitError } from "json-rest-api";
2
+ import { isJobContext } from "./contexts.js";
3
+ import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
4
+ import { RowLimitError } from "./errors.js";
5
+ import { matchesNoRow } from "./handleGuards.js";
6
+ import { handleRecords, readQueryParams } from "./handleRecords.js";
7
+ import { reportedPageRead } from "./manyRowChannel.js";
8
+ import { returnBadRequestWhenJsonRestFieldsetInvalid } from "./resourceHost.js";
9
+
10
+ /**
11
+ * A handle's reads of every row its filters match: queryAll, which answers them at once, and queryPages, which hands
12
+ * them over a page at a time. Both read in cursor pages of `settings.serverPageSize` rows and, in a request context,
13
+ * stop past `settings.requestRowLimit` rows; a system context, and the workspace and user contexts it derives, read
14
+ * without a limit. queryAll with `take` answers only the first `take` rows, and reads no further.
15
+ * @param {object} dependencies
16
+ * @param {{ knex: { instance: any } }} dependencies.api The table's json-rest-api, whose Knex sends its statements.
17
+ * @param {string} dependencies.name The resource's name.
18
+ * @param {{ name: string, schema: Record<string, any> }} dependencies.resource
19
+ * @param {() => any} dependencies.jsonRest The table's json-rest-api resource.
20
+ * @param {(params: { fields?: unknown }, kind: "list") => unknown} dependencies.readFields The fields a read names.
21
+ * @param {(options: object) => object} dependencies.contextOf The call's json-rest-api context, after its scope checks.
22
+ * @param {import("./types.js").HiddenFieldReads} dependencies.hiddenFields The hidden
23
+ * fields a read names, read after it.
24
+ * @param {{ requestRowLimit: number, serverPageSize: number }} dependencies.settings
25
+ * @param {(name: string) => (import("@jskit-ai/resource-core/shared/tableResource").TableResource | null)} dependencies.resourceNamed
26
+ * The application's table resources by name, which shape included records.
27
+ */
28
+ function createEveryRowReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, settings, resourceNamed }) {
29
+ // queryAll() and queryPages() read without a row limit in a system context and the workspace and user contexts it derives.
30
+ const rowLimitOf = (options) => (isJobContext(options.context) ? undefined : settings.requestRowLimit);
31
+
32
+ /**
33
+ * Every record the filters match, read in pages of pageLimits().server rows in
34
+ * id order (or `sort`). In a request it throws past the request row limit
35
+ * (pageLimits().requestRows); a system context, and the workspace and user
36
+ * contexts it derives, read without one, holding every row in memory:
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]
41
+ * @param {{ context?: object | null, trx?: object | null }} [options]
42
+ */
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
+ }
49
+ const context = contextOf(options);
50
+ const rowLimit = rowLimitOf(options);
51
+ checkBlobReads(name, "queryAll", namedBlobs(resource, params.fields, resourceNamed), Infinity);
52
+ const read = { ...params, fields: readFields(params, "list") };
53
+ const queryParams = readQueryParams(resource, read, { page: false, caller: "queryAll" });
54
+ const hidden = hiddenFields.named(params.fields, "plain");
55
+ try {
56
+ const payload = matchesNoRow(params.filters, jsonRest().vars.schemaInfo)
57
+ ? { data: [] }
58
+ : await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().queryAll(
59
+ {
60
+ queryParams,
61
+ pageSize: settings.serverPageSize,
62
+ ...(rowLimit === undefined ? {} : { rowLimit }),
63
+ transaction: options.trx || undefined,
64
+ format: "plain"
65
+ },
66
+ context
67
+ ));
68
+ return await hiddenFields.add(handleRecords(resource, payload.data, read, resourceNamed), hidden, options);
69
+ } catch (error) {
70
+ if (error instanceof RestApiRowLimitError && rowLimit !== undefined) {
71
+ throw new RowLimitError(name, rowLimit, error);
72
+ }
73
+ throw error;
74
+ }
75
+ }
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
+
126
+ /**
127
+ * The records queryAll() answers, handed over a page at a time, so work over
128
+ * many rows holds one page in memory: `for await (const records of
129
+ * queryPages(params, options))`. Each page is one statement of at most
130
+ * pageLimits().server rows (fewer when its fields name blobs, so the page holds
131
+ * at most 16 MiB of them), plus the statements that read its includes and the
132
+ * hidden fields it names, in id order (or `sort`). Each page continues after the
133
+ * last row of the page before, by its sort values: a write between pages that
134
+ * changes what the filters match, but not the sort fields' values, skips and
135
+ * repeats none of the rows still to come, while a row whose sort values move
136
+ * past the cursor is read again or not at all. In a request it throws
137
+ * RowLimitError instead of answering the page that takes it past the request
138
+ * row limit, as queryAll() does; background work reads without one.
139
+ * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} [params]
140
+ * @param {{ context?: object | null, trx?: object | null }} [options]
141
+ * @returns {AsyncGenerator<object[], void, undefined>}
142
+ */
143
+ async function* queryPages(params = {}, options = {}) {
144
+ const context = contextOf(options);
145
+ const rowLimit = rowLimitOf(options);
146
+ const read = { ...params, fields: readFields(params, "list") };
147
+ const queryParams = readQueryParams(resource, read, { page: false, caller: "queryPages" });
148
+ const hidden = hiddenFields.named(params.fields, "plain");
149
+ if (matchesNoRow(params.filters, jsonRest().vars.schemaInfo)) {
150
+ return;
151
+ }
152
+ const size = Math.min(settings.serverPageSize, checkBlobReads(name, "queryPages", namedBlobs(resource, params.fields, resourceNamed)));
153
+ const sort = queryParams.sort?.length ? queryParams.sort : ["id"];
154
+ let rows = 0;
155
+ let after;
156
+ // One page: its statement, its includes' and its hidden fields' read. Answers its records, or null when it has none.
157
+ const page = async () => {
158
+ const payload = await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().query(
159
+ {
160
+ queryParams: { ...queryParams, sort, page: after === undefined ? { size } : { size, after } },
161
+ pageSizeLimit: size,
162
+ transaction: options.trx || undefined,
163
+ format: "plain"
164
+ },
165
+ { ...context }
166
+ ));
167
+ rows += payload.data.length;
168
+ if (rowLimit !== undefined && rows > rowLimit) {
169
+ throw new RowLimitError(name, rowLimit, undefined, "queryPages");
170
+ }
171
+ const pagination = payload.meta?.pagination;
172
+ after = pagination?.hasMore === true ? pagination.cursor?.next ?? undefined : undefined;
173
+ return payload.data.length > 0 ? hiddenFields.add(handleRecords(resource, payload.data, read, resourceNamed), hidden, options) : null;
174
+ };
175
+ let records = await page();
176
+ while (records !== null) {
177
+ yield records;
178
+ records = after === undefined ? null : await reportedPageRead(api.knex.instance, name, page);
179
+ }
180
+ }
181
+
182
+ return Object.freeze({
183
+ queryAll,
184
+ queryPages
185
+ });
186
+ }
187
+
188
+ export { createEveryRowReads };