@jskit-ai/resource-runtime 0.2.29 → 0.2.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Depends on json-rest-api 3.1.8 exactly (from 3.1.7): a handle's `lockWhere` takes `sort` and `limit` (below); on MySQL and MariaDB a lock or read no longer reads the connection's schema at each call when the client's settings name a database (a `USE` on such a client's connection is not followed); and a read, in any context, reads no to-one link to a table with no ownership, no row policy and no filtering hook of the application's own whose declared foreign key protects it (SQLite still reads it).
6
+ - A row policy's `options.trx` names the transaction its read runs in. A write whose caller named no transaction runs in one json-rest-api opens for it, and its row policy runs inside it (the lookup before a patch, the read-back after a create), where `options.trx` was null: a handle call the policy made with its `options` (an owner API's role check, say) took a second connection, waiting on a one-connection pool until it gave up. It now joins the write's transaction, and the handle accepts it as one a handle opened. A policy that passes its `options` on, as the guide says, needs no change.
7
+ - `lockWhere(filters, { ...txOptions, sort, limit })` locks in an order the caller names and only as many rows as it needs, with json-rest-api 3.1.8. `sort` (fields, `"-field"` for descending, a list or one field) locks and answers the rows in that order, then by id, so two paths that lock overlapping rows take them in one order and wait for each other instead of deadlocking. `limit` (1 to 1,000) locks only the first rows of that order, by id without a `sort`, and lifts the 1,000-row refusal: a lock of one row by a unique key other than its id (`limit: 1`) is one statement, as `lock(id)` is, where PostgreSQL read twice. Without either, `lockWhere` locks as before. On MySQL and MariaDB the index `lockWhere` reads must read the rows in that order (after the ownership columns and the filters' single-value equalities, the sort's columns), or it refuses naming the columns, since InnoDB locks rows in the order it reads them.
5
8
  - Depends on json-rest-api 3.1.7 exactly (from 3.1.6): a handle's `aggregate` reads only the rows it groups. When its filters and row policy join no other table, json-rest-api groups the filtered query as it reads, so the database reads the rows the filters select through their index, however many other rows the table holds; it no longer groups the table's rows whose ids the filtered query selects (`where id in (select id … where <filters>)`), a read MySQL and MariaDB could make over the whole table, and PostgreSQL too on a partitioned table. A filter or row policy that joins another table keeps the id selection, so no row counts twice. Results are unchanged.
6
9
  - Depends on json-rest-api 3.1.6 exactly (from 3.1.5): within one transaction (a handle's `withTransaction`, or a write's own), json-rest-api answers a check of a row a write links to, or of a to-one link a response shows, from the transaction's own earlier check of that row in the same scope (the same ownership, row policy and filter values) under a lock at least as strong, until the transaction sends a statement that could change the answer: an insert or update of a table the check reads, an update of a column a remembered check names (such as `workspace_id`), a delete, a savepoint's rollback, or any other statement. A check that found no row is never remembered, and nothing carries from one transaction to the next. Installing one module (a form and a module, each published from a draft version, every row naming its author and publisher) in one transaction sent 55 statements and now sends 30; 32 modules in one transaction sent 1,698 and now send 836: its checks went from 1,024 to 162, the two users every row names checked twice instead of 480 times, and each module's own new rows 5 times instead of 17 (again only after a write to their table), on MariaDB 11.4 and PostgreSQL alike. `transactionChecks.test.js` (SQLite, and PostgreSQL in CI) and `transactionChecks.mysql.test.js` compare 1 and 32 modules, and show a transaction refusing a row it removed, moved out of the caller's scope or hid, another workspace's or user's row in the same transaction, a row an earlier transaction checked, and every link refused before.
7
10
  - Depends on json-rest-api 3.1.5 exactly (from 3.1.4), from the registry with its published integrity: a read-only builder (a `scopedQuery()`, a join source, a row policy's `ownTable()`) that json-rest-api's own query compiles as a subquery keeps its joins, where 3.1.4 dropped them and the subquery matched more rows than it should (a row policy or filter narrowing with `whereExists` over a joined subquery widened), and `lockByIds`/`lockWhere` take `lockMode: 'share'`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/resource-runtime",
3
- "version": "0.2.29",
3
+ "version": "0.2.30",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -15,9 +15,9 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/resource-core": "0.1.213",
19
- "@jskit-ai/resource-crud-core": "0.1.215",
20
- "json-rest-api": "3.1.7"
18
+ "@jskit-ai/resource-core": "0.1.214",
19
+ "@jskit-ai/resource-crud-core": "0.1.216",
20
+ "json-rest-api": "3.1.8"
21
21
  },
22
22
  "description": "The resource runtime: features own their tables through it and read and write them with scoped handles on json-rest-api.",
23
23
  "jskit": {
@@ -64,7 +64,7 @@
64
64
  }
65
65
  },
66
66
  "peerDependencies": {
67
- "@jskit-ai/database-runtime": "0.1.271",
68
- "@jskit-ai/kernel": "0.2.22"
67
+ "@jskit-ai/database-runtime": "0.1.272",
68
+ "@jskit-ai/kernel": "0.2.23"
69
69
  }
