@jskit-ai/resource-runtime 0.2.16 → 0.2.18

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,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - **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
+ - 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
+ - **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.
8
+ - **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.
9
+ - `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`.
10
+ - 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.
11
+ - **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.
12
+ - 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.
13
+ - **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.
14
+ - `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
15
  - 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
16
  - 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
17
  - 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.16",
3
+ "version": "0.2.18",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -15,8 +15,8 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.206",
19
- "@jskit-ai/resource-crud-core": "0.1.206",
18
+ "@jskit-ai/resource-core": "0.1.208",
19
+ "@jskit-ai/resource-crud-core": "0.1.208",
20
20
  "json-rest-api": "3.1.1"
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.",
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.264",
68
- "@jskit-ai/kernel": "0.2.15"
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,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,132 @@
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.
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.
38
+ * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} [params]
39
+ * @param {{ context?: object | null, trx?: object | null }} [options]
40
+ */
41
+ async function queryAll(params = {}, options = {}) {
42
+ const context = contextOf(options);
43
+ const rowLimit = rowLimitOf(options);
44
+ checkBlobReads(name, "queryAll", namedBlobs(resource, params.fields, resourceNamed), Infinity);
45
+ const read = { ...params, fields: readFields(params, "list") };
46
+ const queryParams = readQueryParams(resource, read, { page: false, caller: "queryAll" });
47
+ const hidden = hiddenFields.named(params.fields, "plain");
48
+ try {
49
+ const payload = matchesNoRow(params.filters, jsonRest().vars.schemaInfo)
50
+ ? { data: [] }
51
+ : await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().queryAll(
52
+ {
53
+ queryParams,
54
+ pageSize: settings.serverPageSize,
55
+ ...(rowLimit === undefined ? {} : { rowLimit }),
56
+ transaction: options.trx || undefined,
57
+ format: "plain"
58
+ },
59
+ context
60
+ ));
61
+ return await hiddenFields.add(handleRecords(resource, payload.data, read, resourceNamed), hidden, options);
62
+ } catch (error) {
63
+ if (error instanceof RestApiRowLimitError && rowLimit !== undefined) {
64
+ throw new RowLimitError(name, rowLimit, error);
65
+ }
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * The records queryAll() answers, handed over a page at a time, so work over
72
+ * many rows holds one page in memory: `for await (const records of
73
+ * queryPages(params, options))`. Each page is one statement of at most
74
+ * pageLimits().server rows (fewer when its fields name blobs, so the page holds
75
+ * at most 16 MiB of them), plus the statements that read its includes and the
76
+ * hidden fields it names, in id order (or `sort`). Each page continues after the
77
+ * last row of the page before, by its sort values: a write between pages that
78
+ * changes what the filters match, but not the sort fields' values, skips and
79
+ * repeats none of the rows still to come, while a row whose sort values move
80
+ * past the cursor is read again or not at all. In a request it throws
81
+ * RowLimitError instead of answering the page that takes it past the request
82
+ * row limit, as queryAll() does; background work reads without one.
83
+ * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} [params]
84
+ * @param {{ context?: object | null, trx?: object | null }} [options]
85
+ * @returns {AsyncGenerator<object[], void, undefined>}
86
+ */
87
+ async function* queryPages(params = {}, options = {}) {
88
+ const context = contextOf(options);
89
+ const rowLimit = rowLimitOf(options);
90
+ const read = { ...params, fields: readFields(params, "list") };
91
+ const queryParams = readQueryParams(resource, read, { page: false, caller: "queryPages" });
92
+ const hidden = hiddenFields.named(params.fields, "plain");
93
+ if (matchesNoRow(params.filters, jsonRest().vars.schemaInfo)) {
94
+ return;
95
+ }
96
+ const size = Math.min(settings.serverPageSize, checkBlobReads(name, "queryPages", namedBlobs(resource, params.fields, resourceNamed)));
97
+ const sort = queryParams.sort?.length ? queryParams.sort : ["id"];
98
+ let rows = 0;
99
+ let after;
100
+ // One page: its statement, its includes' and its hidden fields' read. Answers its records, or null when it has none.
101
+ const page = async () => {
102
+ const payload = await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().query(
103
+ {
104
+ queryParams: { ...queryParams, sort, page: after === undefined ? { size } : { size, after } },
105
+ pageSizeLimit: size,
106
+ transaction: options.trx || undefined,
107
+ format: "plain"
108
+ },
109
+ { ...context }
110
+ ));
111
+ rows += payload.data.length;
112
+ if (rowLimit !== undefined && rows > rowLimit) {
113
+ throw new RowLimitError(name, rowLimit, undefined, "queryPages");
114
+ }
115
+ const pagination = payload.meta?.pagination;
116
+ after = pagination?.hasMore === true ? pagination.cursor?.next ?? undefined : undefined;
117
+ return payload.data.length > 0 ? hiddenFields.add(handleRecords(resource, payload.data, read, resourceNamed), hidden, options) : null;
118
+ };
119
+ let records = await page();
120
+ while (records !== null) {
121
+ yield records;
122
+ records = after === undefined ? null : await reportedPageRead(api.knex.instance, name, page);
123
+ }
124
+ }
125
+
126
+ return Object.freeze({
127
+ queryAll,
128
+ queryPages
129
+ });
130
+ }
131
+
132
+ export { createEveryRowReads };
@@ -148,11 +148,34 @@ function markHandleFunctions({ scopedQuery, withTransaction, lockOrCreate }) {
148
148
  HANDLE_WORK_RUNNERS.add(lockOrCreate);
149
149
  }
150
150
 
151
+ /**
152
+ * A call refused before it runs: a rejected promise that is pages too, since a method of any name may answer pages
153
+ * (queryPages(), or an owner's method answering them), so `await` and `for await` both throw `error`. Its rejection
154
+ * counts as handled, so a caller that only iterates leaves none unhandled.
155
+ * @param {Error} error
156
+ * @returns {Promise<never> & AsyncIterable<never>}
157
+ */
158
+ function refusedCall(error) {
159
+ const refused = Promise.reject(error);
160
+ refused.catch(() => {});
161
+ return Object.assign(refused, { [Symbol.asyncIterator]: () => Object.freeze({ next: () => Promise.reject(error) }) });
162
+ }
163
+
164
+ /**
165
+ * Whether a value is an async generator's pages, such as queryPages() answers, whose pages withoutHiddenFields strips
166
+ * one at a time. Other async iterables (a Node stream) pass as they are, as other instances do.
167
+ * @param {unknown} value
168
+ */
169
+ function isAsyncGenerator(value) {
170
+ return Object.prototype.toString.call(value) === "[object AsyncGenerator]";
171
+ }
172
+
151
173
  /**
152
174
  * A handle's joinSource(): the table as a join source for another owner's report, which joins it in its own
153
175
  * statement. It answers `{ query, column }`: the rows scopedQuery() gives under `alias` (the caller's ownership, the
154
176
  * row policy and `filters` applied) with the stored columns a read answers and the ownership fields, hidden or not,
155
- * since a report joins on them and they name the caller's own scope; never another hidden column. `column(field)`
177
+ * since a report joins on them and they name the caller's own scope; never another hidden column, and never a blob,
178
+ * so a report's `select("alias.*")` holds no unbounded bytes. `column(field)`
156
179
  * names each under that alias. A CRUD feature's repository answers it to any feature, where it
157
180
  * refuses scopedQuery(). The builder comes wrapped, since a builder is thenable.
158
181
  * @param {object} dependencies
@@ -179,7 +202,7 @@ function createJoinSource({ api, resource, jsonRest, scopedQuery, column }) {
179
202
  const carried = Object.keys(schemaStructure).filter((field) => {
180
203
  const definition = schemaStructure[field];
181
204
  return field !== "id" && (definition.hidden !== true || joinKeys.has(field)) &&
182
- definition.virtual !== true && !definition.belongsToPolymorphic;
205
+ definition.virtual !== true && !definition.belongsToPolymorphic && resource.schema[field]?.type !== "blob";
183
206
  });
184
207
  // The scoped rows' visible columns and ownership fields, as a derived table under the alias: nothing a caller adds
185
208
  // reaches the others.
@@ -191,6 +214,9 @@ function createJoinSource({ api, resource, jsonRest, scopedQuery, column }) {
191
214
  return Object.freeze({
192
215
  query: source,
193
216
  column(field) {
217
+ if (resource.schema[field]?.type === "blob") {
218
+ throw new TypeError(`${name}.joinSource() carries no blob, so it has no column for "${field}": a report reads no blob, and get() reads one record's.`);
219
+ }
194
220
  if (resource.schema[field]?.hidden === true && !joinKeys.has(field)) {
195
221
  throw new TypeError(`${name}.joinSource() carries no hidden field but its ownership fields, so it has no column for "${field}".`);
196
222
  }
