@jskit-ai/resource-runtime 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/locales/en.json +3 -1
  3. package/package.json +6 -6
  4. package/src/server/errors.js +29 -5
  5. package/src/server/filterJoinSources.js +177 -0
  6. package/src/server/handleBlobs.js +139 -0
  7. package/src/server/handleEveryRow.js +188 -0
  8. package/src/server/handleHidden.js +46 -4
  9. package/src/server/handleLocks.js +173 -19
  10. package/src/server/handleRecords.js +16 -3
  11. package/src/server/index.js +1 -0
  12. package/src/server/manyRowChannel.js +44 -0
  13. package/src/server/resourceHandle.js +64 -52
  14. package/src/server/resourceHost.js +5 -5
  15. package/src/server/resourceRuntime.js +67 -20
  16. package/src/server/types.js +5 -0
  17. package/src/test/expectFlatQueries.js +23 -11
  18. package/src/test/index.js +2 -2
  19. package/test/blobFields.mysql.test.js +8 -0
  20. package/test/blobFields.test.js +8 -0
  21. package/test/crossTableFilters.mysql.test.js +8 -0
  22. package/test/crossTableFilters.test.js +8 -0
  23. package/test/filterJoinSources.mysql.test.js +8 -0
  24. package/test/filterJoinSources.test.js +8 -0
  25. package/test/hiddenFields.test.js +41 -0
  26. package/test/lockIncludes.mysql.test.js +8 -0
  27. package/test/lockIncludes.test.js +8 -0
  28. package/test/lockedReads.mysql.test.js +156 -0
  29. package/test/pagedReads.mysql.test.js +8 -0
  30. package/test/pagedReads.test.js +8 -0
  31. package/test/reportsAcrossOwners.mysql.test.js +8 -0
  32. package/test/reportsAcrossOwners.test.js +8 -0
  33. package/test/resourceRuntime.test.js +55 -2
  34. package/test/support/blobFieldsCases.js +226 -0
  35. package/test/support/crossTableFiltersCases.js +180 -0
  36. package/test/support/filterJoinSourcesCases.js +256 -0
  37. package/test/support/lockIncludesCases.js +158 -0
  38. package/test/support/mysqlDatabase.js +35 -0
  39. package/test/support/pagedReadsCases.js +168 -0
  40. package/test/support/reportsAcrossOwnersCases.js +201 -0
  41. package/test/testHelpers.test.js +128 -3
@@ -1,14 +1,17 @@
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 { withCallOptions } from "./filterJoinSources.js";
11
+ import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
9
12
  import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
10
13
  import { valueOnlyRaw } from "./rawExpression.js";