70
70
  }
@@ -258,19 +258,28 @@ function createLockReads({ api, name, resource, jsonRest, readFields, contextOf,
258
258
  }
259
259
 
260
260
  /**
261
- * Locks the caller's rows the filters select until the transaction ends, in id
262
- * order, and answers them; it waits for transactions holding them, so a row that
263
- * starts to match meanwhile is locked too. At most 1,000 rows (RestApiRowLimitError
264
- * past that). It does not lock rows inserted later: unique numbers take a unique
265
- * index, or a counter row taken with lock(). On MySQL it needs an index starting
266
- * with the ownership columns (no owners: with a filtered column), or it refuses.
261
+ * Locks the caller's rows the filters select until the transaction ends and answers them; it waits for
262
+ * transactions holding them, so a row that starts to match meanwhile is locked too. At most 1,000 rows
263
+ * (RestApiRowLimitError past that). It does not lock rows inserted later: unique numbers take a unique index, or a
264
+ * counter row taken with lock(). On MySQL it needs an index starting with the ownership columns (no owners: with a
265
+ * filtered column), or it refuses.
266
+ * Without `sort` or `limit` it locks in id order, on MySQL and MariaDB in the order of that index. `sort` (stored
267
+ * fields, "-" for descending) locks and answers the rows in that order, then by id, so every writer that locks
268
+ * them takes them in one order; `limit` locks only the first `limit` of them (1 to 1,000), by `sort` or else by
269
+ * id: `limit: 1` locks one row by a unique key in one statement, as lock(id) does. On MySQL and MariaDB either
270
+ * needs an index that reads in that order: after the ownership columns and the filters' single-value equalities,
271
+ * the sort's columns.
267
272
  * `fields` reads only the fields the work needs, and `lockMode` picks the lock (see lockMany).
268
273
  * @param {object} filters
269
- * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[] }} options
274
+ * @param {{ context?: object | null, trx: object, fields?: string[], lockMode?: "update" | "noKeyUpdate" | "share", include?: string | string[], sort?: string | string[], limit?: number }} options
270
275
  */
271
276
  async function lockWhere(filters, options) {
272
277
  requireDefinedFilters(name, "lockWhere", filters);
273
- return lockRead("lockWhere", "lockWhere", { filters }, options);
278
+ return lockRead("lockWhere", "lockWhere", {
279
+ filters,
280
+ ...(options.sort === undefined ? {} : { sort: textList(options.sort) }),
281
+ ...(options.limit === undefined ? {} : { limit: options.limit })
282
+ }, options);
274
283
  }
275
284
 
276
285
  /**
@@ -0,0 +1,43 @@
1
+ // The transactions handle calls may carry: those a handle's withTransaction opened (json-rest-api's own, which every
2
+ // handle call inside the work joins), and those a row policy's options name (see policyCallOptions).
3
+ const handleTransactions = new WeakSet();
4
+
5
+ /**
6
+ * Records a transaction a handle's withTransaction opened, for the handle calls inside its work.
7
+ * @param {object} trx
8
+ */
9
+ function trackHandleTransaction(trx) {
10
+ handleTransactions.add(trx);
11
+ }
12
+
13
+ // A call's options.trx, read or write, is one a handle's withTransaction opened, never a raw Knex transaction.
14
+ function requireHandleTransaction(name, options) {
15
+ if (options.trx && !handleTransactions.has(options.trx)) {
16
+ throw new TypeError(
17
+ `${name}: options.trx is not a transaction a handle opened. A raw Knex transaction or savepoint cannot carry ` +
18
+ "handle calls, reads included: run the work in withTransaction(options, work) and pass on the txOptions it gives work."
19
+ );
20
+ }
21
+ }
22
+
23
+ /**
24
+ * A row policy's options: the call's own, with the transaction its read runs in. A write whose caller named no
25
+ * transaction runs in one json-rest-api opens for it, and its row policy runs inside that one (the lookup before a
26
+ * patch, the read-back after a create): the policy's options name it, so the handle calls the policy passes them to
27
+ * join it instead of taking a second connection.
28
+ * @param {Readonly<{ context: object | null, trx: object | null }> | undefined} callOptions The call's own.
29
+ * @param {{ transaction?: object | null }} jsonRestContext The read's json-rest-api context.
30
+ */
31
+ function policyCallOptions(callOptions, jsonRestContext) {
32
+ const own = jsonRestContext.transaction;
33
+ if (!callOptions || callOptions.trx || !own) {
34
+ return callOptions;
35
+ }
36
+ handleTransactions.add(own);
37
+ return Object.freeze({
38
+ ...callOptions,
39
+ trx: own
40
+ });
41
+ }
42
+
43
+ export { policyCallOptions, requireHandleTransaction, trackHandleTransaction };
@@ -8,6 +8,7 @@ import { createEveryRowReads } from "./handleEveryRow.js";
8
8
  import { createHiddenFieldReads, createJoinSource, markHandleFunctions } from "./handleHidden.js";
9
9
  import { createLockReads, lockModeOf } from "./handleLocks.js";
10
10
  import { withCallOptions } from "./filterJoinSources.js";
11
+ import { requireHandleTransaction, trackHandleTransaction } from "./handleTransactions.js";
11
12
  import { MANY_ROW_CHANNEL } from "./manyRowChannel.js";
12
13
  import { findOrCreateRecord, lockOrCreate } from "./lockOrCreate.js";
13
14
  import { valueOnlyRaw } from "./rawExpression.js";
@@ -69,19 +70,6 @@ function reportManyRow(resource, operation, rows, chunkSize) {
69
70
  }
70
71
  }