@@ -363,6 +389,18 @@ function guardedRepository(repository, resource, hidden, guarded) {
363
389
  return Object.freeze(Object.create(Object.getPrototypeOf(repository), descriptors));
364
390
  }
365
391
 
392
+ /**
393
+ * Each page of an async iterable, such as queryPages()'s, without its hidden fields.
394
+ * @param {AsyncIterable<unknown>} pages
395
+ * @param {Set<string>} hidden
396
+ * @param {string} label
397
+ */
398
+ async function* withoutHiddenPages(pages, hidden, label) {
399
+ for await (const page of pages) {
400
+ yield withoutHiddenValues(page, hidden, label);
401
+ }
402
+ }
403
+
366
404
  /**
367
405
  * @param {object} repository
368
406
  * @param {string} key
@@ -389,10 +427,11 @@ function guardedFunction(repository, key, call, resource, hidden) {
389
427
  const named = [...new Set(args.flatMap((arg) => (isRecord(arg) ? fieldNames(arg.fields) : [])))]
390
428
  .filter((field) => hidden.has(field));
391
429
  if (named.length > 0) {
392
- return Promise.reject(new TypeError(
430
+ const refusal = new TypeError(
393
431
  `${label} fields names the hidden field ${named.map((field) => `"${field}"`).join(", ")}, ` +
394
432
  "which only the table's owner, or a system context, reads."
395
- ));
433
+ );
434
+ return refusedCall(refusal);
396
435
  }
397
436
  const answer = call.apply(repository, args);
398
437
  // A runner's answer is the caller's own work: it passes as it is.
@@ -404,6 +443,9 @@ function guardedFunction(repository, key, call, resource, hidden) {
404
443
  if (isKnexValue(answer)) {
405
444
  return withoutFullBuilder(answer, label);
406
445
  }
446
+ if (isAsyncGenerator(answer)) {
447
+ return withoutHiddenPages(answer, hidden, label);
448
+ }
407
449
  // readable-check: allow method-probe - data: a repository's method may answer at once or with a promise
408
450
  return typeof answer?.then === "function"
409
451
  ? answer.then((value) => withoutHiddenValues(value, hidden, label))
@@ -1,3 +1,4 @@
1
+ import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
1
2
  import { missingOf, requireDefinedFilters } from "./handleGuards.js";
2
3
  import { handleRecords, sparseFieldset, textList } from "./handleRecords.js";
3
4
 
@@ -24,6 +25,28 @@ function lockModeOf(name, caller, lockMode) {
24
25
  return { lockMode };
25
26
  }
26
27
 
28
+ /**
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
+ * @param {string} caller The handle method, for the message.
35
+ * @param {unknown} include
36
+ */
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
+ );
48
+ }
49
+
27
50
  /**
28
51
  * A handle's locking reads: lock, lockMany, lockWhere and claim. Each needs the
29
52
  * caller's transaction (`options.trx`), locks only rows the caller may see, and
@@ -37,13 +60,16 @@ function lockModeOf(name, caller, lockMode) {
37
60
  * The table's json-rest-api resource.
38
61
  * @param {(params: { fields?: unknown }, kind: "view") => unknown} dependencies.readFields The fields a read names.
39
62
  * @param {(options: object) => object} dependencies.contextOf The call's json-rest-api context, after its scope checks.
40
- * @param {ReturnType<typeof import("./handleHidden.js").createHiddenFieldReads>} dependencies.hiddenFields The hidden
63
+ * @param {import("./types.js").HiddenFieldReads} dependencies.hiddenFields The hidden
41
64
  * fields `options.fields` names, read after the lock.
42
65
  */
