@jskit-ai/resource-runtime 0.2.18 → 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.
@@ -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 };
@@ -98,6 +98,46 @@ function pagedReadsCases(connect) {
98
98
  await assert.rejects(pagesOf(notes.queryPages({ page: { size: 2 } }, { context: WORKSPACE_A })), /notes\.queryPages\(\) does not take page/u);
99
99
  }],
100
100
 
101
+ ["queryAll() with take answers the first rows in its sort order, reading no row past them, and a request may name more than its row limit", async (t) => {
102
+ const knex = await connect(t, "da_pr_take");
103
+ const { notes, system } = await createNotes(knex);
104
+ await notes.createMany(Array.from({ length: 7 }, (_, index) => ({ title: `n${index}` })), { context: WORKSPACE_A, returning: "none" });
105
+ await notes.createMany([{ title: "theirs" }], { context: WORKSPACE_B, returning: "none" });
106
+ const request = { context: WORKSPACE_A };
107
+ const titles = (records) => records.map(({ title }) => title);
108
+
109
+ // Pages of 3, the last no larger than the rows still wanted: 4 rows in 2 statements, the second asking for 1.
110
+ const four = await countQueries(knex, () => notes.queryAll({ fields: ["title"], take: 4 }, request));
111
+ assert.deepEqual(titles(four.result), ["n0", "n1", "n2", "n3"]);
112
+ assert.equal(four.count, 2);
113
+ // A request reads past its row limit, 5, when take names more; fewer rows than take answer them all.
114
+ assert.deepEqual(titles(await notes.queryAll({ fields: ["title"], take: 7 }, request)), ["n0", "n1", "n2", "n3", "n4", "n5", "n6"]);
115
+ const ten = await countQueries(knex, () => notes.queryAll({ fields: ["title"], take: 10 }, request));
116
+ assert.equal(ten.result.length, 7);
117
+ assert.equal(ten.count, 3);
118
+ // In its sort order, filtered, and in its scope; background work takes too.
119
+ assert.deepEqual(titles(await notes.queryAll({ sort: "-title", fields: ["title"], take: 2 }, request)), ["n6", "n5"]);
120
+ assert.deepEqual(titles(await notes.queryAll({ filters: { title: "n4" }, fields: ["title"], take: 3 }, request)), ["n4"]);
121
+ assert.deepEqual(titles(await notes.queryAll({ fields: ["title"], take: 1 }, { context: WORKSPACE_B })), ["theirs"]);
122
+ assert.deepEqual(titles(await notes.queryAll({ fields: ["title"], take: 2 }, { context: system.forWorkspace("1") })), ["n0", "n1"]);
123
+ // A whole record without fields, as queryAll() answers it.
124
+ assert.deepEqual(await notes.queryAll({ take: 1 }, request), [{ id: "1", workspaceId: 1, title: "n0", status: "open" }]);
125
+ // A filter that matches no row reads nothing.
126
+ const none = await countQueries(knex, () => notes.queryAll({ filters: { id: [] }, take: 3 }, request));
127
+ assert.deepEqual([none.result, none.count], [[], 0]);
128
+ // take is a whole number from 1, checked before anything runs.
129
+ for (const take of [0, -1, 1.5, "3", null]) {
130
+ await assert.rejects(notes.queryAll({ take }, request), (error) => error instanceof TypeError &&
131
+ /^notes\.queryAll\(\) take is the most records it answers, a whole number from 1\./u.test(error.message), String(take));
132
+ }
133
+ // Without take, or with take: undefined, a request still stops at its row limit, and background work reads every row.
134
+ await assert.rejects(notes.queryAll({}, request), /notes\.queryAll\(\) read more than 5 rows/u);
135
+ await assert.rejects(notes.queryAll({ take: undefined }, request), /notes\.queryAll\(\) read more than 5 rows/u);
136
+ assert.equal((await notes.queryAll({ take: undefined }, { context: system.forWorkspace("1") })).length, 7);
137
+ // queryPages() reads a page at a time already, and takes no take.
138
+ await assert.rejects(pagesOf(notes.queryPages({ take: 2 }, request)), /notes\.queryPages\(\) does not take take/u);
139
+ }],
140
+
101
141
  ["a grouped aggregate without a page answers every group one statement holds and throws past them, never part; a page answers its groups", async (t) => {
102
142
  const knex = await connect(t, "da_pr_groups");
103
143
  const { notes } = await createNotes(knex);
@@ -120,6 +120,38 @@ function projectReports({ projects, tasks }) {
120
120
  return { withTasks, withoutTasks, taskCounts };
121
121
  }
122
122
 
123
+ /**
124
+ * A console's reports, in a feature that owns neither table and requires both owners: each roots at the projects'
125
+ * join source and ties the tasks' to it, in one statement.
126
+ */
127
+ function consoleReports({ projects, tasks }) {
128
+ // Knex: report - the caller's projects with no task the caller sees, for a console that owns neither table
129
+ async function idle(options) {
130
+ const project = await projects.joinSource({ alias: "p" }, options);
131
+ const task = await tasks.joinSource({ alias: "k" }, options);
132
+ return project.query
133
+ .whereNotExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), project.column("id")))
134
+ .select({ name: project.column("name") })
135
+ .orderBy(project.column("id"));
136
+ }
137
+ // Knex: totals - each of the caller's projects with how many tasks the caller sees, for a console that owns neither table
138
+ async function counts(options) {
139
+ const project = await projects.joinSource({ alias: "p" }, options);
140
+ const task = await tasks.joinSource({ alias: "k" }, options);
141
+ const counted = task.query
142
+ .select({ projectId: task.column("projectId") })
143
+ .count({ tasks: task.column("id") })
144
+ .groupBy(task.column("projectId"))
145
+ .as("c");
146
+ const rows = await project.query
147
+ .leftJoin(counted, "c.projectId", project.column("id"))
148
+ .select({ name: project.column("name"), tasks: "c.tasks" })
149
+ .orderBy(project.column("id"));
150
+ return rows.map(({ name, tasks: count }) => ({ name, tasks: Number(count ?? 0) }));
151
+ }
152
+ return { idle, counts };
153
+ }
154
+
123
155
  const names = (rows) => rows.map(({ name }) => name);
