@jskit-ai/resource-runtime 0.2.17 → 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.
@@ -1,14 +1,16 @@
1
1
  import diagnosticsChannel from "node:diagnostics_channel";
2
- import { RestApiRowLimitError } from "json-rest-api";
3
2
  import { retryDeadlocks } from "@jskit-ai/database-runtime/shared";
4
3
  import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
5
4
  import { readChangeHorizon } from "./changeHorizon.js";
6
- import { createJsonRestContext, isJobContext } from "./contexts.js";
5
+ import { createJsonRestContext } from "./contexts.js";
6
+ import { checkBlobReads, checkBlobValues, namedBlobs, refuseBlobsInJson } from "./handleBlobs.js";
7
+ import { createEveryRowReads } from "./handleEveryRow.js";
7
8
  import { createHiddenFieldReads, createJoinSource, markHandleFunctions } from "./handleHidden.js";
8
9
  import { createLockReads, lockModeOf } from "./handleLocks.js";
10
+ import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
9
11
  import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
10
12
  import { valueOnlyRaw } from "./rawExpression.js";
11
- import { PageSizeError, RowLimitError, StaleRecordError, UnpagedQueryError } from "./errors.js";
13
+ import { GroupLimitError, PageSizeError, StaleRecordError, UnpagedQueryError } from "./errors.js";
12
14
  import {
13
15
  formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners, requirePatchConditions,
14
16
  requireReadParams, requireUpsertRows, whereSelection
@@ -36,11 +38,10 @@ import {
36
38
  returnNullWhenJsonRestResourceMissing
37
39
  } from "./resourceHost.js";
38
40
 
39
- // Each many-row call publishes { resource, operation, rows, chunkSize } here while something
40
- // subscribes, so a flat-query test can tell the statements chunking adds from statements that
41
- // grow with the rows.
42
- const MANY_ROW_CHANNEL = "jskit:resources:many-row";
43
41
  const DEFAULT_CHUNK_SIZE = 500;
42
+ // The fewest rows a many-row call's chunk holds. A smaller chunk sends a statement every few rows, as a loop of
43
+ // single-row writes does, and a flat-query check allows a many-row call's later chunks.
44
+ const MIN_CHUNK_SIZE = 100;
44
45
  // Why a many-row patch refuses lockVersion: one version does not hold for many records.
45
46
  const ONE_VERSION = "To change only the rows still at one version, give onlyIf the lock version field and that version; " +
46
47
  "to compare each record's own version, patch() it with its lockVersion.";
@@ -213,11 +214,15 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
213
214
  });
214
215
  }
215
216
 
216
- /** The largest page query() serves, and the page size of every-row reads. */
217
+ /**
218
+ * The largest page query() serves and the most groups one aggregate() answers (`request`), the page size of every-row
219
+ * reads (`server`), and the most rows queryAll() and queryPages() read in a request context (`requestRows`).
220
+ */
217
221
  function pageLimits() {
218
222
  return Object.freeze({
219
223
  request: jsonRest().vars.queryMaxLimit,
220
- server: settings.serverPageSize
224
+ server: settings.serverPageSize,
225
+ requestRows: settings.requestRowLimit
221
226
  });
222
227
  }
223
228
 
@@ -235,6 +240,10 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
235
240
  const read = { ...params, fields: readFields(params, "list") };
236
241
  const queryParams = readQueryParams(resource, read, { page: true, caller: "query" });
237
242
  const hidden = hiddenFields.named(params.fields, format);
243
+ const blobs = namedBlobs(resource, params.fields, resourceNamed);
244
+ if (format === "jsonapi") {
245
+ refuseBlobsInJson(name, blobs);
246
+ }
238
247
  const size = params.page?.size;
239
248
  if (size == null && format !== "jsonapi") {
240
249
  throw new UnpagedQueryError(name);
@@ -242,6 +251,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
242
251
  if (size != null && Number(size) > pageLimits().request) {
243
252
  throw new PageSizeError(name, size, pageLimits().request);
244
253
  }
254
+ checkBlobReads(name, "query", blobs, Number(size));
245
255
  const context = contextOf(options);
246
256
  const payload = format !== "jsonapi" && matchesNoRow(params.filters, jsonRest().vars.schemaInfo)
247
257
  ? { data: [] }
@@ -267,41 +277,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
267
277
  });
268
278
  }
269
279
 