11
- import { PageSizeError, RowLimitError, StaleRecordError, UnpagedQueryError } from "./errors.js";
14
+ import { GroupLimitError, PageSizeError, StaleRecordError, UnpagedQueryError } from "./errors.js";
12
15
  import {
13
16
  formatOf, matchesNoRow, missingOf, passedOn, refuseConditions, requireConditionValues, requireDefinedFilters, requireOwners, requirePatchConditions,
14
17
  requireReadParams, requireUpsertRows, whereSelection
@@ -36,11 +39,10 @@ import {
36
39
  returnNullWhenJsonRestResourceMissing
37
40
  } from "./resourceHost.js";
38
41
 
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
42
  const DEFAULT_CHUNK_SIZE = 500;
43
+ // The fewest rows a many-row call's chunk holds. A smaller chunk sends a statement every few rows, as a loop of
44
+ // single-row writes does, and a flat-query check allows a many-row call's later chunks.
45
+ const MIN_CHUNK_SIZE = 100;
44
46
  // Why a many-row patch refuses lockVersion: one version does not hold for many records.
45
47
  const ONE_VERSION = "To change only the rows still at one version, give onlyIf the lock version field and that version; " +
46
48
  "to compare each record's own version, patch() it with its lockVersion.";
@@ -142,8 +144,9 @@ function write(options, run) {
142
144
  * @param {{ requestRowLimit: number, serverPageSize: number }} dependencies.settings
143
145
  * @param {(name: string) => (import("@jskit-ai/resource-core/shared/tableResource").TableResource | null)} dependencies.resourceNamed
144
146
  * The application's table resources by name, which shape included records.
147
+ * @param {(name: string) => ({ lockMany: Function } | null)} dependencies.handleNamed Owned tables' handles, for a lock's include.
145
148
  */
146
- function createResourceHandle({ api, resource, hooks, settings, resourceNamed }) {
149
+ function createResourceHandle({ api, resource, hooks, settings, resourceNamed, handleNamed }) {
147
150
  const name = resource.name;
148
151
  const lockVersionField = resource.lockVersionField || "";
149
152
  const quiet = { list: quietCollections(resource, "hydrateOnList"), view: quietCollections(resource, "hydrateOnView") };
@@ -152,11 +155,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
152
155
  return api.resources[name];
153
156
  }
154
157
 
155
- /** @param {{ context?: object | null }} options */
158
+ /** @param {{ context?: object | null, trx?: object | null }} options The call's, which its join sources are built in. */
156
159
  function contextOf(options) {
157
160
  requireHandleTransaction(name, options);
158
161
  requireOwners(name, resource.ownership, options.context);
159
- return createJsonRestContext(options.context);
162
+ return withCallOptions(createJsonRestContext(options.context), options);
160
163
  }
161
164
 
162
165
  // The fields a list or a one-record read names (see requestedFields).
@@ -166,7 +169,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
166
169
  // The table as a join source, with its visible columns only (see handleHidden.js).
167
170
  const joinSource = createJoinSource({ api, resource, jsonRest, scopedQuery, column });
168
171
  // lock, lockMany, lockWhere and claim (see handleLocks.js).
169
- const { lock, lockMany, lockWhere, claim } = createLockReads({ name, resource, jsonRest, readFields, contextOf, hiddenFields });
172
+ const { lock, lockMany, lockWhere, claim } = createLockReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, handleNamed, resourceNamed });
170
173
 
171
174
  /**
172
175
  * Runs work in the caller's transaction (`options.trx`), or in one it opens,
@@ -213,11 +216,15 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
213
216
  });
214
217
  }
215
218
 
216
- /** The largest page query() serves, and the page size of every-row reads. */
219
+ /**
220
+ * The largest page query() serves and the most groups one aggregate() answers (`request`), the page size of every-row
221
+ * reads (`server`), and the most rows queryAll() and queryPages() read in a request context (`requestRows`).
222
+ */
217
223
  function pageLimits() {
218
224
  return Object.freeze({
219
225
  request: jsonRest().vars.queryMaxLimit,
220
- server: settings.serverPageSize
226
+ server: settings.serverPageSize,
227
+ requestRows: settings.requestRowLimit
221
228
  });
222
229
  }
223
230
 
@@ -235,6 +242,10 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
235
242
  const read = { ...params, fields: readFields(params, "list") };
236
243
  const queryParams = readQueryParams(resource, read, { page: true, caller: "query" });
237
244
  const hidden = hiddenFields.named(params.fields, format);
245
+ const blobs = namedBlobs(resource, params.fields, resourceNamed);
246
+ if (format === "jsonapi") {
247
+ refuseBlobsInJson(name, blobs);
248
+ }
238
249
  const size = params.page?.size;
239
250
  if (size == null && format !== "jsonapi") {
240
251
  throw new UnpagedQueryError(name);
@@ -242,6 +253,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
242
253
  if (size != null && Number(size) > pageLimits().request) {
243
254
  throw new PageSizeError(name, size, pageLimits().request);
244
255
  }
256
+ checkBlobReads(name, "query", blobs, Number(size));
245
257
  const context = contextOf(options);
246
258
  const payload = format !== "jsonapi" && matchesNoRow(params.filters, jsonRest().vars.schemaInfo)
247
259
  ? { data: [] }
@@ -267,41 +279,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
267
279
  });