71
72
 
72
- // The transactions handles opened: json-rest-api's own, which every handle call inside the work joins.
73
- const handleTransactions = new WeakSet();
74
-
75
- // A call's options.trx, read or write, is one a handle's withTransaction opened, never a raw Knex transaction.
76
- function requireHandleTransaction(name, options) {
77
- if (options.trx && !handleTransactions.has(options.trx)) {
78
- throw new TypeError(
79
- `${name}: options.trx is not a transaction a handle opened. A raw Knex transaction or savepoint cannot carry ` +
80
- "handle calls, reads included: run the work in withTransaction(options, work) and pass on the txOptions it gives work."
81
- );
82
- }
83
- }
84
-
85
73
  // Opens a transaction for work. When work throws, json-rest-api rolls the transaction back and the caller gets the
86
74
  // error work threw, with its status and code, reporting the transaction's outcome ("rolledBack") as transactionOutcome
87
75
  // (not enumerable, so its serialized form is unchanged; a frozen error cannot carry it): a caller that retries a lost
@@ -96,7 +84,7 @@ async function openTransaction(api, options, work) {
96
84
  let own = null;
97
85
  try {
98
86
  return await api.transaction(async (trx) => {
99
- handleTransactions.add(trx);
87
+ trackHandleTransaction(trx);
100
88
  try {
101
89
  return await work(Object.freeze({ ...passedOn(options), trx }));
102
90
  } catch (error) {
@@ -5,6 +5,7 @@ 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
7
  import { callOptionsOf, filterJoinSources, joinSourceHooks } from "./filterJoinSources.js";
8
+ import { policyCallOptions } from "./handleTransactions.js";
8
9
  import { createResourceHandle } from "./resourceHandle.js";
9
10
  import { resourceScopeOptions } from "./resourceHost.js";
10
11
 
@@ -176,8 +177,9 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
176
177
 
177
178
  // The owner's policy, then every contribution, each in its own group ANDed with ownership: a policy only narrows.
178
179
  // Each gets who the call runs for as `caller` (see callerOf), its one way to tell: json-rest-api's own `system` flag
179
- // is left out. Each gets the call's own options as `options`, `{ context, trx }` as the caller passed them, to pass
180
- // on to an owner it reads (another owner's joinSource), never one built by hand. The owner's policy also gets the
180
+ // is left out. Each gets the call's own options as `options`, `{ context, trx }` as the caller passed them, with the
181
+ // transaction the read runs in when the caller named none (see policyCallOptions), to pass on to an owner it reads
182
+ // (another owner's joinSource or handle call), never one built by hand. The owner's policy also gets the
181
183
  // owning feature's dependencies as `requires`; a contribution is a function its feature built in setup, with its own.
182
184
  function composedRowPolicy(featureId, entry, contributions, requires) {
183
185
  if (!entry.rowPolicy && !entry.acceptsContributions) {
@@ -187,7 +189,7 @@ function createResourceRuntime({ api, requestRowLimit = DEFAULT_REQUEST_ROW_LIMI
187
189
  const labelOf = (policyFeatureId, policy, relation) =>
188
190
  `Feature "${policyFeatureId}" row policy ${policy.name ? `${policy.name} ` : ""}${relation} "${resourceName}"`;
189
191
  return async function ownedRowPolicy(jsonRestArgs) {
190
- const args = { ...jsonRestArgs, options: callOptionsOf(jsonRestArgs.context) };
192
+ const args = { ...jsonRestArgs, options: policyCallOptions(callOptionsOf(jsonRestArgs.context), jsonRestArgs.context) };
191
193
  delete args.system;
192
194
  const caller = callerOf(args.context);
193
195
  if (entry.rowPolicy) {
@@ -0,0 +1,8 @@
1
+ import test from "node:test";
2
+ import { ownMysqlDatabase } from "./support/mysqlDatabase.js";
3
+ import { lateRequiresCases } from "./support/lateRequiresCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of lateRequiresCases(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 { lateRequiresCases } from "./support/lateRequiresCases.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 lateRequiresCases((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 { lockWhereOrderCases } from "./support/lockWhereOrderCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of lockWhereOrderCases(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 { lockWhereOrderCases } from "./support/lockWhereOrderCases.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 lockWhereOrderCases((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 { policyTransactionCases } from "./support/policyTransactionCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of policyTransactionCases(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 { policyTransactionCases } from "./support/policyTransactionCases.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 policyTransactionCases((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 { storedSourceCases } from "./support/storedSourceCases.js";
4
+
5
+ // MariaDB or MySQL, each case in a database of its own beside TEST_DB_NAME.
6
+ for (const [name, run] of storedSourceCases(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 { storedSourceCases } from "./support/storedSourceCases.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 storedSourceCases((t) => createPackageTestKnex(t, { environment: process.env }))) {
7
+ test(name, run);
8
+ }
@@ -0,0 +1,154 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
5
+ import { startTestFeatures } from "../../src/test/index.js";
6
+
7
+ // A ring a row policy closes, on every database the runtime supports: the audit history's row policy narrows through
8
+ // the evidence owner's join source, while the evidence owner records each change in the audit history. The audit
9
+ // feature late-requires the evidence's owner API, so the kernel starts the ring and resolves it once every feature has
10
+ // booted, and the policy reads it at call time. Each database's test file runs these cases on its own connection.
11
+
12
+ const evidenceFileResource = defineTableResource({
13
+ name: "evidenceFiles",
14
+ tableName: "evidence_files",
15
+ ownership: "workspace",
16
+ schema: {
17
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
18
+ name: { type: "string", required: true },
19
+ withdrawn: { type: "boolean", defaultTo: false }
20
+ }
21
+ });
22
+
23
+ const auditEntryResource = defineTableResource({
24
+ name: "auditEntries",
25
+ tableName: "audit_entries",
26
+ ownership: "workspace",
27
+ schema: {
28
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
29
+ evidenceFileId: { type: "id", required: true, storage: { column: "evidence_file_id" } },
30
+ action: { type: "string", required: true }
31
+ }
32
+ });
33
+
34
+ // A person sees an audit entry only while they see its evidence file, as the evidence owner's join source answers it.
35
+ async function auditEntriesPolicy({ query, caller, column, options, requires }) {
36
+ if (caller.kind !== "user") {
37
+ return caller.kind !== "anonymous";
38
+ }
39
+ const file = await requires.evidence.joinSource({ alias: "ef" }, options);
40
+ query.whereExists(file.query.select(1).whereColumn(file.column("id"), column("evidenceFileId")));
41
+ return true;
42
+ }
43
+
44
+ // A person does not see a withdrawn evidence file.
45
+ function evidenceFilesPolicy({ query, caller, column }) {
46
+ if (caller.kind === "user") {
47
+ query.where(column("withdrawn"), false);
48
+ }
49
+ return true;
50
+ }
51
+
52
+ /**
53
+ * The audit and evidence features. With `plainRing`, the audit feature requires the evidence's owner API as a plain
54
+ * requirement instead of a late one.
55
+ * @param {{ plainRing?: boolean }} [options]
56
+ */
57
+ function auditAndEvidence({ plainRing = false } = {}) {
58
+ const evidenceRequirement = { evidence: "evidence.files" };
59
+ const AuditFeature = defineFeature({
60
+ id: "audit",
61
+ owns: [{ resource: auditEntryResource, rowPolicy: auditEntriesPolicy }],
62
+ ...(plainRing ? { requires: evidenceRequirement } : { late: evidenceRequirement }),
63
+ provides: { history: "audit.history" },
64
+ setup: ({ resources }) => ({
65
+ history: Object.freeze({
66
+ record: (entry, options) => resources.auditEntries.create(entry, { ...options, returning: "none" }),
67
+ actions: async (options) => (await resources.auditEntries.queryAll({ sort: ["id"] }, options)).map(({ action }) => action)
68
+ })
69
+ })
70
+ });
71
+ const EvidenceFeature = defineFeature({
72
+ id: "evidence",
73
+ owns: [{ resource: evidenceFileResource, rowPolicy: evidenceFilesPolicy }],
74
+ systemScope: "file and withdraw evidence for a test's workspaces",
75
+ requires: { history: "audit.history" },
76
+ provides: { files: "evidence.files" },
77
+ setup: ({ resources, systemContext, history }) => {
78
+ const inWorkspace = (workspaceId) => ({ context: systemContext("file evidence").forWorkspace(workspaceId) });
79
+ return {
80
+ files: Object.freeze({
81
+ async add(name, workspaceId) {
82
+ const id = await resources.evidenceFiles.create({ name }, { ...inWorkspace(workspaceId), returning: "id" });
83
+ await history.record({ evidenceFileId: id, action: `added ${name}` }, inWorkspace(workspaceId));
84
+ return id;
85
+ },
86
+ async withdraw(id, name, workspaceId) {
87
+ await resources.evidenceFiles.patch(id, { withdrawn: true }, { ...inWorkspace(workspaceId), returning: "none" });
88
+ await history.record({ evidenceFileId: id, action: `withdrew ${name}` }, inWorkspace(workspaceId));
89
+ },
90
+ joinSource: (request, options) => resources.evidenceFiles.joinSource(request, options)
91
+ })
92
+ };
93
+ }
94
+ });
95
+ return [AuditFeature, EvidenceFeature];
96
+ }
97
+
98
+ async function createTables(knex) {
99
+ await knex.schema.createTable("evidence_files", (table) => {
100
+ table.increments("id");
101
+ table.integer("workspace_id").nullable().index();
102
+ table.string("name").notNullable();
103
+ table.boolean("withdrawn").notNullable().defaultTo(false);
104
+ });
105
+ await knex.schema.createTable("audit_entries", (table) => {
106
+ table.increments("id");
107
+ table.integer("workspace_id").nullable().index();
108
+ table.integer("evidence_file_id").notNullable().index();
109
+ table.string("action").notNullable();
110
+ });
111
+ }
112
+
113
+ const asPerson = (userId, workspaceId) => ({ context: { actor: { id: userId }, workspace: { id: workspaceId } } });
114
+
115
+ /**
116
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
117
+ * The test's own empty database; `suffix` names it where the database needs a name.
118
+ */
119
+ function lateRequiresCases(connect) {
120
+ return [
121
+ ["a row policy that narrows through an owner which requires its own feature starts with a late requirement, and reads only the rows the policy admits", async (t) => {
122
+ const knex = await connect(t, "rr_late_ring");
123
+ await createTables(knex);
124
+
125
+ // The same ring with a plain requirement is refused before any setup.
126
+ await assert.rejects(
127
+ startTestFeatures({ knex, features: auditAndEvidence({ plainRing: true }) }),
128
+ { message: "Provider capability cycle detected: audit -> evidence -> audit." }
129
+ );
130
+
131
+ const { capabilities, resources, stop } = await startTestFeatures({
132
+ knex,
133
+ features: auditAndEvidence(),
134
+ requires: { files: "evidence.files", history: "audit.history" }
135
+ });
136
+ t.after(stop);
137
+ const { files, history } = capabilities;
138
+ await files.add("contract.pdf", "1");
139
+ const photo = await files.add("photo.jpg", "1");
140
+ await files.withdraw(photo, "photo.jpg", "1");
141
+ await files.add("invoice.pdf", "2");
142
+
143
+ // A person in workspace 1 sees the contract's entry, not the withdrawn photo's two, in the read's one statement.
144
+ const read = await countQueries(knex, () => history.actions(asPerson("7", "1")));
145
+ assert.deepEqual([read.result, read.count], [["added contract.pdf"], 1]);
146
+ assert.deepEqual(await history.actions(asPerson("8", "2")), ["added invoice.pdf"]);
147
+ // Background work in workspace 1 sees every entry of its workspace.
148
+ const job = { context: resources.declareSystemScope("test.reader", "check a test's audit entries")("check").forWorkspace("1") };
149
+ assert.deepEqual(await history.actions(job), ["added contract.pdf", "added photo.jpg", "withdrew photo.jpg"]);
150
+ }]
151
+ ];
152
+ }
153
+
154
+ export { lateRequiresCases };
@@ -0,0 +1,101 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
3
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { createTestResourceRuntime } from "../../src/test/index.js";
5
+
6
+ // lockWhere's sort and limit, on every database the runtime supports: the rows are locked in the sort's order, then by
7
+ // id, and limit locks only the first of them, so a lock of one row by its unique key costs what lock(id) costs. Each
8
+ // database's test file runs these cases on its own connection.
9
+
10
+ const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
11
+ const IN_WORKSPACE_A = Object.freeze({ context: WORKSPACE_A });
12
+
13
+ const slotResource = defineTableResource({
14
+ name: "slots",
15
+ tableName: "slots",
16
+ ownership: "workspace",
17
+ searchSchema: { codes: { type: "array", actualField: "code", filterOperator: "in" } },
18
+ schema: {
19
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
20
+ code: { type: "string", required: true, search: true },
21
+ turn: { type: "integer", required: true }
22
+ }
23
+ });
24
+
25
+ const codeOf = (index) => `C${String(index).padStart(4, "0")}`;
26
+
27
+ /** `count` slots in each of workspaces 1 and 2, codes C0000 up, their turns in the codes' reverse order. */
28
+ async function slotsOf(knex, count) {
29
+ await knex.schema.createTable("slots", (table) => {
30
+ table.increments("id");
31
+ table.integer("workspace_id").nullable();
32
+ table.string("code").notNullable();
33
+ table.integer("turn").notNullable();
34
+ table.unique(["workspace_id", "code"]);
35
+ });
36
+ const rows = [1, 2].flatMap((workspace) => Array.from({ length: count }, (_, index) => ({ workspace_id: workspace, code: codeOf(index), turn: count - index })));
37
+ for (let start = 0; start < rows.length; start += 200) {
38
+ await knex("slots").insert(rows.slice(start, start + 200));
39
+ }
40
+ const runtime = await createTestResourceRuntime({ knex });
41
+ const { slots } = await runtime.own("slots.feature", [slotResource]);
42
+ return slots;
43
+ }
44
+
45
+ /**
46
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
47
+ * The test's own empty database; `suffix` names it where the database needs a name.
48
+ */
49
+ function lockWhereOrderCases(connect) {
50
+ return [
51
+ ["lockWhere locks and answers the rows in sort order, then id, and limit takes the first of them", async (t) => {
52
+ const knex = await connect(t, "da_lw_order");
53
+ const slots = await slotsOf(knex, 4);
54
+ const codes = (rows) => rows.map(({ code }) => code);
55
+ const every = { codes: [0, 1, 2, 3].map(codeOf) };
56
+ await slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
57
+ assert.deepEqual(codes(await slots.lockWhere(every, { ...tx, sort: ["-code"] })), ["C0003", "C0002", "C0001", "C0000"]);
58
+ assert.deepEqual(codes(await slots.lockWhere(every, { ...tx, sort: "-code", limit: 2 })), ["C0003", "C0002"]);
59
+ // A limit alone takes the lowest id: one of the unique key's rows is its one row.
60
+ assert.deepEqual(codes(await slots.lockWhere({ code: "C0001" }, { ...tx, limit: 1 })), ["C0001"]);
61
+ assert.deepEqual(await slots.lockWhere({ code: "C9999" }, { ...tx, limit: 1 }), []);
62
+ });
63
+ for (const options of [{ limit: 0 }, { limit: 1001 }, { sort: ["missing"] }]) {
64
+ await assert.rejects(slots.withTransaction(IN_WORKSPACE_A, (tx) => slots.lockWhere(every, { ...tx, ...options })),
65
+ (error) => error.code === "REST_API_VALIDATION", JSON.stringify(options));
66
+ }
67
+ }],
68
+
69
+ ["lockWhere of one row with limit: 1 sends what lock(id) sends, among 4 rows and among 400", async (t) => {
70
+ const costs = [];
71
+ let client;
72
+ for (const count of [4, 400]) {
73
+ const knex = await connect(t, `da_lw_cost_${count}`);
74
+ client = knex.client.config.client;
75
+ const slots = await slotsOf(knex, count);
76
+ const [{ id }] = await knex("slots").where({ workspace_id: 1, code: "C0001" }).select("id");
77
+ const statements = async (lock) => {
78
+ // MySQL and MariaDB read a table's indexes once per process and set of filtered columns: not this measure.
79
+ await slots.withTransaction(IN_WORKSPACE_A, lock);
80
+ return slots.withTransaction(IN_WORKSPACE_A, async (tx) => {
81
+ const { result, count: sent } = await countQueries(knex, () => lock(tx));
82
+ assert.equal([result].flat().length, 1);
83
+ return sent;
84
+ });
85
+ };
86
+ costs.push({
87
+ lock: await statements((tx) => slots.lock(String(id), tx)),
88
+ "lockWhere limit 1": await statements((tx) => slots.lockWhere({ code: "C0001" }, { ...tx, limit: 1 })),
89
+ lockWhere: await statements((tx) => slots.lockWhere({ code: "C0001" }, tx))
90
+ });
91
+ }
92
+ // SQLite's first lock in a transaction takes its write lock first. Without a limit, PostgreSQL reads again
93
+ // under its locks, for rows that started to match while it waited.
94
+ const one = client === "better-sqlite3" ? 2 : 1;
95
+ const expected = { lock: one, "lockWhere limit 1": one, lockWhere: client === "pg" ? 2 : one };
96
+ assert.deepEqual(costs, [expected, expected]);
97
+ }]
98
+ ];
99
+ }
100
+
101
+ export { lockWhereOrderCases };
@@ -0,0 +1,115 @@
1
+ import assert from "node:assert/strict";
2
+ import knexLib from "knex";
3
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
4
+ import { createTestResourceRuntime } from "../../src/test/index.js";
5
+
6
+ // A row policy that asks another owner through its handle, during a write whose caller gave no transaction:
7
+ // json-rest-api opens the write's own, the policy runs inside it (the lookup before a patch, the read-back after a
8
+ // create), and its options name that transaction, so the owner's read joins it. On a client with one connection a read
9
+ // outside it would wait for the connection the write holds until the pool gives up. Each database's test file runs
10
+ // these cases on its own connection.
11
+
12
+ const asPerson = (userId) => ({ context: { actor: { id: userId }, workspace: { id: "1" } } });
13
+
14
+ const memberResource = defineTableResource({
15
+ name: "teamMembers",
16
+ tableName: "team_members",
17
+ ownership: "workspace",
18
+ schema: {
19
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
20
+ userId: { type: "string", required: true, search: true, storage: { column: "user_id" } },
21
+ role: { type: "string", required: true, search: true }
22
+ }
23
+ });
24
+ const taskResource = defineTableResource({
25
+ name: "tasks",
26
+ tableName: "tasks",
27
+ ownership: "workspace",
28
+ schema: {
29
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
30
+ createdBy: { type: "string", required: true, storage: { column: "created_by" } },
31
+ title: { type: "string", required: true }
32
+ }
33
+ });
34
+
35
+ /**
36
+ * A client of `shared`'s database with one connection, which gives up waiting for it after 2 seconds; person 1 a
37
+ * member and person 2 a lead of workspace 1's team; tasks whose policy shows a lead every task and anyone else theirs,
38
+ * asking the teams' owner through its handle. `seen` records whether each of the owner's reads had a transaction.
39
+ * @param {import("knex").Knex} shared
40
+ */
41
+ async function teamsAndTasks(shared) {
42
+ const { config } = shared.client;
43
+ const knex = knexLib({ ...config, pool: { ...config.pool, min: 0, max: 1 }, acquireConnectionTimeout: 2000 });
44
+ await knex.schema.createTable("team_members", (table) => {
45
+ table.increments("id");
46
+ table.integer("workspace_id").nullable().index();
47
+ table.string("user_id").notNullable();
48
+ table.string("role").notNullable();
49
+ });
50
+ await knex.schema.createTable("tasks", (table) => {
51
+ table.increments("id");
52
+ table.integer("workspace_id").nullable().index();
53
+ table.string("created_by").notNullable();
54
+ table.string("title").notNullable();
55
+ });
56
+ await knex("team_members").insert([{ workspace_id: 1, user_id: "1", role: "member" }, { workspace_id: 1, user_id: "2", role: "lead" }]);
57
+ const runtime = await createTestResourceRuntime({ knex });
58
+ const { teamMembers } = await runtime.own("teams.feature", [{ resource: memberResource }]);
59
+ const seen = new Set();
60
+ const teams = {
61
+ async isLead(userId, options) {
62
+ seen.add(options.trx ? "in a transaction" : "in none");
63
+ return (await teamMembers.queryAll({ filters: { userId, role: "lead" }, take: 1 }, options)).length > 0;
64
+ }
65
+ };
66
+ const { tasks } = await runtime.own("tasks.feature", [{
67
+ resource: taskResource,
68
+ rowPolicy: async ({ query, caller, column, value, options, requires }) => {
69
+ if (caller.kind !== "user") {
70
+ return caller.kind !== "anonymous";
71
+ }
72
+ if (!(await requires.teams.isLead(caller.userId, options))) {
73
+ query.where(column("createdBy"), value("createdBy", caller.userId));
74
+ }
75
+ return true;
76
+ }
77
+ }], { requires: { teams } });
78
+ // What one call answers, and where the owner's reads ran during it.
79
+ const call = async (run) => {
80
+ seen.clear();
81
+ const result = await run();
82
+ return { result, seen: [...seen] };
83
+ };
84
+ return { knex, tasks, call };
85
+ }
86
+
87
+ /**
88
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
89
+ * The test's own empty database; `suffix` names it where the database needs a name.
90
+ */
91
+ function policyTransactionCases(connect) {
92
+ return [
93
+ ["a row policy that asks another owner's handle joins the transaction a write opened for a caller that named none", async (t) => {
94
+ const { knex, tasks, call } = await teamsAndTasks(await connect(t, "da_pt"));
95
+ try {
96
+ const inOne = ["in a transaction"];
97
+ const created = await call(() => tasks.create({ createdBy: "1", title: "first" }, asPerson("1")));
98
+ assert.deepEqual({ title: created.result.title, seen: created.seen }, { title: "first", seen: inOne });
99
+ const patched = await call(() => tasks.patch(created.result.id, { title: "second" }, asPerson("1")));
100
+ assert.deepEqual({ title: patched.result.title, seen: patched.seen }, { title: "second", seen: inOne });
101
+ // In the caller's own transaction, as before; and a read outside any reads the owner outside any too.
102
+ const inCallers = await call(() => tasks.withTransaction(asPerson("1"), (tx) => tasks.patch(created.result.id, { title: "third" }, tx)));
103
+ assert.deepEqual(inCallers.seen, inOne);
104
+ const read = await call(() => tasks.queryAll({}, asPerson("2")));
105
+ assert.deepEqual({ titles: read.result.map(({ title }) => title), seen: read.seen }, { titles: ["third"], seen: ["in none"] });
106
+ // The owner's answer still decides: person 3, no lead, made no task.
107
+ assert.deepEqual(await tasks.queryAll({}, asPerson("3")), []);
108
+ } finally {
109
+ await knex.destroy();
110
+ }
111
+ }]
112
+ ];
113
+ }
114
+
115
+ export { policyTransactionCases };
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
3
+ import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
4
+ import { passedOn, resolveWorkspaceScopeValue } from "../../src/server/index.js";
5
+ import { createTestResourceRuntime } from "../../src/test/index.js";
6
+
7
+ // A row policy that reads another owner's rows as stored, on every database the runtime supports: the folders' owner
8
+ // answers its folders to the documents' policy through a join source under its own system scope, narrowed to the call's
9
+ // workspace, so a document in an open folder is visible to a person who may not see the folder itself, and never
10
+ // through another workspace's folder. Each database's test file runs these cases on its own connection.
11
+
12
+ const asPerson = (userId, workspaceId = "1") => ({ context: { actor: { id: userId }, workspace: { id: workspaceId } } });
13
+
14
+ const folderResource = defineTableResource({
15
+ name: "folders",
16
+ tableName: "folders",
17
+ ownership: "workspace",
18
+ schema: {
19
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
20
+ createdBy: { type: "string", required: true, storage: { column: "created_by" } },
21
+ status: { type: "string", required: true }
22
+ }
23
+ });
24
+ const documentResource = defineTableResource({
25
+ name: "documents",
26
+ tableName: "documents",
27
+ ownership: "workspace",
28
+ schema: {
29
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
30
+ folderId: { type: "id", required: true, storage: { column: "folder_id" } },
31
+ title: { type: "string", required: true }
32
+ }
33
+ });
34
+
35
+ /**
36
+ * Workspace 1's folders 1 (open, made by person 2) and 2 (closed, made by person 1), workspace 2's folder 3 (open);
37
+ * `count` documents in each folder of workspace 1 and, in workspace 1, as many naming workspace 2's folder.
38
+ */
39
+ async function foldersAndDocuments(knex, count) {
40
+ await knex.schema.createTable("folders", (table) => {
41
+ table.increments("id");
42
+ table.integer("workspace_id").nullable().index();
43
+ table.string("created_by").notNullable();
44
+ table.string("status").notNullable();
45
+ });
46
+ await knex.schema.createTable("documents", (table) => {
47
+ table.increments("id");
48
+ table.integer("workspace_id").nullable().index();
49
+ table.integer("folder_id").notNullable().index();
50
+ table.string("title").notNullable();
51
+ });
52
+ await knex("folders").insert([
53
+ { workspace_id: 1, created_by: "2", status: "open" },
54
+ { workspace_id: 1, created_by: "1", status: "closed" },
55
+ { workspace_id: 2, created_by: "2", status: "open" }
56
+ ]);
57
+ const documents = [1, 2, 3].flatMap((folderId) => Array.from({ length: count }, (_, index) => ({
58
+ workspace_id: 1, folder_id: folderId, title: `${folderId}-${String(index).padStart(3, "0")}`
59
+ })));
60
+ for (let start = 0; start < documents.length; start += 200) {
61
+ await knex("documents").insert(documents.slice(start, start + 200));
62
+ }
63
+ const runtime = await createTestResourceRuntime({ knex });
64
+ // A person sees the folders they made; background work sees its scope's.
65
+ const { folders } = await runtime.own("folders.feature", [{
66
+ resource: folderResource,
67
+ rowPolicy: ({ query, caller, column, value }) => {
68
+ if (caller.kind === "user") query.where(column("createdBy"), value("createdBy", caller.userId));
69
+ return caller.kind !== "anonymous";
70
+ }
71
+ }]);
72
+ const systemContext = runtime.declareSystemScope("folders.feature", "answer folders as stored to the documents' row policy");
73
+ // The folders' owner API: its folders as stored, in the caller's workspace, for another owner's row policy.
74
+ const folderStatuses = {
75
+ storedSource({ alias }, options) {
76
+ const context = systemContext("the documents' row policy reads each folder's status as stored")
77
+ .forWorkspace(resolveWorkspaceScopeValue(options.context));
78
+ return folders.joinSource({ alias }, { ...passedOn(options), context });
79
+ }
80
+ };
81
+ // A person sees the documents of the open folders, as stored: a folder they may not see counts too.
82
+ const { documents: documentsHandle } = await runtime.own("documents.feature", [{
83
+ resource: documentResource,
84
+ rowPolicy: async ({ query, caller, column, options, requires }) => {
85
+ if (caller.kind !== "user") return caller.kind !== "anonymous";
86
+ const folder = await requires.folders.storedSource({ alias: "f" }, options);
87
+ query.whereExists(folder.query.select(1).whereColumn(folder.column("id"), column("folderId")).where(folder.column("status"), "open"));
88
+ return true;
89
+ }
90
+ }], { requires: { folders: folderStatuses } });
91
+ return { folders, documents: documentsHandle };
92
+ }
93
+
94
+ /**
95
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
96
+ * The test's own empty database; `suffix` names it where the database needs a name.
97
+ */
98
+ function storedSourceCases(connect) {
99
+ return [
100
+ ["a row policy reads another owner's rows as stored in the call's workspace, and a page of them costs one statement among 3 and 300 documents", async (t) => {
101
+ const costs = [];
102
+ for (const count of [3, 300]) {
103
+ const knex = await connect(t, `da_ss_${count}`);
104
+ const { folders, documents } = await foldersAndDocuments(knex, count);
105
+ // Person 1 sees folder 2 only, yet the documents of folder 1, which is open; never those naming workspace 2's
106
+ // open folder 3, and never the closed folder 2's.
107
+ assert.deepEqual((await folders.queryAll({}, asPerson("1"))).map(({ id }) => id), ["2"]);
108
+ const { result, count: statements } = await countQueries(knex, () => documents.queryAll({ take: 20 }, asPerson("1")));
109
+ assert.equal(result.length, Math.min(count, 20));
110
+ assert.deepEqual([...new Set(result.map(({ folderId }) => String(folderId)))], ["1"]);
111
+ // In a transaction the stored read joins the caller's.
112
+ const inTransaction = await documents.withTransaction(asPerson("1"), (tx) => documents.queryAll({ take: 1 }, tx));
113
+ assert.deepEqual(inTransaction.map(({ folderId }) => String(folderId)), ["1"]);
114
+ costs.push(statements);
115
+ }
116
+ assert.deepEqual(costs, [1, 1]);
117
+ }]
118
+ ];
119
+ }
120
+
121
+ export { storedSourceCases };