270
- /**
271
- * Every record the filters match, read in pages of pageLimits().server rows in
272
- * id order (or `sort`). In a request it throws past the request row limit;
273
- * a system context, and the workspace and user contexts it derives, read
274
- * without one.
275
- * @param {{ filters?: object, sort?: string | string[], include?: string | string[], fields?: string[] | object }} [params]
276
- * @param {{ context?: object | null, trx?: object | null }} [options]
277
- */
278
- async function queryAll(params = {}, options = {}) {
279
- const context = contextOf(options);
280
- const rowLimit = isJobContext(options.context) ? undefined : settings.requestRowLimit;
281
- const read = { ...params, fields: readFields(params, "list") };
282
- const queryParams = readQueryParams(resource, read, { page: false, caller: "queryAll" });
283
- const hidden = hiddenFields.named(params.fields, "plain");
284
- try {
285
- const payload = matchesNoRow(params.filters, jsonRest().vars.schemaInfo)
286
- ? { data: [] }
287
- : await returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().queryAll(
288
- {
289
- queryParams,
290
- pageSize: settings.serverPageSize,
291
- ...(rowLimit === undefined ? {} : { rowLimit }),
292
- transaction: options.trx || undefined,
293
- format: "plain"
294
- },
295
- context
296
- ));
297
- return await hiddenFields.add(handleRecords(resource, payload.data, read, resourceNamed), hidden, options);
298
- } catch (error) {
299
- if (error instanceof RestApiRowLimitError && rowLimit !== undefined) {
300
- throw new RowLimitError(name, rowLimit, error);
301
- }
302
- throw error;
303
- }
304
- }
280
+ // queryAll and queryPages (see handleEveryRow.js).
281
+ const { queryAll, queryPages } = createEveryRowReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, settings, resourceNamed });
305
282
 
306
283
  /**
307
284
  * One record. A missing or hidden one throws json-rest-api's not-found error
@@ -315,6 +292,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
315
292
  const format = formatOf(name, options);
316
293
  const named = { ...params, fields: readFields(params, "view") };
317
294
  const hidden = hiddenFields.named(params.fields, format);
295
+ const blobs = namedBlobs(resource, params.fields, resourceNamed);
296
+ if (format === "jsonapi") {
297
+ refuseBlobsInJson(name, blobs);
298
+ }
299
+ checkBlobReads(name, "get", blobs);
318
300
  const read = () => returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().get(
319
301
  {
320
302
  id,
@@ -331,15 +313,24 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
331
313
  /**
332
314
  * Totals: `measures` ({ name: { count | countDistinct | sum | avg | min | max: field, where? } })
333
315
  * over the filtered rows, grouped by `groupBy` fields or date buckets. Answers the rows.
334
- * @param {{ measures: object, groupBy?: Array<string | object>, filters?: object, sort?: string[], page?: object }} spec
316
+ * One statement answers at most pageLimits().request groups: a grouped
317
+ * aggregate without `page` answers every group or, when there are more, throws
318
+ * GroupLimitError rather than answer part of them. `page: { size, number }`
319
+ * (number from 1) answers one page of groups; a page shorter than `size` is the last.
320
+ * @param {{ measures: object, groupBy?: Array<string | object>, filters?: object, sort?: string[], page?: { size: number, number?: number } }} spec
335
321
  * @param {{ context?: object | null, trx?: object | null }} [options]
336
322
  */
337
323
  async function aggregate({ measures, groupBy, filters, sort, page }, options = {}) {
338
324
  requireDefinedFilters(name, "aggregate", filters);
325
+ if (page !== undefined && page?.size == null) {
326
+ throw new TypeError(`${name}.aggregate() page needs size (at most pageLimits().request) and takes number from 1: page: { size, number }.`);
327
+ }
339
328
  const context = contextOf(options);
340
329
  if (matchesNoRow(filters, jsonRest().vars.schemaInfo)) {
341
330
  return noRowsAggregate(measures, groupBy);
342
331
  }
332
+ // json-rest-api pages grouped rows at its default page size when none is named, and says so only in meta.
333
+ const groupLimit = page === undefined && Array.isArray(groupBy) && groupBy.length > 0 ? pageLimits().request : undefined;
343
334
  const result = await jsonRest().aggregate(
344
335
  {
345
336
  measures: aggregateMeasures(measures),
@@ -347,12 +338,16 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
347
338
  queryParams: {
348
339
  ...(filters === undefined ? {} : { filters }),
349
340
  ...(sort === undefined ? {} : { sort: textList(sort) }),
350
- ...(page === undefined ? {} : { page })
341
+ ...(page === undefined ? {} : { page }),
342
+ ...(groupLimit === undefined ? {} : { page: { size: groupLimit } })
351
343
  },
352
344
  transaction: options.trx || undefined
353
345
  },
354
346
  context
355
347
  );
348
+ if (groupLimit !== undefined && result.meta?.page?.hasMore === true) {
349
+ throw new GroupLimitError(name, groupLimit);
350
+ }
356
351
  return result.data;
357
352
  }