124
156
 
125
157
  /**
@@ -147,6 +179,21 @@ function reportsAcrossOwnersCases(connect) {
147
179
  const counts = await countQueries(knex, () => taskCounts(request));
148
180
  assert.deepEqual([counts.result, counts.count], [[{ name: "Alpha", tasks: 2 }, { name: "Beta", tasks: 1 }, { name: "Gamma", tasks: 0 }], 1]);
149
181
  assert.deepEqual(await taskCounts(handles.job), [{ name: "Alpha", tasks: 2 }, { name: "Beta", tasks: 1 }, { name: "Gamma", tasks: 1 }]);
182
+ }],
183
+
184
+ ["a console's report, in a feature that owns none of the tables, roots at one owner's join source and ties the others' to it, in one statement", async (t) => {
185
+ const knex = await connect(t, "da_ro_console");
186
+ const handles = await projectsAndTasks(knex);
187
+ const { idle, counts } = consoleReports(handles);
188
+ const request = { context: WORKSPACE_A };
189
+
190
+ const none = await countQueries(knex, () => idle(request));
191
+ assert.deepEqual([names(none.result), none.count], [["Gamma"], 1]);
192
+ assert.deepEqual(names(await idle(handles.job)), []);
193
+
194
+ const counted = await countQueries(knex, () => counts(request));
195
+ assert.deepEqual([counted.result, counted.count], [[{ name: "Alpha", tasks: 2 }, { name: "Beta", tasks: 1 }, { name: "Gamma", tasks: 0 }], 1]);
196
+ assert.deepEqual(await counts(handles.job), [{ name: "Alpha", tasks: 2 }, { name: "Beta", tasks: 1 }, { name: "Gamma", tasks: 1 }]);
150
197
  }]
151
198
  ];
152
199
  }