@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
@@ -0,0 +1,180 @@
1
+ import assert from "node:assert/strict";
2
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
3
+ import { createTestResourceRuntime } from "../../src/test/index.js";
4
+
5
+ // A search filter that reads another owner's table, on every database the runtime supports: json-rest-api joins that
6
+ // table as the table's own read in the caller's scope, so its ownership, its owner's row policy and the policies
7
+ // contributed to it decide which of its rows a filter can match; own() refuses a filter into a system table or onto a
8
+ // hidden field. Each database's test file runs these cases on its own connection.
9
+
10
+ const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
11
+ // A request hides what only background work may see.
12
+ const inRequest = (caller) => caller.kind === "user" || caller.kind === "anonymous";
13
+
14
+ const supplierResource = defineTableResource({
15
+ name: "suppliers",
16
+ tableName: "suppliers",
17
+ ownership: "workspace",
18
+ searchSchema: { itemName: { type: "string", actualField: "items.name" } },
19
+ relationships: { items: { type: "hasMany", target: "items", foreignKey: "supplierId" } },
20
+ schema: {
21
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
22
+ name: { type: "string", required: true, indexed: true },
23
+ archived: { type: "boolean", defaultTo: false },
24
+ blocked: { type: "boolean", defaultTo: false },
25
+ token: { type: "string", nullable: true, hidden: true, indexed: true }
26
+ }
27
+ });
28
+
29
+ const itemResource = (searchSchema = { supplierName: { type: "string", actualField: "suppliers.name" } }, schema = {}) => defineTableResource({
30
+ name: "items",
31
+ tableName: "items",
32
+ ownership: "workspace",
33
+ searchSchema,
34
+ schema: {
35
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
36
+ name: { type: "string", required: true, indexed: true },
37
+ supplierId: { type: "id", nullable: true, belongsTo: "suppliers", as: "supplier", storage: { column: "supplier_id" } },
38
+ ...schema
39
+ }
40
+ });
41
+
42
+ const vaultResource = defineTableResource({
43
+ name: "vaults",
44
+ tableName: "vaults",
45
+ ownership: "system",
46
+ schema: { code: { type: "string", required: true, indexed: true } }
47
+ });
48
+
49
+ /**
50
+ * Suppliers in workspace 1: Acme, Bolt (archived, which only background work sees) and Crate (blocked by the items
51
+ * feature's contributed policy, for everyone); and an Acme in workspace 2. Workspace 1's items: Hammer twice and
52
+ * Recalled (which only background work sees) from Acme, Nails from Bolt, Box from Crate and Saw from workspace 2's Acme.
53
+ */
54
+ async function suppliersAndItems(knex) {
55
+ await knex.schema.createTable("suppliers", (table) => {
56
+ table.increments("id");
57
+ table.integer("workspace_id").nullable();
58
+ table.string("name").notNullable().index();
59
+ table.boolean("archived").notNullable().defaultTo(false);
60
+ table.boolean("blocked").notNullable().defaultTo(false);
61
+ table.string("token").nullable();
62
+ });
63
+ await knex.schema.createTable("items", (table) => {
64
+ table.increments("id");
65
+ table.integer("workspace_id").nullable();
66
+ table.string("name").notNullable().index();
67
+ table.integer("supplier_id").nullable().index();
68
+ });
69
+ await knex("suppliers").insert([
70
+ { workspace_id: 1, name: "Acme", archived: false, blocked: false },
71
+ { workspace_id: 1, name: "Bolt", archived: true, blocked: false },
72
+ { workspace_id: 2, name: "Acme", archived: false, blocked: false },
73
+ { workspace_id: 1, name: "Crate", archived: false, blocked: true }
74
+ ]);
75
+ await knex("items").insert([
76
+ { workspace_id: 1, name: "Hammer", supplier_id: 1 },
77
+ { workspace_id: 1, name: "Nails", supplier_id: 2 },
78
+ { workspace_id: 1, name: "Saw", supplier_id: 3 },
79
+ { workspace_id: 1, name: "Box", supplier_id: 4 },
80
+ { workspace_id: 1, name: "Hammer", supplier_id: 1 },
81
+ { workspace_id: 1, name: "Recalled", supplier_id: 1 },
82
+ { workspace_id: 2, name: "Drill", supplier_id: 3 }
83
+ ]);
84
+ const runtime = await createTestResourceRuntime({ knex });
85
+ const { suppliers } = await runtime.own("suppliers.feature", [{
86
+ resource: supplierResource,
87
+ acceptsContributions: true,
88
+ rowPolicy: ({ query, column, caller }) => {
89
+ if (inRequest(caller)) query.where(column("archived"), false);
90
+ return true;
91
+ }
92
+ }]);
93
+ const owned = await runtime.own("items.feature", [{
94
+ resource: itemResource(),
95
+ rowPolicy: ({ query, column, caller }) => {
96
+ if (inRequest(caller)) query.whereNot(column("name"), "Recalled");
97
+ return true;
98
+ }
99
+ }]);
100
+ owned.contributeRowPolicy("suppliers", ({ query, column }) => {
101
+ query.where(column("blocked"), false);
102
+ return true;
103
+ });
104
+ const job = runtime.declareSystemScope("items.feature", "restock every workspace")("restock").forWorkspace("1");
105
+ return { suppliers, items: owned.items, job: { context: job } };
106
+ }
107
+
108
+ const names = (records) => records.map(({ name }) => name);
109
+
110
+ /**
111
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
112
+ * The test's own empty database; `suffix` names it where the database needs a name.
113
+ */
114
+ function crossTableFiltersCases(connect) {
115
+ return [
116
+ ["a filter on another owner's table matches only the rows the caller's scope reads there: its ownership, its owner's row policy and the policies contributed to it", async (t) => {
117
+ const knex = await connect(t, "da_xt_scope");
118
+ const { suppliers, items, job } = await suppliersAndItems(knex);
119
+ const request = { context: WORKSPACE_A };
120
+ const itemsOf = async (supplierName, options) => names(await items.queryAll({ filters: { supplierName } }, options));
121
+
122
+ // Workspace 2's Acme is not the caller's, so Saw, which names it, matches no Acme of the caller's.
123
+ assert.deepEqual(await itemsOf("Acme", request), ["Hammer", "Hammer"]);
124
+ assert.deepEqual(await itemsOf("Acme", job), ["Hammer", "Hammer", "Recalled"]);
125
+ // The suppliers' owner shows an archived supplier to background work only.
126
+ assert.deepEqual(await itemsOf("Bolt", request), []);
127
+ assert.deepEqual(await itemsOf("Bolt", job), ["Nails"]);
128
+ // The contributed policy hides a blocked supplier from everyone.
129
+ assert.deepEqual(await itemsOf("Crate", request), []);
130
+ assert.deepEqual(await itemsOf("Crate", job), []);
131
+ // An aggregate filters the same way, counting each item once.
132
+ assert.deepEqual(await items.aggregate({ measures: { items: { count: "*" } }, filters: { supplierName: "Acme" } }, request), [{ items: 2 }]);
133
+ const page = await items.query({ filters: { supplierName: "Acme" }, page: { size: 1 } }, request);
134
+ assert.deepEqual([names(page.records), page.page.hasMore], [["Hammer"], true]);
135
+
136
+ // The other way, a supplier filtered by its items' names: each supplier once, through the items' own scope.
137
+ assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Hammer" } }, request)), ["Acme"]);
138
+ assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Recalled" } }, request)), []);
139
+ assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Recalled" } }, job)), ["Acme"]);
140
+ assert.deepEqual(names(await suppliers.queryAll({ filters: { itemName: "Drill" } }, request)), []);
141
+ }],
142
+
143
+ ["own() refuses a filter that reads a system table from a table that is not one, or a field its owner hides, saying what to do instead", async (t) => {
144
+ const knex = await connect(t, "da_xt_refuse");
145
+ const owning = async (...features) => {
146
+ const runtime = await createTestResourceRuntime({ knex });
147
+ for (const [featureId, owns] of features) {
148
+ await runtime.own(featureId, owns);
149
+ }
150
+ };
151
+ const vaultCode = itemResource({ vaultCode: { type: "string", actualField: "vaults.code" } }, {
152
+ vaultId: { type: "id", nullable: true, belongsTo: "vaults", as: "vault", storage: { column: "vault_id" } }
153
+ });
154
+ await assert.rejects(owning(["vaults.feature", [vaultResource]], ["suppliers.feature", [supplierResource]], ["items.feature", [vaultCode]]), {
155
+ name: "TypeError",
156
+ message: 'Table resource "items" filters "vaultCode" on vaults.code, which reads "vaults", a system table: only its ' +
157
+ "owner's system context reads it, and the filter would read it in the caller's scope, a request's too. Make " +
158
+ '"vaults" a table the caller\'s scope guards, or filter on a field of "items", or have the owner of "vaults" ' +
159
+ "answer the ids it matches (an owner API) and filter by them."
160
+ });
161
+ // The filtering table owned first: the check waits for the table it reads.
162
+ await assert.rejects(owning(["items.feature", [vaultCode]], ["suppliers.feature", [supplierResource]], ["vaults.feature", [vaultResource]]),
163
+ /filters "vaultCode" on vaults\.code, which reads "vaults", a system table/u);
164
+ const supplierToken = itemResource({ supplierToken: { type: "string", actualField: "suppliers.token" } });
165
+ await assert.rejects(owning(["vaults.feature", [vaultResource]], ["suppliers.feature", [supplierResource]], ["items.feature", [supplierToken]]),
166
+ /Table resource "items" filters "supplierToken" on suppliers\.token, a field "suppliers" hides: a filter on it would tell a caller who may not read it which rows hold a value\. Filter on a field "suppliers" shows, or filter on a field of "items"/u);
167
+ // A system table may filter on another: its reads already need a system context.
168
+ const ledgerResource = defineTableResource({
169
+ name: "ledgers",
170
+ tableName: "ledgers",
171
+ ownership: "system",
172
+ searchSchema: { vaultCode: { type: "string", actualField: "vaults.code" } },
173
+ schema: { vaultId: { type: "id", nullable: true, belongsTo: "vaults", as: "vault", storage: { column: "vault_id" } } }
174
+ });
175
+ await owning(["vaults.feature", [vaultResource, ledgerResource]]);
176
+ }]
177
+ ];
178
+ }
179
+
180
+ export { crossTableFiltersCases };
@@ -0,0 +1,256 @@
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
+ // Search filters that read other tables through their owners' join sources, on every database the runtime supports:
7
+ // a plain read (query, queryAll, aggregate) asks which of its rows have, or lack, another owner's rows, or whether any
8
+ // of its own rows match, in its one statement, the other table's ownership, row policy and hidden fields deciding what
9
+ // the filter sees. Each database's test file runs these cases on its own connection.
10
+
11
+ const WORKSPACE_A = Object.freeze({ workspace: Object.freeze({ id: "1" }) });
12
+ // A request hides what only background work may see.
13
+ const inRequest = (caller) => caller.kind === "user" || caller.kind === "anonymous";
14
+
15
+ const projectResource = defineTableResource({
16
+ name: "projects",
17
+ tableName: "projects",
18
+ ownership: "workspace",
19
+ schema: {
20
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
21
+ name: { type: "string", required: true }
22
+ }
23
+ });
24
+
25
+ const taskResource = defineTableResource({
26
+ name: "tasks",
27
+ tableName: "tasks",
28
+ ownership: "workspace",
29
+ schema: {
30
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
31
+ projectId: { type: "id", required: true, storage: { column: "project_id" } },
32
+ status: { type: "string", required: true },
33
+ confidential: { type: "boolean", defaultTo: false },
34
+ reviewNote: { type: "string", nullable: true, hidden: true, storage: { column: "review_note" } }
35
+ }
36
+ });
37
+
38
+ // The tasks' owner's join source, which the projects' feature requires as `tasks`.
39
+ const tasksSource = ({ requires }) => requires.tasks;
40
+
41
+ /**
42
+ * The projects owner's search filters, each reading the tasks through their owner's join source, or the projects
43
+ * themselves through the feature's own handle.
44
+ */
45
+ const projectSearch = Object.freeze({
46
+ // Projects with a task in this status.
47
+ taskStatus: {
48
+ type: "string",
49
+ joinSources: { k: tasksSource },
50
+ applyFilter(query, status, { column, joinSource }) {
51
+ const task = joinSource("k");
52
+ query.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("status"), status));
53
+ }
54
+ },
55
+ // Projects with no task the caller sees (true), or with one (false).
56
+ idle: {
57
+ type: "boolean",
58
+ joinSources: { k: tasksSource },
59
+ applyFilter(query, idle, { column, joinSource }) {
60
+ const task = joinSource("k");
61
+ const tasks = task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id"));
62
+ if (idle) {
63
+ query.whereNotExists(tasks);
64
+ } else {
65
+ query.whereExists(tasks);
66
+ }
67
+ }
68
+ },
69
+ // Projects named like the term; when no project the caller sees is, those with a task in the term's status.
70
+ named: {
71
+ type: "string",
72
+ joinSources: { k: tasksSource, other: ({ owned }) => owned.projects },
73
+ applyFilter(query, term, { column, joinSource }) {
74
+ const other = joinSource("other");
75
+ const task = joinSource("k");
76
+ query.where((match) => match
77
+ .where(column("name"), "like", `%${term}%`)
78
+ .orWhere((fallback) => fallback
79
+ .whereNotExists(other.query.select(other.column("id")).where(other.column("name"), "like", `%${term}%`))
80
+ .whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("status"), term))));
81
+ }
82
+ },
83
+ // A filter on a column the tasks' join source does not carry.
84
+ reviewed: {
85
+ type: "string",
86
+ joinSources: { k: tasksSource },
87
+ applyFilter(query, note, { column, joinSource }) {
88
+ const task = joinSource("k");
89
+ query.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), column("id")).where(task.column("reviewNote"), note));
90
+ }
91
+ }
92
+ });
93
+
94
+ /**
95
+ * Workspace 1's projects Alpha (an open and a done task), Beta (a done task, and an open task of workspace 2's that
96
+ * names it) and Gamma (a confidential open task, which only background work sees); workspace 2's Delta (an open task).
97
+ */
98
+ async function projectsAndTasks(knex) {
99
+ await knex.schema.createTable("projects", (table) => {
100
+ table.increments("id");
101
+ table.integer("workspace_id").nullable().index();
102
+ table.string("name").notNullable();
103
+ });
104
+ await knex.schema.createTable("tasks", (table) => {
105
+ table.increments("id");
106
+ table.integer("workspace_id").nullable();
107
+ table.integer("project_id").notNullable().index();
108
+ table.string("status").notNullable();
109
+ table.boolean("confidential").notNullable().defaultTo(false);
110
+ table.string("review_note").nullable();
111
+ });
112
+ await knex("projects").insert([
113
+ { workspace_id: 1, name: "Alpha" },
114
+ { workspace_id: 1, name: "Beta" },
115
+ { workspace_id: 1, name: "Gamma" },
116
+ { workspace_id: 2, name: "Delta" }
117
+ ]);
118
+ await knex("tasks").insert([
119
+ { workspace_id: 1, project_id: 1, status: "open", confidential: false, review_note: "ok" },
120
+ { workspace_id: 1, project_id: 1, status: "done", confidential: false },
121
+ { workspace_id: 1, project_id: 2, status: "done", confidential: false },
122
+ { workspace_id: 1, project_id: 3, status: "open", confidential: true },
123
+ { workspace_id: 2, project_id: 4, status: "open", confidential: false },
124
+ { workspace_id: 2, project_id: 2, status: "open", confidential: false }
125
+ ]);
126
+ const runtime = await createTestResourceRuntime({ knex });
127
+ const { tasks } = await runtime.own("tasks.feature", [{
128
+ resource: taskResource,
129
+ rowPolicy: ({ query, column, caller }) => {
130
+ if (inRequest(caller)) query.where(column("confidential"), false);
131
+ return true;
132
+ }
133
+ }]);
134
+ const { projects } = await runtime.own("projects.feature", [{ resource: projectResource, searchSchema: projectSearch }], { requires: { tasks } });
135
+ const job = runtime.declareSystemScope("projects.feature", "review every workspace's projects")("review").forWorkspace("1");
136
+ return { runtime, projects, tasks, job: { context: job } };
137
+ }
138
+
139
+ const names = (rows) => rows.map(({ name }) => name);
140
+ const sorted = { sort: ["id"] };
141
+
142
+ /**
143
+ * @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
144
+ * The test's own empty database; `suffix` names it where the database needs a name.
145
+ */
146
+ function filterJoinSourcesCases(connect) {
147
+ return [
148
+ ["a search filter asks, in a plain read's one statement, which of its rows have or lack another owner's rows, through that owner's join source and row policy", async (t) => {
149
+ const knex = await connect(t, "da_fjs_exists");
150
+ const { projects, job } = await projectsAndTasks(knex);
151
+ const request = { context: WORKSPACE_A };
152
+
153
+ const open = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { taskStatus: "open" } }, request));
154
+ // Beta's open task is workspace 2's, and Gamma's is confidential.
155
+ assert.deepEqual([names(open.result), open.count], [["Alpha"], 1]);
156
+ assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { taskStatus: "open" } }, job)), ["Alpha", "Gamma"]);
157
+ assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { taskStatus: "done" } }, request)), ["Alpha", "Beta"]);
158
+
159
+ const idle = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { idle: true } }, request));
160
+ assert.deepEqual([names(idle.result), idle.count], [["Gamma"], 1]);
161
+ assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: true } }, job)), []);
162
+ assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: false } }, request)), ["Alpha", "Beta"]);
163
+
164
+ // A page, an aggregate and a join source take the filter as they take any other.
165
+ const page = await countQueries(knex, () => projects.query({ ...sorted, filters: { idle: false }, page: { size: 1 } }, request));
166
+ assert.deepEqual([names(page.result.records), page.result.page.hasMore, page.count], [["Alpha"], true, 1]);
167
+ const counted = await countQueries(knex, () => projects.aggregate({ measures: { projects: { count: "*" } }, filters: { taskStatus: "done" } }, request));
168
+ assert.deepEqual([counted.result, counted.count], [[{ projects: 2 }], 1]);
169
+ const source = await projects.joinSource({ alias: "p", filters: { idle: true } }, request);
170
+ assert.deepEqual(names(await source.query.select({ name: source.column("name") })), ["Gamma"]);
171
+ const pages = [];
172
+ for await (const records of projects.queryPages({ filters: { taskStatus: "done" } }, request)) {
173
+ pages.push(names(records));
174
+ }
175
+ assert.deepEqual(pages, [["Alpha", "Beta"]]);
176
+ }],
177
+
178
+ ["a search filter asks whether any of the caller's own rows match, through the feature's own handle, and falls back on another owner's rows", async (t) => {
179
+ const knex = await connect(t, "da_fjs_own");
180
+ const { projects } = await projectsAndTasks(knex);
181
+ const request = { context: WORKSPACE_A };
182
+ const read = async (term) => {
183
+ const { result, count } = await countQueries(knex, () => projects.queryAll({ ...sorted, filters: { named: term } }, request));
184
+ return [names(result), count];
185
+ };
186
+ assert.deepEqual(await read("lph"), [["Alpha"], 1]);
187
+ // No project the caller sees is named like "done" (workspace 2's Delta is not either), so the tasks decide.
188
+ assert.deepEqual(await read("done"), [["Alpha", "Beta"], 1]);
189
+ // Delta matches "elt", but it is workspace 2's, so workspace 1's projects fall back on their tasks, of which none
190
+ // is in the status "elt".
191
+ assert.deepEqual(await read("elt"), [[], 1]);
192
+ }],
193
+
194
+ ["a join source in a filter carries no hidden column but the ownership fields, as a report's does", async (t) => {
195
+ const knex = await connect(t, "da_fjs_hidden");
196
+ const { projects, job } = await projectsAndTasks(knex);
197
+ for (const options of [{ context: WORKSPACE_A }, job]) {
198
+ await assert.rejects(projects.queryAll({ filters: { reviewed: "ok" } }, options),
199
+ /tasks\.joinSource\(\) carries no hidden field but its ownership fields, so it has no column for "reviewNote"/u);
200
+ }
201
+ }],
202
+
203
+ ["own() refuses, at startup, join sources it cannot use: no alias map, a name that is no alias, an owner that is no function, a filter with no applyFilter", async (t) => {
204
+ const knex = await connect(t, "da_fjs_startup");
205
+ await knex.schema.createTable("things", (table) => {
206
+ table.increments("id");
207
+ table.integer("workspace_id").nullable();
208
+ table.string("name").notNullable();
209
+ });
210
+ const runtime = await createTestResourceRuntime({ knex });
211
+ const thing = defineTableResource({
212
+ name: "things",
213
+ tableName: "things",
214
+ ownership: "workspace",
215
+ schema: { workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } }, name: { type: "string" } }
216
+ });
217
+ const owning = (entry) => runtime.own("things.feature", [{ resource: thing, searchSchema: { linked: { type: "string", ...entry } } }]);
218
+ const applyFilter = () => {};
219
+ await assert.rejects(owning({ joinSources: {}, applyFilter }), /filter "linked" of "things" joinSources must name each join source by its alias/u);
220
+ await assert.rejects(owning({ joinSources: { "1k": () => null }, applyFilter }), /names the join source "1k", which is no alias/u);
221
+ await assert.rejects(owning({ joinSources: { k: "tasks" }, applyFilter }), /join source "k" must be a function answering its owner/u);
222
+ await assert.rejects(owning({ joinSources: { k: () => null } }), /reads join sources, so it takes an applyFilter\(query, value, \{ column, joinSource \}\) and no oneOf/u);
223
+ // The table resource's own search names no feature to answer its join sources.
224
+ const sharedSearch = defineTableResource({ ...thing, searchSchema: { linked: { type: "string", joinSources: { k: () => null }, applyFilter } } });
225
+ await assert.rejects(runtime.own("things.feature", [sharedSearch]),
226
+ /filter "linked" of "things" names joinSources in the table resource, which names no feature to answer them; give the filter in the owns entry's searchSchema/u);
227
+ // Nothing was owned by the refused calls, so a correct declaration owns the table.
228
+ const { things } = await owning({ joinSources: { k: () => null }, applyFilter });
229
+ await assert.rejects(things.queryAll({ filters: { linked: "x" } }, { context: WORKSPACE_A }), /things filter "linked" join source "k" names no owner with joinSource\(\{ alias \}, options\)/u);
230
+ }],
231
+
232
+ ["a write or a lock that chooses its rows by a join-source filter is refused on MySQL and MariaDB, which read the source from the snapshot; elsewhere it chooses the rows the filter matches", async (t) => {
233
+ const knex = await connect(t, "da_fjs_writes");
234
+ const { projects } = await projectsAndTasks(knex);
235
+ const request = { context: WORKSPACE_A };
236
+ const mysql = knex.client.config.client === "mysql2";
237
+ if (mysql) {
238
+ // A write answers json-rest-api's RestApiWriteError, whose cause is the refusal, as for a filter on another table's field.
239
+ const refused = (method) => (error) => {
240
+ const refusal = error.name === "RestApiWriteError" ? error.cause : error;
241
+ return refusal.name === "RestApiValidationError" &&
242
+ new RegExp(`${method} on 'projects' filters "idle" through another table's join source, which MySQL and MariaDB read from the transaction snapshot`, "u").test(refusal.message);
243
+ };
244
+ await assert.rejects(projects.patchWhere({ idle: true }, { name: "Quiet" }, request), refused("patchWhere"));
245
+ await assert.rejects(projects.withTransaction(request, (tx) => projects.lockWhere({ idle: true }, tx)), refused("lockWhere"));
246
+ assert.deepEqual(names(await projects.queryAll({ ...sorted, filters: { idle: true } }, request)), ["Gamma"]);
247
+ return;
248
+ }
249
+ assert.deepEqual(names(await projects.withTransaction(request, (tx) => projects.lockWhere({ idle: true }, { ...tx, fields: ["name"] }))), ["Gamma"]);
250
+ assert.deepEqual(await projects.patchWhere({ idle: true }, { name: "Quiet" }, { ...request, returning: "ids" }), ["3"]);
251
+ assert.deepEqual(names(await projects.queryAll(sorted, request)), ["Alpha", "Beta", "Quiet"]);
252
+ }]
253
+ ];
254
+ }
255
+
256
+ export { filterJoinSourcesCases };
@@ -0,0 +1,158 @@
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
+ // A locking read's include, on every database the runtime supports: lock, lockMany, lockWhere and claim lock the
7
+ // records their rows name too, after their own rows, through each related table's own handle, and answer them nested
8
+ // as a read's include does. Each 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 inRequest = (caller) => caller.kind === "user" || caller.kind === "anonymous";
12
+
13
+ const yardResource = defineTableResource({
14
+ name: "yards",
15
+ tableName: "yards",
16
+ ownership: "public",
17
+ schema: { name: { type: "string", required: true } }
18
+ });
19
+ const batchResource = defineTableResource({
20
+ name: "batches",
21
+ tableName: "batches",
22
+ ownership: "workspace",
23
+ schema: {
24
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
25
+ yardId: { type: "id", nullable: true, belongsTo: "yards", as: "yard", storage: { column: "yard_id" } },
26
+ stage: { type: "string", required: true },
27
+ archived: { type: "boolean", defaultTo: false },
28
+ grader: { type: "string", nullable: true, hidden: true },
29
+ slots: { type: "array", storage: { virtual: true }, relation: { kind: "collection", namespace: "slots", foreignKey: "batchId" } }
30
+ }
31
+ });
32
+ const slotResource = defineTableResource({
33
+ name: "slots",
34
+ tableName: "slots",
35
+ ownership: "workspace",
36
+ searchSchema: { codes: { type: "array", actualField: "code", filterOperator: "in" } },
37
+ schema: {
38
+ workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
39
+ batchId: { type: "id", nullable: true, belongsTo: "batches", as: "batch", storage: { column: "batch_id" } },
40
+ code: { type: "string", required: true }
41
+ }
42
+ });
43
+
44
+ /**
45
+ * Yard North; workspace 1's batches 1 (drying, at North) and 2 (archived, which only background work sees); its slots
46
+ * A (batch 1), B (batch 2), C (batch 1) and D (no batch).
47
+ */
48
+ async function slotsAndBatches(knex) {
49
+ await knex.schema.createTable("yards", (table) => {
50
+ table.increments("id");
51
+ table.string("name").notNullable();
52
+ });
53
+ await knex.schema.createTable("batches", (table) => {
54
+ table.increments("id");
55
+ table.integer("workspace_id").nullable().index();
56
+ table.integer("yard_id").nullable();
57
+ table.string("stage").notNullable();
58
+ table.boolean("archived").notNullable().defaultTo(false);
59
+ table.string("grader").nullable();
60
+ });
61
+ await knex.schema.createTable("slots", (table) => {
62
+ table.increments("id");
63
+ table.integer("workspace_id").nullable();
64
+ table.integer("batch_id").nullable();
65
+ table.string("code").notNullable();
66
+ table.index(["workspace_id", "code"]);
67
+ });
68
+ await knex("yards").insert({ name: "North" });
69
+ await knex("batches").insert([
70
+ { workspace_id: 1, yard_id: 1, stage: "drying", archived: false, grader: "lee" },
71
+ { workspace_id: 1, yard_id: null, stage: "done", archived: true }
72
+ ]);
73
+ await knex("slots").insert([
74
+ { workspace_id: 1, batch_id: 1, code: "A" },
75
+ { workspace_id: 1, batch_id: 2, code: "B" },
76
+ { workspace_id: 1, batch_id: 1, code: "C" },
77
+ { workspace_id: 1, batch_id: null, code: "D" }
78
+ ]);
79
+ const runtime = await createTestResourceRuntime({ knex });
80
+ const { yards, batches, slots } = await runtime.own("drying.feature", [yardResource, {
81
+ resource: batchResource,
82
+ rowPolicy: ({ query, column, caller }) => {
83
+ if (inRequest(caller)) query.where(column("archived"), false);
84
+ return true;
85
+ }
86
+ }, slotResource]);
87
+ const job = runtime.declareSystemScope("drying.feature", "settle every workspace's batches")("settle").forWorkspace("1");
88
+ return { yards, batches, slots, job: { context: job } };
89
+ }
90
+
91
+ // The tables each statement reads, in order: SELECTs and the locks' own.
92
+ const tablesOf = (queries) => queries.map((sql) => [...sql.matchAll(/from [`"](\w+)[`"]/giu)].map(([, table]) => table)[0]).filter(Boolean);
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 lockIncludesCases(connect) {
99
+ return [
100
+ ["a lock's include answers what a read's include answers, locking each included type once, after the lock's own rows", async (t) => {
101
+ const knex = await connect(t, "da_li_same");
102
+ const { slots } = await slotsAndBatches(knex);
103
+ const request = { context: WORKSPACE_A };
104
+ const ids = ["1", "2", "3", "4"];
105
+ for (const include of [["batch"], ["batch.yard"], "batch.yard"]) {
106
+ const read = await slots.queryAll({ filters: { id: ids }, include }, request);
107
+ const { result: locked, queries } = await countQueries(knex, () => slots.withTransaction(request, (tx) => slots.lockMany(ids, { ...tx, include })));
108
+ assert.deepEqual(locked, read, JSON.stringify(include));
109
+ // The lock, the links it holds, then the batches it names, locked through their own handle; with the yards
110
+ // included, the batches' links too. The yards are read once: their lock, or the check that each batch's yard is
111
+ // one the caller sees, as any read of a batch's yardId makes.
112
+ const reads = tablesOf(queries);
113
+ const seen = `${JSON.stringify(include)}: ${reads.join(", ")}`;
114
+ assert.deepEqual(reads.slice(0, 3), ["slots", "slots", "batches"], seen);
115
+ assert.equal(reads.filter((table) => table === "batches").length, JSON.stringify(include).includes("yard") ? 2 : 1, seen);
116
+ assert.equal(reads.filter((table) => table === "yards").length, 1, seen);
117
+ }
118
+ // A slot of the archived batch reads it as a link the caller may not see, as the read does.
119
+ const [slotB] = await slots.withTransaction(request, (tx) => slots.lockMany(["2"], { ...tx, include: ["batch"] }));
120
+ assert.deepEqual(slotB, { id: "2", workspaceId: 1, batchId: null, batch: undefined, code: "B" });
121
+ }],
122
+
123
+ ["lock, lockWhere and claim include too, with the fields the call names, and background work sees what a request may not", async (t) => {
124
+ const knex = await connect(t, "da_li_calls");
125
+ const { slots, job } = await slotsAndBatches(knex);
126
+ const request = { context: WORKSPACE_A };
127
+ const one = await slots.withTransaction(request, (tx) => slots.lock("1", { ...tx, fields: ["code"], include: ["batch"] }));
128
+ assert.deepEqual(one, { id: "1", code: "A", batchId: "1", batch: { id: "1", workspaceId: 1, yardId: "1", stage: "drying", archived: false } });
129
+ const where = await slots.withTransaction(request, (tx) => slots.lockWhere({ codes: ["B", "C", "D"] }, { ...tx, fields: ["code"], include: "batch" }));
130
+ assert.deepEqual(where.map(({ code, batchId, batch }) => [code, batchId, batch?.stage ?? null]), [["B", null, null], ["C", "1", "drying"], ["D", null, null]]);
131
+ const claimed = await slots.withTransaction(job, (tx) => slots.claim({ filters: { codes: ["B"] }, include: ["batch"] }, { ...tx, fields: ["code"] }));
132
+ assert.deepEqual(claimed.map(({ code, batchId, batch }) => [code, batchId, batch?.stage]), [["B", "2", "done"]]);
133
+ const claimedToo = await slots.withTransaction(job, (tx) => slots.claim({ filters: { codes: ["B"] } }, { ...tx, fields: ["code"], include: ["batch"] }));
134
+ assert.deepEqual(claimedToo, claimed);
135
+ // An included record leaves out its hidden fields, as any read does.
136
+ assert.equal(Object.hasOwn(one.batch, "grader"), false);
137
+ // include: [] includes nothing, as a read's does.
138
+ assert.deepEqual(await slots.withTransaction(request, (tx) => slots.lock("1", { ...tx, fields: ["code"], include: [] })), { id: "1", code: "A" });
139
+ }],
140
+
141
+ ["a lock refuses, before any statement, an include that is no belongs-to relationship, and claim's include named twice", async (t) => {
142
+ const knex = await connect(t, "da_li_refused");
143
+ const { batches, slots } = await slotsAndBatches(knex);
144
+ const request = { context: WORKSPACE_A };
145
+ const { count } = await countQueries(knex, () => batches.withTransaction(request, async (tx) => {
146
+ await assert.rejects(batches.lock("1", { ...tx, include: ["slots"] }),
147
+ /^TypeError: batches\.lock\(\) includes "slots", which is no belongs-to relationship of batches: a lock includes only the records its rows name/u);
148
+ await assert.rejects(slots.lockMany(["1"], { ...tx, include: ["nothing"] }), /slots\.lockMany\(\) includes "nothing", which is no belongs-to relationship/u);
149
+ await assert.rejects(slots.claim({ filters: { codes: ["A"] }, include: ["batch"] }, { ...tx, include: ["batch"] }),
150
+ /slots\.claim\(\) takes include once: in its params or in its options, not both/u);
151
+ }));
152
+ // The transaction's own BEGIN and COMMIT, where the database sends them; no read.
153
+ assert.ok(count <= 2, `statements: ${count}`);
154
+ }]
155
+ ];
156
+ }
157
+
158
+ export { lockIncludesCases };
@@ -0,0 +1,35 @@
1
+ import knexLib from "knex";
2
+ import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
3
+
4
+ // The connection settings the runtime gives mysql2 (BIGINT as text, DATE as text, UTC).
5
+ const RUNTIME_MYSQL = Object.freeze({ supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" });
6
+
7
+ /**
8
+ * A MariaDB/MySQL database of the test's own beside TEST_DB_NAME, dropped after the test. Every connection runs with
9
+ * MariaDB's innodb_snapshot_isolation off, the MariaDB 11.4 default (11.6 turns it on), so a test reads InnoDB's
10
+ * REPEATABLE READ as every supported server does by default; a server without the setting (MySQL) needs nothing.
11
+ * @param {import("node:test").TestContext} context
12
+ * @param {string} suffix The database's name after TEST_DB_NAME's.
13
+ */
14
+ async function ownMysqlDatabase(context, suffix) {
15
+ const name = `${requireTestDatabase(process.env)}_${suffix}`;
16
+ const server = { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
17
+ const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
18
+ const [variables] = await admin.raw("SHOW VARIABLES LIKE 'innodb_snapshot_isolation'");
19
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
20
+ await admin.raw("CREATE DATABASE ??", [name]);
21
+ const setting = variables.length === 0 ? null : "SET SESSION innodb_snapshot_isolation = OFF";
22
+ const knex = knexLib({
23
+ client: "mysql2",
24
+ connection: { ...server, database: name, ...RUNTIME_MYSQL },
25
+ pool: { min: 0, max: 6, ...(setting ? { afterCreate: (connection, done) => connection.query(setting, (error) => done(error, connection)) } : {}) }
26
+ });
27
+ context.after(async () => {
28
+ await knex.destroy();
29
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
30
+ await admin.destroy();
31
+ });
32
+ return knex;
33
+ }
34
+
35
+ export { ownMysqlDatabase };