358
353
 
@@ -363,6 +358,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
363
358
  * @param {{ context?: object | null, trx?: object | null, returning?: "record" | "id" | "none", format?: "jsonapi" }} [options]
364
359
  */
365
360
  async function create(attributes, options = {}) {
361
+ checkBlobValues(resource, [attributes]);
366
362
  const returning = pickReturning(SINGLE_RETURNING, options.returning, "record", `${name}.create()`);
367
363
  const format = formatOf(name, options);
368
364
  // An afterWrite hook needs the new id, so a create returning nothing still asks for it.
@@ -387,7 +383,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
387
383
  * @param {{ id: unknown } & Record<string, unknown>} attributes
388
384
  * @param {{ context?: object | null, trx?: object | null }} [options]
389
385
  */
390
- function findOrCreate(attributes, options = {}) {
386
+ async function findOrCreate(attributes, options = {}) {
387
+ checkBlobValues(resource, [attributes]);
391
388
  return findOrCreateRecord({ get, create }, attributes, passedOn(options));
392
389
  }
393
390
 
@@ -456,6 +453,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
456
453
  if (!isRecord(attributes)) {
457
454
  throw new TypeError(`${name}.patch() takes attributes as an object.`);
458
455
  }
456
+ // Before any statement: a lockVersion or onlyIf patch locks the row first, and an afterWrite hook opens a transaction.
457
+ checkBlobValues(resource, [attributes]);
459
458
  requirePatchConditions(name, lockVersionField, attributes, options);
460
459
  const { lockVersion, onlyIf, missing: missingOption, ...callOptions } = options;
461
460
  const missing = missingOf(name, "patch", missingOption);
@@ -522,6 +521,12 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
522
521
  }
523
522
 
524
523
  function manyRowWrite(operation, rows, options, request) {
524
+ if (options.chunkSize !== undefined && !(Number.isSafeInteger(options.chunkSize) && options.chunkSize >= MIN_CHUNK_SIZE)) {
525
+ throw new TypeError(
526
+ `${name}.${operation}() chunkSize is a whole number of at least ${MIN_CHUNK_SIZE} rows (${DEFAULT_CHUNK_SIZE} when left out): ` +
527
+ "a smaller chunk sends a statement every few rows."
528
+ );
529
+ }
525
530
  const returning = pickReturning(MANY_RETURNING, options.returning, "none", `${name}.${operation}()`);
526
531
  const askFor = hooks.afterWrite && (returning === "none" || returning === "count") ? "ids" : returning;
527
532
  reportManyRow(name, operation, rows, options.chunkSize);
@@ -550,6 +555,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
550
555
  if (!Array.isArray(rows)) {
551
556
  throw new TypeError(`${name}.createMany() takes an array of rows.`);
552
557
  }
558
+ checkBlobValues(resource, rows);
553
559
  refuseConditions(name, "createMany", options, ["lockVersion", "onlyIf"],
554
560
  "A create has no stored record to compare; onConflict says what happens to a record that exists.");
555
561
  if (options.onConflict) {
@@ -573,6 +579,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
573
579
  if (!Array.isArray(rows)) {
574
580
  throw new TypeError(`${name}.patchMany() takes an array of { id, ...changes } rows.`);
575
581
  }
582
+ checkBlobValues(resource, rows);
576
583
  refuseConditions(name, "patchMany", options, ["lockVersion"], ONE_VERSION);
577
584
  requireConditionValues(name, "patchMany", options, ["onlyIf"]);
578
585
  return manyRowWrite("patchMany", rows.length, options, (params, context) => jsonRest().patchMany(
@@ -597,6 +604,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
597
604
  * @param {{ context?: object | null, trx?: object | null, returning?: "none" | "ids" | "records" | "count", onlyIf?: object, all?: boolean, chunkSize?: number, lockMode?: "update" | "noKeyUpdate" }} [options]
598
605
  */
599
606
  async function patchWhere(filters, attributes, options = {}) {
607
+ checkBlobValues(resource, [attributes]);
600
608
  refuseConditions(name, "patchWhere", options, ["lockVersion"], ONE_VERSION);
601
609
  requireConditionValues(name, "patchWhere", options, ["onlyIf"]);
602
610
  const selection = whereSelection(name, "patchWhere", filters, options);
@@ -630,7 +638,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
630
638
  }
631
639
 
632
640
  // Runs work on the record with row.id, locked, creating it first when missing (see lockOrCreate.js).
633
- function lockOrCreateRecord(row, options, work) {
641
+ async function lockOrCreateRecord(row, options, work) {
642
+ checkBlobValues(resource, [row]);
634
643
  return lockOrCreate({ name, withTransaction, lock, createMany }, row, options, work);
635
644
  }
636
645
 
@@ -711,6 +720,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
711
720
  withTransaction,
712
721
  query,
713
722
  queryAll,
723
+ queryPages,
714
724
  get,
715
725
  aggregate,
716
726
  create,
@@ -8,6 +8,7 @@ import {
8
8
  RowPolicyPlugin
9
9
  } from "json-rest-api";
10
10
  import {
11
+ isRecord,
11
12
  normalizeObject,
12
13
  normalizeOpaqueId,
13
14
  normalizeRecordId,
@@ -24,6 +25,7 @@ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
24
25
  import { resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
25
26
  import { ROUTE_VISIBILITY_WORKSPACE, ROUTE_VISIBILITY_WORKSPACE_USER } from "@jskit-ai/kernel/shared/support/visibility";
26
27
  import { createJsonRestContext } from "./contexts.js";
28
+ import { blobFields } from "./handleBlobs.js";
27
29
  import { isPlainJsonRestObject, resolveJsonRestCollectionRelationships } from "./jsonRestValues.js";
28
30
  import { valueOnlyRaw } from "./rawExpression.js";
29
31
 
@@ -299,16 +301,14 @@ function applyJsonRestQueryFields(scopeOptions = {}, extraQueryFields = {}) {
299
301
  }
300
302
  }
301
303
 
304
+ // The fields a read leaves out unless its fields name them: the resource's defaultExclude, and every blob field.
302
305
  function resolveJsonRestDefaultExcludedFields(resource) {
303
- const defaultExclude = resource.defaultExclude;
304
- if (defaultExclude == null) {
305
- return [];
306
- }
306
+ const defaultExclude = resource.defaultExclude ?? [];
307
307
  if (!Array.isArray(defaultExclude)) {
308
308
  throw new TypeError("json-rest-api resource defaultExclude must be an array.");
309
309
  }
310
310
 
311
- return normalizeUniqueTextList(defaultExclude);
311
+ return normalizeUniqueTextList([...defaultExclude, ...(isRecord(resource.schema) ? blobFields(resource) : [])]);
312
312
  }
313
313
 
314
314
  function applyJsonRestDefaultExclusions(scopeOptions = {}, resource = {}) {
@@ -9,6 +9,8 @@ import { resourceScopeOptions } from "./resourceHost.js";
9
9
 
10
10
  const DEFAULT_REQUEST_ROW_LIMIT = 10000;
11
11
  const DEFAULT_SERVER_PAGE_SIZE = 1000;
12
+ // A row policy's `requires` when its feature was owned with none (a test's runtime.own(featureId, owns)).
13
+ const NO_REQUIRES = Object.freeze({});
12
14
  const ENTRY_KEYS = Object.freeze(["resource", "rowPolicy", "hooks", "acceptsContributions", "normalizeId", "queryFields", "searchSchema"]);
13
15
  // Every table resource's datetime-utc fields are written as UTC database date-times.
14
16
  const WRITE_SERIALIZERS = Object.freeze({ "datetime-utc": toDatabaseDateTimeUtc });
@@ -44,7 +46,8 @@ function ownedEntry(entry, featureId) {
44
46
 
45
47
  /**
46
48
  * The filters of a resource's search that read another table: each `actualField` or `oneOf` path
47
- * "resource.field" (or "a.b.field", whose last resource holds the field), as { filter, target, field }.
49
+ * "resource.field" (or "a.b.field", whose last resource holds the field), as { filter, tables, target, field }, where
50
+ * `tables` names every resource the path joins and `target` the last.
48
51
  * @param {Record<string, any>} scopeOptions The resource's json-rest-api scope options.
49
52
  */
50
53
  function crossTableFilters(scopeOptions) {
@@ -56,7 +59,7 @@ function crossTableFilters(scopeOptions) {
56
59
  .filter((path) => typeof path === "string" && path.includes("."))
57
60
  .map((path) => {
58
61
  const segments = path.split(".");
59
- return { filter, target: segments.at(-2), field: segments.at(-1) };
62
+ return { filter, tables: segments.slice(0, -1), target: segments.at(-2), field: segments.at(-1) };
60
63
  }));
61
64
  }
62
65
 
@@ -144,8 +147,9 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
144
147
 
145
148
  // The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
146
149
  // Each gets who the call runs for as `caller` (see callerOf), its one way to tell: json-rest-api's own `system` flag
147
- // is left out.
148
- function composedRowPolicy(featureId, entry, contributions) {
150
+ // is left out. The owner's policy also gets the owning feature's dependencies as `requires`; a contribution is a
151
+ // function its feature built in setup, with its own.
152
+ function composedRowPolicy(featureId, entry, contributions, requires) {
149
153
  if (!entry.rowPolicy && !entry.acceptsContributions) {
150
154
  return undefined;
151
155
  }
@@ -154,7 +158,7 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
154
158
  delete args.system;
155
159
  const caller = callerOf(args.context);
156
160
  if (entry.rowPolicy) {
157
- const result = await applyGrouped(entry.rowPolicy, { ...args, caller, ownTable: ownTableReader(featureId, args.db) });
161
+ const result = await applyGrouped(entry.rowPolicy, { ...args, caller, ownTable: ownTableReader(featureId, args.db), requires });
158
162
  if (result !== true) {
159
163
  return result;
160
164
  }
@@ -184,30 +188,50 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
184
188
  }
185
189
 
186
190
  /**
187
- * Refuses, at startup, a cross-table filter on a field json-rest-api cannot search: one its target resource does
188
- * not declare `indexed: true`, which json-rest-api otherwise refuses only at the first query. A filter whose
189
- * target no feature owns yet waits for it.
191
+ * Refuses, at startup, a cross-table filter json-rest-api would not search, or would search outside its owner's
192
+ * consent. json-rest-api joins each table the path names as that table's own read in the caller's scope (its
193
+ * ownership, its owner's row policy and the policies contributed to it), and searches only a field its owner declares
194
+ * `indexed: true`, which it otherwise refuses only at the first query. Two tables no scope guards are refused here: a
195
+ * `system` table, which only its owner's system context reads, joined into a table that is not `system` itself (a
196
+ * request would read it), and a hidden field, whose value a filter would tell a caller who may not read it. A filter
197
+ * whose tables no feature owns yet waits for them.
190
198
  * @param {ReadonlyArray<{ resource: Record<string, any> }>} entries The resources being owned now.
191
199
  * @param {ReadonlyArray<Record<string, any>>} scopes Their json-rest-api scope options, in the same order.
192
200
  */
193
201
  function checkCrossTableFilters(entries, scopes) {
194
202
  const owning = new Map(entries.map(({ resource }) => [resource.name, resource]));
195
- const targetNamed = (name) => owning.get(name) || ownedByName.get(name)?.resource;
203
+ const resourceOf = (name) => owning.get(name) || ownedByName.get(name)?.resource;
196
204
  const filters = [
197
205
  ...pendingCrossTableFilters.splice(0),
198
- ...entries.flatMap(({ resource }, index) => crossTableFilters(scopes[index]).map((filter) => ({ ...filter, source: resource.name })))
206
+ ...entries.flatMap(({ resource }, index) => crossTableFilters(scopes[index]).map((filter) => ({ ...filter, source: resource })))
199
207
  ];
200
208
  for (const filter of filters) {
201
- const target = targetNamed(filter.target);
202
- if (!target) {
209
+ if (!filter.tables.every(resourceOf)) {
203
210
  pendingCrossTableFilters.push(filter);
204
211
  continue;
205
212
  }
206
- if (target.schema?.[filter.field]?.indexed !== true) {
213
+ const { source, filter: name, target, field } = filter;
214
+ const on = `Table resource "${source.name}" filters "${name}" on ${target}.${field}`;
215
+ const instead = `filter on a field of "${source.name}", or have the owner of "${target}" answer the ids it matches ` +
216
+ "(an owner API) and filter by them.";
217
+ const system = filter.tables.find((table) => resourceOf(table).ownership === "system");
218
+ if (system && source.ownership !== "system") {
207
219
  throw new TypeError(
208
- `Table resource "${filter.source}" filters "${filter.filter}" on ${filter.target}.${filter.field}, which ` +
209
- `"${filter.target}" does not declare indexed: true. A cross-table filter reads another table by that field: ` +
210
- `give the field indexed: true and its column a database index, or filter on a field of "${filter.source}".`
220
+ `${on}, which reads "${system}", a system table: only its owner's system context reads it, and the filter ` +
221
+ `would read it in the caller's scope, a request's too. Make "${system}" a table the caller's scope guards, or ${instead}`
222
+ );
223
+ }
224
+ const definition = resourceOf(target).schema?.[field];
225
+ if (definition?.hidden === true) {
226
+ throw new TypeError(
227
+ `${on}, a field "${target}" hides: a filter on it would tell a caller who may not read it which rows hold a ` +
228
+ `value. Filter on a field "${target}" shows, or ${instead}`
229
+ );
230
+ }
231
+ if (definition?.indexed !== true) {
232
+ throw new TypeError(
233
+ `${on}, which "${target}" does not declare indexed: true. A cross-table filter reads another table by that field: ` +
234
+ `give the field indexed: true and its column a database index, or filter on a field of "${source.name}".`
211
235
  );
212
236
  }
213
237
  }
@@ -219,8 +243,10 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
219
243
  * narrows another feature's resource whose owner accepts contributions.
220
244
  * @param {string} featureId
221
245
  * @param {ReadonlyArray<object>} owns
246
+ * @param {{ requires?: Readonly<Record<string, unknown>> }} [options] The feature's dependencies, by local name, as its
247
+ * setup receives them (defineFeature passes them): each entry's rowPolicy receives them as `requires`.
222
248
  */
223
- async function own(featureId, owns) {
249
+ async function own(featureId, owns, { requires = NO_REQUIRES } = {}) {
224
250
  const entries = owns.map((entry) => ownedEntry(entry, featureId));
225
251
  const names = new Set();
226
252
  for (const { resource } of entries) {
@@ -234,7 +260,7 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
234
260
  const scopes = entries.map((entry, index) => resourceScopeOptions(entry.resource, {
235
261
  writeSerializers: WRITE_SERIALIZERS,
236
262
  normalizeId: entry.normalizeId,
237
- rowPolicy: composedRowPolicy(featureId, entry, contributions[index]),
263
+ rowPolicy: composedRowPolicy(featureId, entry, contributions[index], requires),
238
264
  searchSchema: entry.searchSchema,
239
265
  queryFields: entry.queryFields
240
266
  }));
@@ -32,6 +32,11 @@
32
32
  * @typedef {ReturnType<typeof import("./resourceHandle.js").createResourceHandle>} ResourceHandle
33
33
  */
34
34
 
35
+ /**
36
+ * A handle's reads of the hidden fields a read names, which json-rest-api leaves out (see handleHidden.js).
37
+ * @typedef {ReturnType<typeof import("./handleHidden.js").createHiddenFieldReads>} HiddenFieldReads
38
+ */
39
+
35
40
  /**
36
41
  * The options every handle call takes last: the caller's context (an action's,
37
42
  * or a system context) and the transaction to join.
@@ -1,13 +1,16 @@
1
1
  import { AssertionError } from "node:assert";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import diagnosticsChannel from "node:diagnostics_channel";
3
4
  import {
4
5
  countQueries,
5
6
  countRuntimeQueries,
6
7
  requireTestDatabase
7
8
  } from "@jskit-ai/database-runtime/server/testDatabases";
8
- import { MANY_ROW_CHANNEL } from "../server/resourceHandle.js";
9
+ import { MANY_ROW_CHANNEL } from "../server/manyRowChannel.js";
9
10
 
10
11
  const REPEATED_STATEMENTS_SHOWN = 5;
12
+ // The measurement open in the current async context: a many-row call reports for the one whose work makes it.
13
+ const openMeasurement = new AsyncLocalStorage();
11
14
  // A quoted SQL string, written as a string so that source scanners that skip quoted text keep their place.
12
15
  const SQL_STRING_LITERAL = new RegExp("'(?:[^']|'')*'", "gu");
13
16
 
@@ -39,19 +42,25 @@ function requireSizes(sizes) {
39
42
 
40
43
  /**
41
44
  * Counts the statements `work` sends, and the extra statements the many-row
42
- * calls among them report for their chunks after the first.
45
+ * calls among them report for their chunks after the first, and queryPages()
46
+ * for its pages after the first. Both come only
47
+ * from `work` and the async work it starts, as countQueries() counts them, so
48
+ * another test or a loop running meanwhile does not change the count.
43
49
  * @param {import("knex").Knex | import("knex").Knex.Transaction | null} knex
44
50
  * @param {() => unknown} work
45
51
  */
46
52
  async function measure(knex, work) {
47
53
  const calls = [];
54
+ const measurement = Symbol("measurement");
48
55
  const listen = (message) => {
49
- calls.push(message);
56
+ if (openMeasurement.getStore() === measurement) calls.push(message);
50
57
  };
51
58
  diagnosticsChannel.subscribe(MANY_ROW_CHANNEL, listen);
52
59
  try {
53
- const { count, queries } = knex ? await countQueries(knex, work) : await countRuntimeQueries(work);
54
- const chunkStatements = calls.reduce((total, { rows, chunkSize }) => total + Math.max(0, Math.ceil(rows / chunkSize) - 1), 0);
60
+ const { count, queries } = await openMeasurement.run(measurement, () => knex ? countQueries(knex, work) : countRuntimeQueries(work));
61
+ // A many-row write's chunks after its first, and the statements of each queryPages() page after its first.
62
+ const chunkStatements = calls.reduce((total, { operation, statements, rows, chunkSize }) =>
63
+ total + (operation === "queryPages" ? statements : Math.max(0, Math.ceil(rows / chunkSize) - 1)), 0);
55
64
  return { count, chunkStatements, queries };
56
65
  } finally {
57
66
  diagnosticsChannel.unsubscribe(MANY_ROW_CHANNEL, listen);
@@ -60,10 +69,13 @@ async function measure(knex, work) {
60
69
 
61
70
  /**
62
71
  * Fails when a path's statements grow with its rows. For each size, smallest first, it seeds that many rows with
63
- * `seed(size)`, then runs `run(seeded, size)` and counts the statements sent meanwhile: through `knex` when given (its
64
- * transactions' included), else through the runtime of a server the test booted, as countRuntimeQueries() does. The
65
- * extra statements of a many-row write's later chunks, which its handle reports, are allowed, so no number is
66
- * hand-picked. A flat path then sends as many statements at every size; a path that reads or writes row by row sends
72
+ * `seed(size)`, then runs `run(seeded, size)` and counts the statements it sends: through `knex` when given (its
73
+ * transactions' included), else through the runtime of a server the test booted, as countRuntimeQueries() does. Only
74
+ * the path's own statements count, from `run` and the async work it starts, so a test or a background loop sending
75
+ * through the same Knex meanwhile changes nothing. The
76
+ * extra statements of a many-row write's later chunks, and of a queryPages() read's later pages (its own page, include
77
+ * and hidden-field reads, whose pages shrink to a few rows when they name blobs), which its handle reports, are
78
+ * allowed, so no number is hand-picked; work the path does itself for each page counts. A flat path then sends as many statements at every size; a path that reads or writes row by row sends
67
79
  * more at each, and one that sends none at every size was counted on the wrong channel and fails too. On failure the message gives every count and the statements repeated most at the largest size. Its seed
68
80
  * keeps the sizes apart (a workspace or user of their own, or a fresh database).
69
81
  * @template S
@@ -74,7 +86,7 @@ async function measure(knex, work) {
74
86
  * @param {import("knex").Knex | import("knex").Knex.Transaction | null} [options.knex]
75
87
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.environment The test's environment, such as `process.env`.
76
88
  * @returns {Promise<Array<{ size: number, count: number, chunkStatements: number }>>} The count at each size, and how
77
- * many of its statements were later chunks of many-row writes.
89
+ * many of its statements were later chunks of many-row writes or later pages of queryPages().
78
90
  */
79
91
  async function expectFlatQueries({ sizes = [10, 200], seed, run, knex = null, environment }) {
80
92
  requireTestDatabase(environment);
@@ -101,7 +113,7 @@ async function expectFlatQueries({ sizes = [10, 200], seed, run, knex = null, en
101
113
  const growing = ({ count, chunkStatements }) => count - chunkStatements > smallest.count - smallest.chunkStatements;
102
114
  if (measured.some(growing)) {
103
115
  const described = counts.map(({ size, count, chunkStatements }) =>
104
- `${count} at ${size} rows${chunkStatements > 0 ? ` (${chunkStatements} of them later chunks)` : ""}`);
116
+ `${count} at ${size} rows${chunkStatements > 0 ? ` (${chunkStatements} of them later chunks or pages)` : ""}`);
105
117
  const repeated = mostRepeated(largest.queries).map(([statement, times]) => ` ${times} x ${statement}`);
106
118
  throw new AssertionError({
107
119
  message: [
package/src/test/index.js CHANGED
@@ -38,8 +38,8 @@ async function createTestResourceRuntime({ knex, logger = silentLogger, requestR
38
38
  }
39
39
  return Object.freeze({
40
40
  ...runtime,
41
- async own(featureId, owns) {
42
- const handles = await runtime.own(featureId, owns);
41
+ async own(featureId, owns, options) {
42
+ const handles = await runtime.own(featureId, owns, options);
43
43
  for (const name of Object.keys(handles)) {
44
44
  await api.resources[name].createKnexTable();
45
45
  }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { blobFieldsCases } from "./support/blobFieldsCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of blobFieldsCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { blobFieldsCases } from "./support/blobFieldsCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of blobFieldsCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { crossTableFiltersCases } from "./support/crossTableFiltersCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of crossTableFiltersCases(ownMysqlDatabase)) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { createPackageTestKnex } from "../src/test/index.js";
3
+ import { crossTableFiltersCases } from "./support/crossTableFiltersCases.js";
4
+
5
+ // SQLite in memory, or a PostgreSQL schema of its own on a DB_CLIENT=pg run (see createPackageTestKnex).
6
+ for (const [name, run] of crossTableFiltersCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -1,4 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
+ import { Readable } from "node:stream";
2
3
  import test from "node:test";
3
4
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
5
  import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
@@ -229,6 +230,46 @@ test("withoutHiddenFields refuses a hidden field named through any method, and s
229
230
  assert.deepEqual(await exposed.cardsTitled({ context: system.forWorkspace("2") }, { title: "Kit" }), [{ id: "3", title: "Kit", publicToken: "t3" }]);
230
231
  });
231
232
 
233
+ test("withoutHiddenFields strips the hidden fields from each page queryPages() hands another feature, and refuses one its fields names", async (t) => {
234
+ const { cards, resource, system, options } = await createCardFixture(t);
235
+ const owner = Object.freeze({
236
+ ...cards,
237
+ tokenPages: (callOptions) => cards.queryPages({ fields: ["title", "publicToken"] }, callOptions),
238
+ // An owner's method of another name that forwards the caller's params to queryPages().
239
+ eachCard: (params, callOptions) => cards.queryPages(params, callOptions),
240
+ // A stream of the owner's own, which passes as it is.
241
+ exportStream: () => Readable.from(["Rex\n", "Bo\n"])
242
+ });
243
+ const exposed = withoutHiddenFields(owner, resource);
244
+ const pagesOf = async (pages) => {
245
+ const read = [];
246
+ for await (const records of pages) {
247
+ read.push(records);
248
+ }
249
+ return read;
250
+ };
251
+ assert.deepEqual(await pagesOf(exposed.tokenPages(options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
252
+ assert.deepEqual(await pagesOf(exposed.queryPages({ fields: ["title"] }, options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
253
+ await assert.rejects(pagesOf(exposed.queryPages({ fields: ["title", "publicToken"] }, options)), /cards\.queryPages\(\) fields names the hidden field "publicToken"/u);
254
+ assert.deepEqual(await pagesOf(exposed.tokenPages({ context: system.forWorkspace("2") })), [[{ id: "3", title: "Kit", publicToken: "t3" }]]);
255
+
256
+ // A refusal is pages that throw and a rejected promise at once, whatever the method's name, and leaves no rejection
257
+ // unhandled when only iterated.
258
+ const unhandled = [];
259
+ const onUnhandled = (reason) => unhandled.push(reason);
260
+ process.on("unhandledRejection", onUnhandled);
261
+ t.after(() => process.off("unhandledRejection", onUnhandled));
262
+ assert.deepEqual(await pagesOf(exposed.eachCard({ fields: ["title"] }, options)), [[{ id: "1", title: "Rex" }, { id: "2", title: "Bo" }]]);
263
+ await assert.rejects(pagesOf(exposed.eachCard({ fields: ["title", "publicToken"] }, options)), /cards\.eachCard\(\) fields names the hidden field "publicToken"/u);
264
+ await assert.rejects(exposed.eachCard({ fields: ["publicToken"] }, options), /cards\.eachCard\(\) fields names the hidden field/u);
265
+ await new Promise((resolve) => setImmediate(resolve));
266
+ assert.deepEqual(unhandled, []);
267
+ const stream = exposed.exportStream();
268
+ assert.equal(stream instanceof Readable, true);
269
+ assert.equal(typeof stream.pipe, "function");
270
+ assert.deepEqual(await stream.toArray(), ["Rex\n", "Bo\n"]);
271
+ });
272
+
232
273
  test("withoutHiddenFields refuses a field one owned table hides and another shows, since it strips hidden fields by name", () => {
233
274
  const cards = defineTableResource({
234
275
  name: "cards",