268
280
  }
269
281
 
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
- }
282
+ // queryAll and queryPages (see handleEveryRow.js).
283
+ const { queryAll, queryPages } = createEveryRowReads({ api, name, resource, jsonRest, readFields, contextOf, hiddenFields, settings, resourceNamed });
305
284
 
306
285
  /**
307
286
  * One record. A missing or hidden one throws json-rest-api's not-found error
@@ -315,6 +294,11 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
315
294
  const format = formatOf(name, options);
316
295
  const named = { ...params, fields: readFields(params, "view") };
317
296
  const hidden = hiddenFields.named(params.fields, format);
297
+ const blobs = namedBlobs(resource, params.fields, resourceNamed);
298
+ if (format === "jsonapi") {
299
+ refuseBlobsInJson(name, blobs);
300
+ }
301
+ checkBlobReads(name, "get", blobs);
318
302
  const read = () => returnBadRequestWhenJsonRestFieldsetInvalid(() => jsonRest().get(
319
303
  {
320
304
  id,
@@ -331,15 +315,24 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
331
315
  /**
332
316
  * Totals: `measures` ({ name: { count | countDistinct | sum | avg | min | max: field, where? } })
333
317
  * 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
318
+ * One statement answers at most pageLimits().request groups: a grouped
319
+ * aggregate without `page` answers every group or, when there are more, throws
320
+ * GroupLimitError rather than answer part of them. `page: { size, number }`
321
+ * (number from 1) answers one page of groups; a page shorter than `size` is the last.
322
+ * @param {{ measures: object, groupBy?: Array<string | object>, filters?: object, sort?: string[], page?: { size: number, number?: number } }} spec
335
323
  * @param {{ context?: object | null, trx?: object | null }} [options]
336
324
  */
337
325
  async function aggregate({ measures, groupBy, filters, sort, page }, options = {}) {
338
326
  requireDefinedFilters(name, "aggregate", filters);
327
+ if (page !== undefined && page?.size == null) {
328
+ throw new TypeError(`${name}.aggregate() page needs size (at most pageLimits().request) and takes number from 1: page: { size, number }.`);
329
+ }
339
330
  const context = contextOf(options);
340
331
  if (matchesNoRow(filters, jsonRest().vars.schemaInfo)) {
341
332
  return noRowsAggregate(measures, groupBy);
342
333
  }
334
+ // json-rest-api pages grouped rows at its default page size when none is named, and says so only in meta.
335
+ const groupLimit = page === undefined && Array.isArray(groupBy) && groupBy.length > 0 ? pageLimits().request : undefined;
343
336
  const result = await jsonRest().aggregate(
344
337
  {
345
338
  measures: aggregateMeasures(measures),
@@ -347,12 +340,16 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
347
340
  queryParams: {
348
341
  ...(filters === undefined ? {} : { filters }),
349
342
  ...(sort === undefined ? {} : { sort: textList(sort) }),
350
- ...(page === undefined ? {} : { page })
343
+ ...(page === undefined ? {} : { page }),
344
+ ...(groupLimit === undefined ? {} : { page: { size: groupLimit } })
351
345
  },
352
346
  transaction: options.trx || undefined
353
347
  },
354
348
  context
355
349
  );
350
+ if (groupLimit !== undefined && result.meta?.page?.hasMore === true) {
351
+ throw new GroupLimitError(name, groupLimit);
352
+ }
356
353
  return result.data;
357
354
  }
358
355
 
@@ -363,6 +360,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
363
360
  * @param {{ context?: object | null, trx?: object | null, returning?: "record" | "id" | "none", format?: "jsonapi" }} [options]
364
361
  */