43
66
  function createLockReads({ name, resource, jsonRest, readFields, contextOf, hiddenFields }) {
44
67
  // A locking read (json-rest-api's lockByIds, lockWhere or claim) of the fields options.fields names, as records, in the
45
68
  // lock mode options.lockMode names. `caller` is the handle method, for the messages.
46
69
  async function lockRead(caller, method, read, options) {
70
+ refuseInclude(name, caller, options.include);
71
+ // lock() and lockMany() hold their ids' blobs, lockWhere() and claim() any number of rows, so they name none.
72
+ checkBlobReads(name, caller, namedBlobs(resource, options.fields, () => null), method === "lockByIds" ? read.ids.length : Infinity);
47
73
  const mode = lockModeOf(name, caller, options.lockMode);
48
74
  const hidden = hiddenFields.named(options.fields, "plain");
49
75
  const fields = readFields({ fields: options.fields }, "view");
@@ -112,10 +138,11 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
112
138
  * @param {{ filters: object, sort?: string | string[], take?: number }} params
113
139
  * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" }} options
114
140
  */
115
- async function claim({ filters, sort, take } = {}, options, ...rest) {
141
+ async function claim({ filters, sort, take, include } = {}, options, ...rest) {
116
142
  if (rest.length > 0) {
117
143
  throw new TypeError(`${name}.claim() takes ({ filters, sort, take }, options).`);
118
144
  }
145
+ refuseInclude(name, "claim", include);
119
146
  requireDefinedFilters(name, "claim", filters);
120
147
  return lockRead("claim", "claim", {
121
148
  filters,
@@ -1,6 +1,7 @@
1
1
  import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
2
2
  import { RECORD_TIMESTAMPS, storedTimestamps } from "@jskit-ai/resource-core/shared/tableResource";
3
3
  import { isJobContext } from "./contexts.js";
4
+ import { blobBuffers } from "./handleBlobs.js";
4
5
  import { requireDefinedFilters } from "./handleGuards.js";
5
6
  import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
6
7
 
@@ -269,7 +270,7 @@ function inputData(resource, attributes, stamp, context) {
269
270
  if (!isRecord(attributes)) {
270
271
  throw new TypeError(`${resource.name} writes take attributes as an object.`);
271
272
  }
272
- const data = stampedAttributes(resource, attributes, stamp, context);
273
+ const data = blobBuffers(resource, stampedAttributes(resource, attributes, stamp, context));
273
274
  for (const [fieldName, definition] of Object.entries(resource.schema)) {
274
275
  if (!definition?.belongsTo || !Object.hasOwn(data, fieldName)) {
275
276
  continue;
@@ -8,6 +8,7 @@ export { withoutHiddenFields } from "./handleHidden.js";
8
8
  export { passedOn } from "./handleGuards.js";
9
9
  export {
10
10
  DuplicateOwnerError,
11
+ GroupLimitError,
11
12
  MissingScopeError,
12
13
  PageSizeError,
13
14
  RowLimitError,
@@ -0,0 +1,44 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import diagnosticsChannel from "node:diagnostics_channel";
3
+
4
+ // Each many-row call publishes { resource, operation, rows, chunkSize } here while something subscribes, and each page
5
+ // of queryPages() after its first publishes { resource, operation: "queryPages", statements }, so a flat-query test
6
+ // can tell the statements chunking and paging add from statements that grow with the rows.
7
+ const MANY_ROW_CHANNEL = "jskit:resources:many-row";
8
+ // The page read open in the current async context, whose statements it counts.
9
+ const openPageRead = new AsyncLocalStorage();
10
+
11
+ /**
12
+ * Runs `read`, a page of queryPages() after its first, and, while a flat-query test listens, publishes how many
13
+ * statements it sent: the page's own, its included records' and its hidden fields', not the caller's work between
14
+ * pages.
15
+ * @template T
16
+ * @param {{ on: Function, off: Function }} knex The handle's Knex, which reports its transactions' statements too.
17
+ * @param {string} resource
18
+ * @param {() => Promise<T>} read
19
+ * @returns {Promise<T>}
20
+ */
21
+ async function reportedPageRead(knex, resource, read) {
22
+ const channel = diagnosticsChannel.channel(MANY_ROW_CHANNEL);
23
+ if (!channel.hasSubscribers) {
24
+ return read();
25
+ }
26
+ const page = Symbol("page");
27
+ let statements = 0;
28
+ const count = () => {
29
+ if (openPageRead.getStore() === page) statements += 1;
30
+ };
31
+ knex.on("query", count);
32
+ try {
33
+ return await openPageRead.run(page, read);
34
+ } finally {
35
+ knex.off("query", count);
36
+ channel.publish(Object.freeze({
37
+ resource,
38
+ operation: "queryPages",
39
+ statements
40
+ }));
41
+ }
42
+ }
43
+
44
+ export { MANY_ROW_CHANNEL, reportedPageRead };