@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.
- package/CHANGELOG.md +14 -0
- package/locales/en.json +3 -1
- package/package.json +6 -6
- package/src/server/errors.js +29 -5
- package/src/server/filterJoinSources.js +177 -0
- package/src/server/handleBlobs.js +139 -0
- package/src/server/handleEveryRow.js +188 -0
- package/src/server/handleHidden.js +46 -4
- package/src/server/handleLocks.js +173 -19
- package/src/server/handleRecords.js +16 -3
- package/src/server/index.js +1 -0
- package/src/server/manyRowChannel.js +44 -0
- package/src/server/resourceHandle.js +64 -52
- package/src/server/resourceHost.js +5 -5
- package/src/server/resourceRuntime.js +67 -20
- package/src/server/types.js +5 -0
- package/src/test/expectFlatQueries.js +23 -11
- package/src/test/index.js +2 -2
- package/test/blobFields.mysql.test.js +8 -0
- package/test/blobFields.test.js +8 -0
- package/test/crossTableFilters.mysql.test.js +8 -0
- package/test/crossTableFilters.test.js +8 -0
- package/test/filterJoinSources.mysql.test.js +8 -0
- package/test/filterJoinSources.test.js +8 -0
- package/test/hiddenFields.test.js +41 -0
- package/test/lockIncludes.mysql.test.js +8 -0
- package/test/lockIncludes.test.js +8 -0
- package/test/lockedReads.mysql.test.js +156 -0
- package/test/pagedReads.mysql.test.js +8 -0
- package/test/pagedReads.test.js +8 -0
- package/test/reportsAcrossOwners.mysql.test.js +8 -0
- package/test/reportsAcrossOwners.test.js +8 -0
- package/test/resourceRuntime.test.js +55 -2
- package/test/support/blobFieldsCases.js +226 -0
- package/test/support/crossTableFiltersCases.js +180 -0
- package/test/support/filterJoinSourcesCases.js +256 -0
- package/test/support/lockIncludesCases.js +158 -0
- package/test/support/mysqlDatabase.js +35 -0
- package/test/support/pagedReadsCases.js +168 -0
- package/test/support/reportsAcrossOwnersCases.js +201 -0
- package/test/testHelpers.test.js +128 -3
|
@@ -0,0 +1,168 @@
|
|
|
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 { GroupLimitError, RowLimitError } from "../../src/server/index.js";
|
|
5
|
+
import { createTestResourceRuntime } from "../../src/test/index.js";
|
|
6
|
+
|
|
7
|
+
// Reads larger than one statement answers, on every database the runtime supports: queryPages() and its request row
|
|
8
|
+
// limit, and a grouped aggregate's group limit. 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 WORKSPACE_B = Object.freeze({ workspace: Object.freeze({ id: "2" }) });
|
|
12
|
+
|
|
13
|
+
// Notes whose pages hold 3 rows, as do a grouped aggregate's, and of which a request reads at most 5. json-rest-api's
|
|
14
|
+
// own default page, 2, is smaller than the most a statement answers.
|
|
15
|
+
const noteResource = defineTableResource({
|
|
16
|
+
name: "notes",
|
|
17
|
+
tableName: "notes",
|
|
18
|
+
ownership: "workspace",
|
|
19
|
+
queryDefaultLimit: 2,
|
|
20
|
+
queryMaxLimit: 3,
|
|
21
|
+
schema: {
|
|
22
|
+
workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } },
|
|
23
|
+
title: { type: "string", required: true, search: true },
|
|
24
|
+
status: { type: "string", defaultTo: "open", search: true }
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
async function createNotes(knex) {
|
|
29
|
+
await knex.schema.createTable("notes", (table) => {
|
|
30
|
+
table.increments("id");
|
|
31
|
+
table.integer("workspace_id").nullable();
|
|
32
|
+
table.string("title").notNullable();
|
|
33
|
+
table.string("status").notNullable().defaultTo("open");
|
|
34
|
+
});
|
|
35
|
+
const runtime = await createTestResourceRuntime({ knex, serverPageSize: 3, requestRowLimit: 5 });
|
|
36
|
+
const { notes } = await runtime.own("notes.feature", [noteResource]);
|
|
37
|
+
const system = runtime.declareSystemScope("notes.feature", "settle every workspace's notes")("settle the notes");
|
|
38
|
+
return { notes, system };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function pagesOf(pages) {
|
|
42
|
+
const read = [];
|
|
43
|
+
for await (const records of pages) {
|
|
44
|
+
read.push(records.map(({ title }) => title));
|
|
45
|
+
}
|
|
46
|
+
return read;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
51
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
52
|
+
*/
|
|
53
|
+
function pagedReadsCases(connect) {
|
|
54
|
+
return [
|
|
55
|
+
["queryPages() hands every row over a server page at a time, one statement each, and a write between pages that changes what the filters match skips none", async (t) => {
|
|
56
|
+
const knex = await connect(t, "da_pr_pages");
|
|
57
|
+
const { notes, system } = await createNotes(knex);
|
|
58
|
+
await notes.createMany(Array.from({ length: 7 }, (_, index) => ({ title: `n${index}` })), { context: WORKSPACE_A, returning: "none" });
|
|
59
|
+
await notes.createMany([{ title: "theirs" }], { context: WORKSPACE_B, returning: "none" });
|
|
60
|
+
const job = { context: system.forWorkspace("1") };
|
|
61
|
+
|
|
62
|
+
const { result: pages, count } = await countQueries(knex, () => pagesOf(notes.queryPages({ filters: { status: "open" }, fields: ["title"] }, job)));
|
|
63
|
+
assert.deepEqual(pages, [["n0", "n1", "n2"], ["n3", "n4", "n5"], ["n6"]]);
|
|
64
|
+
assert.equal(count, 3);
|
|
65
|
+
|
|
66
|
+
// A job settles each page as it reads it: the next page starts after the last row read, not at an offset the
|
|
67
|
+
// settled rows moved.
|
|
68
|
+
const settled = await notes.withTransaction(job, async (tx) => {
|
|
69
|
+
const titles = [];
|
|
70
|
+
for await (const records of notes.queryPages({ filters: { status: "open" }, fields: ["title"] }, tx)) {
|
|
71
|
+
await notes.patchWhere({ id: records.map(({ id }) => id) }, { status: "done" }, tx);
|
|
72
|
+
titles.push(...records.map(({ title }) => title));
|
|
73
|
+
}
|
|
74
|
+
return titles;
|
|
75
|
+
});
|
|
76
|
+
assert.deepEqual(settled, ["n0", "n1", "n2", "n3", "n4", "n5", "n6"]);
|
|
77
|
+
assert.deepEqual(await pagesOf(notes.queryPages({ filters: { status: "open" } }, job)), []);
|
|
78
|
+
assert.deepEqual(await pagesOf(notes.queryPages({}, { context: WORKSPACE_B })), [["theirs"]]);
|
|
79
|
+
// A filter that matches no row reads nothing.
|
|
80
|
+
const none = await countQueries(knex, () => pagesOf(notes.queryPages({ filters: { id: [] } }, job)));
|
|
81
|
+
assert.deepEqual([none.result, none.count], [[], 0]);
|
|
82
|
+
}],
|
|
83
|
+
|
|
84
|
+
["queryPages() in a request throws at the request row limit instead of answering the page that passes it; pageLimits() names the limit", async (t) => {
|
|
85
|
+
const knex = await connect(t, "da_pr_limit");
|
|
86
|
+
const { notes } = await createNotes(knex);
|
|
87
|
+
await notes.createMany(Array.from({ length: 7 }, (_, index) => ({ title: `n${index}` })), { context: WORKSPACE_A, returning: "none" });
|
|
88
|
+
assert.deepEqual(notes.pageLimits(), { request: 3, server: 3, requestRows: 5 });
|
|
89
|
+
const read = [];
|
|
90
|
+
await assert.rejects(async () => {
|
|
91
|
+
for await (const records of notes.queryPages({ fields: ["title"] }, { context: WORKSPACE_A })) {
|
|
92
|
+
read.push(records.length);
|
|
93
|
+
}
|
|
94
|
+
}, (error) => error instanceof RowLimitError && error.status === 400 && error.code === "RESOURCE_ROW_LIMIT" &&
|
|
95
|
+
error.messageParams.rowLimit === 5 && /notes\.queryPages\(\) read more than 5 rows inside a request\. .*queryPages\(\) reads them a page at a time/u.test(error.message));
|
|
96
|
+
assert.deepEqual(read, [3]);
|
|
97
|
+
await assert.rejects(notes.queryAll({}, { context: WORKSPACE_A }), /notes\.queryAll\(\) read more than 5 rows/u);
|
|
98
|
+
await assert.rejects(pagesOf(notes.queryPages({ page: { size: 2 } }, { context: WORKSPACE_A })), /notes\.queryPages\(\) does not take page/u);
|
|
99
|
+
}],
|
|
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
|
+
|
|
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) => {
|
|
142
|
+
const knex = await connect(t, "da_pr_groups");
|
|
143
|
+
const { notes } = await createNotes(knex);
|
|
144
|
+
const options = { context: WORKSPACE_A };
|
|
145
|
+
await notes.createMany(["a", "b", "b", "c"].map((status, index) => ({ title: `n${index}`, status })), { ...options, returning: "none" });
|
|
146
|
+
const byStatus = { groupBy: ["status"], measures: { notes: { count: "*" } }, sort: ["status"] };
|
|
147
|
+
|
|
148
|
+
// Three groups, more than json-rest-api's default page of two, in one statement.
|
|
149
|
+
const { result: groups, count } = await countQueries(knex, () => notes.aggregate(byStatus, options));
|
|
150
|
+
assert.deepEqual(groups, [{ status: "a", notes: 1 }, { status: "b", notes: 2 }, { status: "c", notes: 1 }]);
|
|
151
|
+
assert.equal(count, 1);
|
|
152
|
+
|
|
153
|
+
await notes.create({ title: "n4", status: "d" }, { ...options, returning: "none" });
|
|
154
|
+
await assert.rejects(notes.aggregate(byStatus, options), (error) => error instanceof GroupLimitError && error.status === 400 &&
|
|
155
|
+
error.code === "RESOURCE_GROUP_LIMIT" && error.messageCode === "resource.groupLimit" && error.messageParams.groupLimit === 3 &&
|
|
156
|
+
/notes\.aggregate\(\) has more than 3 groups, the most one statement answers\. Read them in pages/u.test(error.message));
|
|
157
|
+
const page = (number) => notes.aggregate({ ...byStatus, page: { size: 2, number } }, options);
|
|
158
|
+
assert.deepEqual((await page(1)).map(({ status }) => status), ["a", "b"]);
|
|
159
|
+
assert.deepEqual((await page(2)).map(({ status }) => status), ["c", "d"]);
|
|
160
|
+
assert.deepEqual(await page(3), []);
|
|
161
|
+
await assert.rejects(notes.aggregate({ ...byStatus, page: { number: 2 } }, options), /notes\.aggregate\(\) page needs size/u);
|
|
162
|
+
// Without groupBy an aggregate is one row, whatever the number of rows.
|
|
163
|
+
assert.deepEqual(await notes.aggregate({ measures: { notes: { count: "*" } } }, options), [{ notes: 5 }]);
|
|
164
|
+
}]
|
|
165
|
+
];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export { pagedReadsCases };
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
// Reports over two owners' rows, on every database the runtime supports: the projects' owner asks which of its
|
|
7
|
+
// projects have, or lack, rows of the tasks' owner, and counts them, each in one statement through the tasks' join
|
|
8
|
+
// source, so the tasks' ownership and row policy decide which tasks count. Each database's test file runs these cases
|
|
9
|
+
// 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, search: true },
|
|
33
|
+
confidential: { type: "boolean", defaultTo: false }
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Workspace 1's projects Alpha (an open and a done task), Beta (a done task, and an open task of workspace 2's that
|
|
39
|
+
* names it) and Gamma (a confidential open task, which only background work sees); workspace 2's Delta (an open task).
|
|
40
|
+
*/
|
|
41
|
+
async function projectsAndTasks(knex) {
|
|
42
|
+
await knex.schema.createTable("projects", (table) => {
|
|
43
|
+
table.increments("id");
|
|
44
|
+
table.integer("workspace_id").nullable();
|
|
45
|
+
table.string("name").notNullable();
|
|
46
|
+
});
|
|
47
|
+
await knex.schema.createTable("tasks", (table) => {
|
|
48
|
+
table.increments("id");
|
|
49
|
+
table.integer("workspace_id").nullable();
|
|
50
|
+
table.integer("project_id").notNullable().index();
|
|
51
|
+
table.string("status").notNullable();
|
|
52
|
+
table.boolean("confidential").notNullable().defaultTo(false);
|
|
53
|
+
});
|
|
54
|
+
await knex("projects").insert([
|
|
55
|
+
{ workspace_id: 1, name: "Alpha" },
|
|
56
|
+
{ workspace_id: 1, name: "Beta" },
|
|
57
|
+
{ workspace_id: 1, name: "Gamma" },
|
|
58
|
+
{ workspace_id: 2, name: "Delta" }
|
|
59
|
+
]);
|
|
60
|
+
await knex("tasks").insert([
|
|
61
|
+
{ workspace_id: 1, project_id: 1, status: "open", confidential: false },
|
|
62
|
+
{ workspace_id: 1, project_id: 1, status: "done", confidential: false },
|
|
63
|
+
{ workspace_id: 1, project_id: 2, status: "done", confidential: false },
|
|
64
|
+
{ workspace_id: 1, project_id: 3, status: "open", confidential: true },
|
|
65
|
+
{ workspace_id: 2, project_id: 4, status: "open", confidential: false },
|
|
66
|
+
{ workspace_id: 2, project_id: 2, status: "open", confidential: false }
|
|
67
|
+
]);
|
|
68
|
+
const runtime = await createTestResourceRuntime({ knex });
|
|
69
|
+
const { projects } = await runtime.own("projects.feature", [projectResource]);
|
|
70
|
+
const { tasks } = await runtime.own("tasks.feature", [{
|
|
71
|
+
resource: taskResource,
|
|
72
|
+
rowPolicy: ({ query, column, caller }) => {
|
|
73
|
+
if (inRequest(caller)) query.where(column("confidential"), false);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}]);
|
|
77
|
+
const job = runtime.declareSystemScope("projects.feature", "review every workspace's projects")("review").forWorkspace("1");
|
|
78
|
+
return { projects, tasks, job: { context: job } };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The projects owner's reports, as its repository holds them, each one statement: `tasks` is the tasks owner's API,
|
|
83
|
+
* of which they use only joinSource().
|
|
84
|
+
*/
|
|
85
|
+
function projectReports({ projects, tasks }) {
|
|
86
|
+
const projectId = projects.column("id", "p");
|
|
87
|
+
// Knex: report - the caller's projects that have a task the caller sees, matching the tasks' filters
|
|
88
|
+
async function withTasks(filters, options) {
|
|
89
|
+
const task = await tasks.joinSource({ alias: "k", filters }, options);
|
|
90
|
+
const { query } = await projects.scopedQuery({ alias: "p" }, options);
|
|
91
|
+
return query
|
|
92
|
+
.whereExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), projectId))
|
|
93
|
+
.select({ name: projects.column("name", "p") })
|
|
94
|
+
.orderBy(projectId);
|
|
95
|
+
}
|
|
96
|
+
// Knex: report - the caller's projects with no task the caller sees
|
|
97
|
+
async function withoutTasks(options) {
|
|
98
|
+
const task = await tasks.joinSource({ alias: "k" }, options);
|
|
99
|
+
const { query } = await projects.scopedQuery({ alias: "p" }, options);
|
|
100
|
+
return query
|
|
101
|
+
.whereNotExists(task.query.select(task.column("id")).whereColumn(task.column("projectId"), projectId))
|
|
102
|
+
.select({ name: projects.column("name", "p") })
|
|
103
|
+
.orderBy(projectId);
|
|
104
|
+
}
|
|
105
|
+
// Knex: totals - each of the caller's projects with how many tasks the caller sees, none counted as 0
|
|
106
|
+
async function taskCounts(options) {
|
|
107
|
+
const task = await tasks.joinSource({ alias: "k" }, options);
|
|
108
|
+
const counted = task.query
|
|
109
|
+
.select({ projectId: task.column("projectId") })
|
|
110
|
+
.count({ tasks: task.column("id") })
|
|
111
|
+
.groupBy(task.column("projectId"))
|
|
112
|
+
.as("c");
|
|
113
|
+
const { query } = await projects.scopedQuery({ alias: "p" }, options);
|
|
114
|
+
const rows = await query
|
|
115
|
+
.leftJoin(counted, "c.projectId", projectId)
|
|
116
|
+
.select({ name: projects.column("name", "p"), tasks: "c.tasks" })
|
|
117
|
+
.orderBy(projectId);
|
|
118
|
+
return rows.map(({ name, tasks: count }) => ({ name, tasks: Number(count ?? 0) }));
|
|
119
|
+
}
|
|
120
|
+
return { withTasks, withoutTasks, taskCounts };
|
|
121
|
+
}
|
|
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
|
+
|
|
155
|
+
const names = (rows) => rows.map(({ name }) => name);
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {(t: import("node:test").TestContext, suffix: string) => Promise<import("knex").Knex>} connect
|
|
159
|
+
* The test's own empty database; `suffix` names it where the database needs a name.
|
|
160
|
+
*/
|
|
161
|
+
function reportsAcrossOwnersCases(connect) {
|
|
162
|
+
return [
|
|
163
|
+
["a report asks, in one statement, which of its rows have or lack another owner's rows, and counts them, through that owner's join source and row policy", async (t) => {
|
|
164
|
+
const knex = await connect(t, "da_ro_exists");
|
|
165
|
+
const handles = await projectsAndTasks(knex);
|
|
166
|
+
const { withTasks, withoutTasks, taskCounts } = projectReports(handles);
|
|
167
|
+
const request = { context: WORKSPACE_A };
|
|
168
|
+
|
|
169
|
+
const open = await countQueries(knex, () => withTasks({ status: "open" }, request));
|
|
170
|
+
// Beta's open task is workspace 2's, and Gamma's is confidential.
|
|
171
|
+
assert.deepEqual([names(open.result), open.count], [["Alpha"], 1]);
|
|
172
|
+
assert.deepEqual(names(await withTasks({ status: "open" }, handles.job)), ["Alpha", "Gamma"]);
|
|
173
|
+
assert.deepEqual(names(await withTasks(undefined, request)), ["Alpha", "Beta"]);
|
|
174
|
+
|
|
175
|
+
const none = await countQueries(knex, () => withoutTasks(request));
|
|
176
|
+
assert.deepEqual([names(none.result), none.count], [["Gamma"], 1]);
|
|
177
|
+
assert.deepEqual(names(await withoutTasks(handles.job)), []);
|
|
178
|
+
|
|
179
|
+
const counts = await countQueries(knex, () => taskCounts(request));
|
|
180
|
+
assert.deepEqual([counts.result, counts.count], [[{ name: "Alpha", tasks: 2 }, { name: "Beta", tasks: 1 }, { name: "Gamma", tasks: 0 }], 1]);
|
|
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 }]);
|
|
197
|
+
}]
|
|
198
|
+
];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export { reportsAcrossOwnersCases };
|
package/test/testHelpers.test.js
CHANGED
|
@@ -97,10 +97,10 @@ test("expectFlatQueries() allows the later chunks a many-row write reports, and
|
|
|
97
97
|
};
|
|
98
98
|
const createInChunks = (options, size) => books.createMany(
|
|
99
99
|
Array.from({ length: size }, (_, index) => ({ title: `Book ${index}` })),
|
|
100
|
-
{ ...options, chunkSize:
|
|
100
|
+
{ ...options, chunkSize: 100 }
|
|
101
101
|
);
|
|
102
|
-
const counts = await expectFlatQueries({ knex, environment, sizes: [3,
|
|
103
|
-
assert.deepEqual(counts.map(({ size, chunkStatements }) => [size, chunkStatements]), [[3, 0], [
|
|
102
|
+
const counts = await expectFlatQueries({ knex, environment, sizes: [3, 300], seed, run: createInChunks });
|
|
103
|
+
assert.deepEqual(counts.map(({ size, chunkStatements }) => [size, chunkStatements]), [[3, 0], [300, 2]]);
|
|
104
104
|
|
|
105
105
|
const oneByOne = async (options, size) => {
|
|
106
106
|
for (let index = 0; index < size; index += 1) {
|
|
@@ -110,6 +110,40 @@ test("expectFlatQueries() allows the later chunks a many-row write reports, and
|
|
|
110
110
|
await assert.rejects(expectFlatQueries({ knex, environment, sizes: [3, 30], seed, run: oneByOne }), /The statements grow with the rows/u);
|
|
111
111
|
});
|
|
112
112
|
|
|
113
|
+
test("expectFlatQueries() counts only the path's own statements and many-row writes, not those of work beside it", async (t) => {
|
|
114
|
+
const { knex, books } = await createShelfFixture(t);
|
|
115
|
+
let workspace = 0;
|
|
116
|
+
const seed = () => {
|
|
117
|
+
workspace += 1;
|
|
118
|
+
return { context: { workspace: { id: String(workspace) } } };
|
|
119
|
+
};
|
|
120
|
+
// Work beside the path, started before it, as another test or a background loop is: woken by the path, it writes
|
|
121
|
+
// row by row and in chunks, as many rows as the path has, while the path waits for it.
|
|
122
|
+
let wake = null;
|
|
123
|
+
const beside = (async () => {
|
|
124
|
+
const options = { context: { workspace: { id: "999" } }, returning: "none" };
|
|
125
|
+
for (;;) {
|
|
126
|
+
const { size, done } = await new Promise((resolve) => { wake = resolve; });
|
|
127
|
+
if (!size) return;
|
|
128
|
+
for (let index = 0; index < size; index += 1) await books.create({ title: `Beside ${index}` }, options);
|
|
129
|
+
await books.createMany(Array.from({ length: size * 10 }, (_, index) => ({ title: `Beside ${index}` })), { ...options, chunkSize: 100 });
|
|
130
|
+
done();
|
|
131
|
+
}
|
|
132
|
+
})();
|
|
133
|
+
const flatPath = async (options, size) => {
|
|
134
|
+
await new Promise((done) => wake({ size, done }));
|
|
135
|
+
return books.queryAll({}, options);
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
const counts = await expectFlatQueries({ knex, environment, sizes: [3, 30], seed, run: flatPath });
|
|
139
|
+
assert.deepEqual(counts.map(({ chunkStatements }) => chunkStatements), [0, 0], "the work beside it wrote 300 rows in 3 chunks");
|
|
140
|
+
assert.equal(counts[0].count, counts[1].count);
|
|
141
|
+
} finally {
|
|
142
|
+
wake({});
|
|
143
|
+
await beside;
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
113
147
|
test("expectScoped() passes a path that keeps to its workspace and fails one that reaches another", async (t) => {
|
|
114
148
|
const { books, systemContext } = await createShelfFixture(t);
|
|
115
149
|
const owners = [{ context: { workspace: { id: "1" } } }, { context: { workspace: { id: "2" } } }];
|
|
@@ -288,3 +322,94 @@ test("startTestFeatures() starts features in the order their requires give, on t
|
|
|
288
322
|
assert.deepEqual(order, ["shelves", "reports", "boot"]);
|
|
289
323
|
assert.deepEqual(resources.ownedTables(), [{ name: "shelves", tableName: "shelves", featureId: "shelves" }]);
|
|
290
324
|
});
|
|
325
|
+
|
|
326
|
+
test("an owned table's row policy receives the capabilities its feature requires, as its setup does", async (t) => {
|
|
327
|
+
const knex = await testKnex(t);
|
|
328
|
+
const shelves = defineTableResource({
|
|
329
|
+
name: "shelves",
|
|
330
|
+
tableName: "shelves",
|
|
331
|
+
ownership: "workspace",
|
|
332
|
+
schema: { workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } }, label: { type: "string", required: true } }
|
|
333
|
+
});
|
|
334
|
+
// What the policy needs from another feature: the labels each person may see, as a membership service answers them.
|
|
335
|
+
const Visibility = defineProvider({
|
|
336
|
+
id: "test.visibility",
|
|
337
|
+
provides: { visibility: "shelves.visibility" },
|
|
338
|
+
setup: () => ({ visibility: Object.freeze({ labelsFor: (userId) => (String(userId) === "7" ? ["fiction"] : []) }) })
|
|
339
|
+
});
|
|
340
|
+
const received = [];
|
|
341
|
+
const ShelvesFeature = defineFeature({
|
|
342
|
+
id: "shelves",
|
|
343
|
+
requires: { visibility: "shelves.visibility" },
|
|
344
|
+
owns: [{
|
|
345
|
+
resource: shelves,
|
|
346
|
+
rowPolicy: ({ query, caller, column, requires }) => {
|
|
347
|
+
received.push(requires);
|
|
348
|
+
if (caller.kind !== "user") return caller.kind !== "anonymous";
|
|
349
|
+
query.whereIn(column("label"), requires.visibility.labelsFor(caller.userId));
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
}],
|
|
353
|
+
systemScope: "add shelves for a test",
|
|
354
|
+
provides: { shelfRecords: "shelves.records" },
|
|
355
|
+
setup: ({ resources, systemContext, visibility }) => ({
|
|
356
|
+
shelfRecords: Object.freeze({
|
|
357
|
+
setupVisibility: visibility,
|
|
358
|
+
add: (label, workspaceId) => resources.shelves.create({ label }, { context: systemContext("add a shelf").forWorkspace(workspaceId), returning: "none" }),
|
|
359
|
+
labels: async (options) => (await resources.shelves.queryAll({}, options)).map(({ label }) => label).sort()
|
|
360
|
+
})
|
|
361
|
+
})
|
|
362
|
+
});
|
|
363
|
+
const { capabilities, stop } = await startTestFeatures({
|
|
364
|
+
knex,
|
|
365
|
+
features: [ShelvesFeature, Visibility],
|
|
366
|
+
requires: { shelfRecords: "shelves.records" },
|
|
367
|
+
createTables: true
|
|
368
|
+
});
|
|
369
|
+
t.after(stop);
|
|
370
|
+
await capabilities.shelfRecords.add("fiction", "1");
|
|
371
|
+
await capabilities.shelfRecords.add("poetry", "1");
|
|
372
|
+
const asPerson = (userId) => ({ context: { actor: { id: userId }, workspace: { id: "1" } } });
|
|
373
|
+
assert.deepEqual(await capabilities.shelfRecords.labels(asPerson("7")), ["fiction"]);
|
|
374
|
+
assert.deepEqual(await capabilities.shelfRecords.labels(asPerson("8")), []);
|
|
375
|
+
assert.deepEqual(Object.keys(received.at(-1)), ["visibility"], "the feature's own dependencies, by local name");
|
|
376
|
+
assert.equal(received.at(-1).visibility, capabilities.shelfRecords.setupVisibility, "the same capability its setup received");
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
test("startTestFeatures() refuses two table owners that require each other's owner APIs, naming the ring, before any setup", async (t) => {
|
|
380
|
+
const knex = await testKnex(t);
|
|
381
|
+
const table = (name) => defineTableResource({
|
|
382
|
+
name,
|
|
383
|
+
tableName: name,
|
|
384
|
+
ownership: "workspace",
|
|
385
|
+
schema: { workspaceId: { type: "id", nullable: true, storage: { column: "workspace_id" } }, label: { type: "string", required: true } }
|
|
386
|
+
});
|
|
387
|
+
const setups = [];
|
|
388
|
+
// The parent's owner reads its children, and the children's owner advances the parent: each requires the other.
|
|
389
|
+
const ParentsFeature = defineFeature({
|
|
390
|
+
id: "parents",
|
|
391
|
+
owns: [table("parents")],
|
|
392
|
+
requires: { children: "children.records" },
|
|
393
|
+
provides: { parents: "parents.records" },
|
|
394
|
+
setup: () => {
|
|
395
|
+
setups.push("parents");
|
|
396
|
+
return { parents: Object.freeze({}) };
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
// An optional require closes a ring as a required one does.
|
|
400
|
+
const ChildrenFeature = defineFeature({
|
|
401
|
+
id: "children",
|
|
402
|
+
owns: [table("children")],
|
|
403
|
+
optional: { parents: "parents.records" },
|
|
404
|
+
provides: { children: "children.records" },
|
|
405
|
+
setup: () => {
|
|
406
|
+
setups.push("children");
|
|
407
|
+
return { children: Object.freeze({}) };
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
await assert.rejects(
|
|
411
|
+
startTestFeatures({ knex, features: [ParentsFeature, ChildrenFeature], createTables: true }),
|
|
412
|
+
{ message: "Provider capability cycle detected: children -> parents -> children." }
|
|
413
|
+
);
|
|
414
|
+
assert.deepEqual(setups, []);
|
|
415
|
+
});
|