365
362
  async function create(attributes, options = {}) {
363
+ checkBlobValues(resource, [attributes]);
366
364
  const returning = pickReturning(SINGLE_RETURNING, options.returning, "record", `${name}.create()`);
367
365
  const format = formatOf(name, options);
368
366
  // An afterWrite hook needs the new id, so a create returning nothing still asks for it.
@@ -387,7 +385,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
387
385
  * @param {{ id: unknown } & Record<string, unknown>} attributes
388
386
  * @param {{ context?: object | null, trx?: object | null }} [options]
389
387
  */
390
- function findOrCreate(attributes, options = {}) {
388
+ async function findOrCreate(attributes, options = {}) {
389
+ checkBlobValues(resource, [attributes]);
391
390
  return findOrCreateRecord({ get, create }, attributes, passedOn(options));
392
391
  }
393
392
 
@@ -456,6 +455,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
456
455
  if (!isRecord(attributes)) {
457
456
  throw new TypeError(`${name}.patch() takes attributes as an object.`);
458
457
  }
458
+ // Before any statement: a lockVersion or onlyIf patch locks the row first, and an afterWrite hook opens a transaction.
459
+ checkBlobValues(resource, [attributes]);
459
460
  requirePatchConditions(name, lockVersionField, attributes, options);
460
461
  const { lockVersion, onlyIf, missing: missingOption, ...callOptions } = options;
461
462
  const missing = missingOf(name, "patch", missingOption);
@@ -522,6 +523,12 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
522
523
  }
523
524
 
524
525
  function manyRowWrite(operation, rows, options, request) {
526
+ if (options.chunkSize !== undefined && !(Number.isSafeInteger(options.chunkSize) && options.chunkSize >= MIN_CHUNK_SIZE)) {
527
+ throw new TypeError(
528
+ `${name}.${operation}() chunkSize is a whole number of at least ${MIN_CHUNK_SIZE} rows (${DEFAULT_CHUNK_SIZE} when left out): ` +
529
+ "a smaller chunk sends a statement every few rows."
530
+ );
531
+ }
525
532
  const returning = pickReturning(MANY_RETURNING, options.returning, "none", `${name}.${operation}()`);
526
533
  const askFor = hooks.afterWrite && (returning === "none" || returning === "count") ? "ids" : returning;
527
534
  reportManyRow(name, operation, rows, options.chunkSize);
@@ -550,6 +557,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
550
557
  if (!Array.isArray(rows)) {
551
558
  throw new TypeError(`${name}.createMany() takes an array of rows.`);
552
559
  }
560
+ checkBlobValues(resource, rows);
553
561
  refuseConditions(name, "createMany", options, ["lockVersion", "onlyIf"],
554
562
  "A create has no stored record to compare; onConflict says what happens to a record that exists.");
555
563
  if (options.onConflict) {
@@ -573,6 +581,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
573
581
  if (!Array.isArray(rows)) {
574
582
  throw new TypeError(`${name}.patchMany() takes an array of { id, ...changes } rows.`);
575
583
  }
584
+ checkBlobValues(resource, rows);
576
585
  refuseConditions(name, "patchMany", options, ["lockVersion"], ONE_VERSION);
577
586
  requireConditionValues(name, "patchMany", options, ["onlyIf"]);
578
587
  return manyRowWrite("patchMany", rows.length, options, (params, context) => jsonRest().patchMany(
@@ -597,6 +606,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
597
606
  * @param {{ context?: object | null, trx?: object | null, returning?: "none" | "ids" | "records" | "count", onlyIf?: object, all?: boolean, chunkSize?: number, lockMode?: "update" | "noKeyUpdate" }} [options]
598
607
  */
599
608
  async function patchWhere(filters, attributes, options = {}) {
609
+ checkBlobValues(resource, [attributes]);
600
610
  refuseConditions(name, "patchWhere", options, ["lockVersion"], ONE_VERSION);
601
611
  requireConditionValues(name, "patchWhere", options, ["onlyIf"]);
602
612
  const selection = whereSelection(name, "patchWhere", filters, options);
@@ -630,7 +640,8 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
630
640
  }
631
641
 
632
642
  // Runs work on the record with row.id, locked, creating it first when missing (see lockOrCreate.js).
633
- function lockOrCreateRecord(row, options, work) {
643
+ async function lockOrCreateRecord(row, options, work) {
644
+ checkBlobValues(resource, [row]);
634
645
  return lockOrCreate({ name, withTransaction, lock, createMany }, row, options, work);
635
646
  }
636
647
 
@@ -711,6 +722,7 @@ function createResourceHandle({ api, resource, hooks, settings, resourceNamed })
711
722
  withTransaction,
712
723
  query,
713
724
  queryAll,
725
+ queryPages,
714
726
  get,
715
727
  aggregate,
716
728
  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 = {}) {
@@ -4,11 +4,14 @@ import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import { isTableResource } from "@jskit-ai/resource-core/shared/tableResource";
5
5
  import { callerOf, createSystemContext } from "./contexts.js";
6
6
  import { DuplicateOwnerError } from "./errors.js";
7
+ import { filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
7
8
  import { createResourceHandle } from "./resourceHandle.js";
8
9
  import { resourceScopeOptions } from "./resourceHost.js";
9
10
 
10
11
  const DEFAULT_REQUEST_ROW_LIMIT = 10000;
11
12
  const DEFAULT_SERVER_PAGE_SIZE = 1000;
13
+ // A row policy's `requires` when its feature was owned with none (a test's runtime.own(featureId, owns)).
14
+ const NO_REQUIRES = Object.freeze({});
12
15
  const ENTRY_KEYS = Object.freeze(["resource", "rowPolicy", "hooks", "acceptsContributions", "normalizeId", "queryFields", "searchSchema"]);
13
16
  // Every table resource's datetime-utc fields are written as UTC database date-times.
14
17
  const WRITE_SERIALIZERS = Object.freeze({ "datetime-utc": toDatabaseDateTimeUtc });
@@ -44,7 +47,8 @@ function ownedEntry(entry, featureId) {
44
47
 
45
48
  /**
46
49
  * 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 }.
50
+ * "resource.field" (or "a.b.field", whose last resource holds the field), as { filter, tables, target, field }, where
51
+ * `tables` names every resource the path joins and `target` the last.
48
52
  * @param {Record<string, any>} scopeOptions The resource's json-rest-api scope options.
49
53
  */
50
54
  function crossTableFilters(scopeOptions) {
@@ -56,7 +60,7 @@ function crossTableFilters(scopeOptions) {
56
60
  .filter((path) => typeof path === "string" && path.includes("."))
57
61
  .map((path) => {
58
62
  const segments = path.split(".");
59
- return { filter, target: segments.at(-2), field: segments.at(-1) };
63
+ return { filter, tables: segments.slice(0, -1), target: segments.at(-2), field: segments.at(-1) };
60
64
  }));
61
65
  }
62
66
 
@@ -107,6 +111,8 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
107
111
  const ownedByName = new Map();
108
112
  /** @type {Map<string, string>} */
109
113
  const ownerByTable = new Map();
114
+ /** @type {Map<string, object>} Each owned table's handle, by resource name: a lock's include locks through it. */
115
+ const handleByName = new Map();
110
116
  // Cross-table filters whose target table no feature owns yet: they are checked when its owner owns it.
111
117
  const pendingCrossTableFilters = [];
112
118
  /** @type {Map<string, string>} The system scope each feature declared. */
@@ -131,6 +137,14 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
131
137
  return ownedByName.get(name)?.resource ?? null;
132
138
  }
133
139
 
140
+ /**
141
+ * The handle of the table a feature owns under `name`, or null: a lock's include locks related records through it.
142
+ * @param {string} name
143
+ */
144
+ function handleNamed(name) {
145
+ return handleByName.get(name) ?? null;
146
+ }
147
+
134
148
  // A SELECT-only builder over one of the feature's own tables, for a row policy's subqueries.
135
149
  function ownTableReader(featureId, db) {
136
150
  return function ownTable(name) {
@@ -144,8 +158,9 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
144
158
 
145
159
  // The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
146
160
  // 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) {
161
+ // is left out. The owner's policy also gets the owning feature's dependencies as `requires`; a contribution is a
162
+ // function its feature built in setup, with its own.
163
+ function composedRowPolicy(featureId, entry, contributions, requires) {
149
164
  if (!entry.rowPolicy && !entry.acceptsContributions) {
150
165
  return undefined;
151
166
  }
@@ -154,7 +169,7 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
154
169
  delete args.system;
155
170
  const caller = callerOf(args.context);
156
171
  if (entry.rowPolicy) {
157
- const result = await applyGrouped(entry.rowPolicy, { ...args, caller, ownTable: ownTableReader(featureId, args.db) });
172
+ const result = await applyGrouped(entry.rowPolicy, { ...args, caller, ownTable: ownTableReader(featureId, args.db), requires });
158
173
  if (result !== true) {
159
174
  return result;
160
175
  }
@@ -184,30 +199,50 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
184
199
  }
185
200
 
186
201
  /**
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.
202
+ * Refuses, at startup, a cross-table filter json-rest-api would not search, or would search outside its owner's
203
+ * consent. json-rest-api joins each table the path names as that table's own read in the caller's scope (its
204
+ * ownership, its owner's row policy and the policies contributed to it), and searches only a field its owner declares
205
+ * `indexed: true`, which it otherwise refuses only at the first query. Two tables no scope guards are refused here: a
206
+ * `system` table, which only its owner's system context reads, joined into a table that is not `system` itself (a
207
+ * request would read it), and a hidden field, whose value a filter would tell a caller who may not read it. A filter
208
+ * whose tables no feature owns yet waits for them.
190
209
  * @param {ReadonlyArray<{ resource: Record<string, any> }>} entries The resources being owned now.
191
210
  * @param {ReadonlyArray<Record<string, any>>} scopes Their json-rest-api scope options, in the same order.
192
211
  */
193
212
  function checkCrossTableFilters(entries, scopes) {
194
213
  const owning = new Map(entries.map(({ resource }) => [resource.name, resource]));
195
- const targetNamed = (name) => owning.get(name) || ownedByName.get(name)?.resource;
214
+ const resourceOf = (name) => owning.get(name) || ownedByName.get(name)?.resource;
196
215
  const filters = [
197
216
  ...pendingCrossTableFilters.splice(0),
198
- ...entries.flatMap(({ resource }, index) => crossTableFilters(scopes[index]).map((filter) => ({ ...filter, source: resource.name })))
217
+ ...entries.flatMap(({ resource }, index) => crossTableFilters(scopes[index]).map((filter) => ({ ...filter, source: resource })))
199
218
  ];
200
219
  for (const filter of filters) {
201
- const target = targetNamed(filter.target);
202
- if (!target) {
220
+ if (!filter.tables.every(resourceOf)) {
203
221
  pendingCrossTableFilters.push(filter);
204
222
  continue;
205
223
  }
206
- if (target.schema?.[filter.field]?.indexed !== true) {
224
+ const { source, filter: name, target, field } = filter;
225
+ const on = `Table resource "${source.name}" filters "${name}" on ${target}.${field}`;
226
+ const instead = `filter on a field of "${source.name}", or have the owner of "${target}" answer the ids it matches ` +
227
+ "(an owner API) and filter by them.";
228
+ const system = filter.tables.find((table) => resourceOf(table).ownership === "system");
229
+ if (system && source.ownership !== "system") {
207
230
  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}".`
231
+ `${on}, which reads "${system}", a system table: only its owner's system context reads it, and the filter ` +
232
+ `would read it in the caller's scope, a request's too. Make "${system}" a table the caller's scope guards, or ${instead}`
233
+ );
234
+ }
235
+ const definition = resourceOf(target).schema?.[field];
236
+ if (definition?.hidden === true) {
237
+ throw new TypeError(
238
+ `${on}, a field "${target}" hides: a filter on it would tell a caller who may not read it which rows hold a ` +
239
+ `value. Filter on a field "${target}" shows, or ${instead}`
240
+ );
241
+ }
242
+ if (definition?.indexed !== true) {
243
+ throw new TypeError(
244
+ `${on}, which "${target}" does not declare indexed: true. A cross-table filter reads another table by that field: ` +
245
+ `give the field indexed: true and its column a database index, or filter on a field of "${source.name}".`
211
246
  );
212
247
  }
213
248
  }
@@ -219,8 +254,10 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
219
254
  * narrows another feature's resource whose owner accepts contributions.
220
255
  * @param {string} featureId
221
256
  * @param {ReadonlyArray<object>} owns
257
+ * @param {{ requires?: Readonly<Record<string, unknown>> }} [options] The feature's dependencies, by local name, as its
258
+ * setup receives them (defineFeature passes them): each entry's rowPolicy receives them as `requires`.
222
259
  */
223
- async function own(featureId, owns) {
260
+ async function own(featureId, owns, { requires = NO_REQUIRES } = {}) {
224
261
  const entries = owns.map((entry) => ownedEntry(entry, featureId));
225
262
  const names = new Set();
226
263
  for (const { resource } of entries) {
@@ -231,15 +268,24 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
231
268
  claim(featureId, resource);
232
269
  }
233
270
  const contributions = entries.map(() => []);
271
+ // Filters that read other tables through their owners' join sources (see filterJoinSources.js).
272
+ const searches = entries.map((entry) => filterJoinSources(featureId, entry.resource, entry.searchSchema));
234
273
  const scopes = entries.map((entry, index) => resourceScopeOptions(entry.resource, {
235
274
  writeSerializers: WRITE_SERIALIZERS,
236
275
  normalizeId: entry.normalizeId,
237
- rowPolicy: composedRowPolicy(featureId, entry, contributions[index]),
238
- searchSchema: entry.searchSchema,
276
+ rowPolicy: composedRowPolicy(featureId, entry, contributions[index], requires),
277
+ searchSchema: searches[index].searchSchema,
239
278
  queryFields: entry.queryFields
240
279
  }));
241
280
  checkCrossTableFilters(entries, scopes);
242
281
  const handles = {};
282
+ // A join source's picker gets the feature's dependencies and its own handles, built below before any read.
283
+ const ownerOf = (pick) => pick({ requires, owned: handles });
284
+ for (const [index, { declared }] of searches.entries()) {
285
+ if (declared.length > 0) {
286
+ scopes[index].hooks = joinSourceHooks({ resourceName: entries[index].resource.name, declared, ownerOf });
287
+ }
288
+ }
243
289
  for (const [index, entry] of entries.entries()) {
244
290
  const { resource } = entry;
245
291
  ownedByName.set(resource.name, {
@@ -250,7 +296,8 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
250
296
  });
251
297
  ownerByTable.set(resource.tableName, featureId);
252
298
  await api.addResource(resource.name, scopes[index]);
253
- handles[resource.name] = createResourceHandle({ api, resource, hooks: entry.hooks, settings, resourceNamed: tableResource });
299
+ handles[resource.name] = createResourceHandle({ api, resource, hooks: entry.hooks, settings, resourceNamed: tableResource, handleNamed });
300
+ handleByName.set(resource.name, handles[resource.name]);
254
301
  }
255
302
  Object.defineProperty(handles, "contributeRowPolicy", {
256
303
  value: (name, policy) => contributeRowPolicy(featureId, name, policy),
@@ -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
+ }