@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.
- package/CHANGELOG.md +14 -0
- package/locales/en.json +3 -1
- package/package.json +6 -6
- package/src/server/errors.js +29 -5
- package/src/server/filterJoinSources.js +177 -0
- package/src/server/handleBlobs.js +139 -0
- package/src/server/handleEveryRow.js +188 -0
- package/src/server/handleHidden.js +46 -4
- package/src/server/handleLocks.js +173 -19
- package/src/server/handleRecords.js +16 -3
- package/src/server/index.js +1 -0
- package/src/server/manyRowChannel.js +44 -0
- package/src/server/resourceHandle.js +64 -52
- package/src/server/resourceHost.js +5 -5
- package/src/server/resourceRuntime.js +67 -20
- package/src/server/types.js +5 -0
- package/src/test/expectFlatQueries.js +23 -11
- package/src/test/index.js +2 -2
- package/test/blobFields.mysql.test.js +8 -0
- package/test/blobFields.test.js +8 -0
- package/test/crossTableFilters.mysql.test.js +8 -0
- package/test/crossTableFilters.test.js +8 -0
- package/test/filterJoinSources.mysql.test.js +8 -0
- package/test/filterJoinSources.test.js +8 -0
- package/test/hiddenFields.test.js +41 -0
- package/test/lockIncludes.mysql.test.js +8 -0
- package/test/lockIncludes.test.js +8 -0
- package/test/lockedReads.mysql.test.js +156 -0
- package/test/pagedReads.mysql.test.js +8 -0
- package/test/pagedReads.test.js +8 -0
- package/test/reportsAcrossOwners.mysql.test.js +8 -0
- package/test/reportsAcrossOwners.test.js +8 -0
- package/test/resourceRuntime.test.js +55 -2
- package/test/support/blobFieldsCases.js +226 -0
- package/test/support/crossTableFiltersCases.js +180 -0
- package/test/support/filterJoinSourcesCases.js +256 -0
- package/test/support/lockIncludesCases.js +158 -0
- package/test/support/mysqlDatabase.js +35 -0
- package/test/support/pagedReadsCases.js +168 -0
- package/test/support/reportsAcrossOwnersCases.js +201 -0
- package/test/testHelpers.test.js +128 -3
|
@@ -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
|
|
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
|
-
|
|
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,5 +1,8 @@
|
|
|
1
|
+
import { detectDialectFromClient } from "@jskit-ai/database-runtime/shared";
|
|
2
|
+
import { checkBlobReads, namedBlobs } from "./handleBlobs.js";
|
|
1
3
|
import { missingOf, requireDefinedFilters } from "./handleGuards.js";
|
|
2
|
-
import { handleRecords, sparseFieldset, textList } from "./handleRecords.js";
|
|
4
|
+
import { defaultFieldList, handleRecords, includedRelationships, sparseFieldset, textList } from "./handleRecords.js";
|
|
5
|
+
import { resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
|
|
3
6
|
|
|
4
7
|
// The row lock a locking read takes. "update" (the default) is FOR UPDATE. "noKeyUpdate" is PostgreSQL's FOR NO KEY
|
|
5
8
|
// UPDATE, which still keeps every other lock and write of the row out but lets other transactions insert rows that
|
|
@@ -24,29 +27,173 @@ function lockModeOf(name, caller, lockMode) {
|
|
|
24
27
|
return { lockMode };
|
|
25
28
|
}
|
|
26
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
|
+
|
|
33
|
+
/**
|
|
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
|
|
39
|
+
* @param {string} caller The handle method, for the message.
|
|
40
|
+
* @param {unknown} include
|
|
41
|
+
*/
|
|
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
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
27
63
|
/**
|
|
28
64
|
* A handle's locking reads: lock, lockMany, lockWhere and claim. Each needs the
|
|
29
65
|
* caller's transaction (`options.trx`), locks only rows the caller may see, and
|
|
30
66
|
* reads the fields `options.fields` names, or every field a one-record read
|
|
31
67
|
* answers, so a belongs-to field left out costs no check that its related
|
|
32
|
-
* 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).
|
|
33
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.
|
|
34
73
|
* @param {string} dependencies.name The resource's name.
|
|
35
|
-
* @param {{ name: string, schema: Record<string, any> }} dependencies.resource
|
|
36
|
-
* @param {() => Record<string,
|
|
37
|
-
* 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.
|
|
38
76
|
* @param {(params: { fields?: unknown }, kind: "view") => unknown} dependencies.readFields The fields a read names.
|
|
39
77
|
* @param {(options: object) => object} dependencies.contextOf The call's json-rest-api context, after its scope checks.
|
|
40
|
-
* @param {
|
|
78
|
+
* @param {import("./types.js").HiddenFieldReads} dependencies.hiddenFields The hidden
|
|
41
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.
|
|
42
84
|
*/
|
|
43
|
-
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
|
+
|
|
44
186
|
// A locking read (json-rest-api's lockByIds, lockWhere or claim) of the fields options.fields names, as records, in the
|
|
45
|
-
// lock mode options.lockMode names. `caller` is the handle method,
|
|
46
|
-
|
|
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);
|
|
191
|
+
// lock() and lockMany() hold their ids' blobs, lockWhere() and claim() any number of rows, so they name none.
|
|
192
|
+
checkBlobReads(name, caller, namedBlobs(resource, options.fields, () => null), method === "lockByIds" ? read.ids.length : Infinity);
|
|
47
193
|
const mode = lockModeOf(name, caller, options.lockMode);
|
|
48
194
|
const hidden = hiddenFields.named(options.fields, "plain");
|
|
49
|
-
const
|
|
195
|
+
const named = readFields({ fields: options.fields }, "view");
|
|
196
|
+
const fields = includes.length > 0 ? fieldsBeside(named, includes) : named;
|
|
50
197
|
const { data } = await jsonRest()[method]({
|
|
51
198
|
...read,
|
|
52
199
|
...mode,
|
|
@@ -54,7 +201,8 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
|
|
|
54
201
|
format: "plain",
|
|
55
202
|
...(fields ? { queryParams: { fields: sparseFieldset(resource, fields) } } : {})
|
|
56
203
|
}, contextOf(options));
|
|
57
|
-
|
|
204
|
+
const records = await hiddenFields.add(handleRecords(resource, data, { fields }), hidden, options);
|
|
205
|
+
return includes.length > 0 ? withLockedIncludes(records, includes, options) : records;
|
|
58
206
|
}
|
|
59
207
|
|
|
60
208
|
/**
|
|
@@ -63,8 +211,10 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
|
|
|
63
211
|
* `fields` names the fields the lock reads, so a belongs-to field left out costs no check that its related
|
|
64
212
|
* record is visible; without it every field is read. `lockMode: "noKeyUpdate"` takes PostgreSQL's FOR NO KEY
|
|
65
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).
|
|
66
216
|
* @param {unknown[]} ids
|
|
67
|
-
* @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
|
|
68
218
|
*/
|
|
69
219
|
async function lockMany(ids, options) {
|
|
70
220
|
return lockRead("lockMany", "lockByIds", { ids, ...(options.missing ? { missing: options.missing } : {}) }, options);
|
|
@@ -81,7 +231,7 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
|
|
|
81
231
|
* json-rest-api's not-found error, or answers null with `missing: "skip"`.
|
|
82
232
|
* `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
|
|
83
233
|
* @param {unknown} id
|
|
84
|
-
* @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
|
|
85
235
|
*/
|
|
86
236
|
async function lock(id, options) {
|
|
87
237
|
missingOf(name, "lock", options.missing);
|
|
@@ -98,7 +248,7 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
|
|
|
98
248
|
* with the ownership columns (no owners: with a filtered column), or it refuses.
|
|
99
249
|
* `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
|
|
100
250
|
* @param {object} filters
|
|
101
|
-
* @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
|
|
102
252
|
*/
|
|
103
253
|
async function lockWhere(filters, options) {
|
|
104
254
|
requireDefinedFilters(name, "lockWhere", filters);
|
|
@@ -109,19 +259,23 @@ function createLockReads({ name, resource, jsonRest, readFields, contextOf, hidd
|
|
|
109
259
|
* Takes up to `take` (default 1) of the rows the filters select that no
|
|
110
260
|
* other transaction holds, in `sort` order, locked until the transaction ends.
|
|
111
261
|
* `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
|
|
112
|
-
*
|
|
113
|
-
* @param {{
|
|
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
|
|
114
265
|
*/
|
|
115
|
-
async function claim({ filters, sort, take } = {}, options, ...rest) {
|
|
266
|
+
async function claim({ filters, sort, take, include } = {}, options, ...rest) {
|
|
116
267
|
if (rest.length > 0) {
|
|
117
|
-
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.`);
|
|
118
272
|
}
|
|
119
273
|
requireDefinedFilters(name, "claim", filters);
|
|
120
274
|
return lockRead("claim", "claim", {
|
|
121
275
|
filters,
|
|
122
276
|
...(take === undefined ? {} : { limit: take }),
|
|
123
277
|
...(sort === undefined ? {} : { sort: textList(sort) })
|
|
124
|
-
}, options);
|
|
278
|
+
}, options, include ?? options.include);
|
|
125
279
|
}
|
|
126
280
|
|
|
127
281
|
return Object.freeze({
|
|
@@ -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
|
|
|
@@ -67,13 +68,23 @@ function requestedFields(params, quiet, schemaInfo) {
|
|
|
67
68
|
return params.fields;
|
|
68
69
|
}
|
|
69
70
|
const left = new Set(skipped.flatMap(({ fieldName, relationshipName }) => [fieldName, relationshipName]));
|
|
70
|
-
|
|
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 }) {
|
|
71
82
|
return [
|
|
72
83
|
...Object.entries(outputFields)
|
|
73
84
|
.filter(([field, definition]) => field !== "id" && field !== idProperty && !definition?.hidden && !definition?.normallyHidden)
|
|
74
85
|
.map(([field]) => field),
|
|
75
86
|
...Object.keys(outputRelationships)
|
|
76
|
-
]
|
|
87
|
+
];
|
|
77
88
|
}
|
|
78
89
|
|
|
79
90
|
/**
|
|
@@ -269,7 +280,7 @@ function inputData(resource, attributes, stamp, context) {
|
|
|
269
280
|
if (!isRecord(attributes)) {
|
|
270
281
|
throw new TypeError(`${resource.name} writes take attributes as an object.`);
|
|
271
282
|
}
|
|
272
|
-
const data = stampedAttributes(resource, attributes, stamp, context);
|
|
283
|
+
const data = blobBuffers(resource, stampedAttributes(resource, attributes, stamp, context));
|
|
273
284
|
for (const [fieldName, definition] of Object.entries(resource.schema)) {
|
|
274
285
|
if (!definition?.belongsTo || !Object.hasOwn(data, fieldName)) {
|
|
275
286
|
continue;
|
|
@@ -454,6 +465,8 @@ function patchAnswer(id, record, returning) {
|
|
|
454
465
|
|
|
455
466
|
export {
|
|
456
467
|
aggregateMeasures,
|
|
468
|
+
defaultFieldList,
|
|
469
|
+
includedRelationships,
|
|
457
470
|
MANY_RETURNING,
|
|
458
471
|
SINGLE_RETURNING,
|
|
459
472
|
handleRecords,
|
package/src/server/index.js
CHANGED
|
@@ -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 };
|