@jskit-ai/workspaces-core 0.2.43 → 0.2.45
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 +2 -0
- package/migrations/workspaces_core_indexes_by_user.cjs +31 -0
- package/package.json +4 -4
- package/test/indexesByUser.mysql.test.js +4 -0
- package/test/indexesByUser.postgres.test.js +4 -0
- package/test/indexesByUser.test.js +4 -0
- package/test/support/indexesByUserCases.js +210 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A person's workspaces are read through an index on PostgreSQL: the new migration `workspaces_core_indexes_by_user` adds `ix_workspace_memberships_user` (`workspace_memberships.user_id`), which `workspaces.listForUserId` and `workspaces.memberships.listActiveWorkspaceIdsByUserId` read by, and `ix_workspaces_owner` (`workspaces.owner_user_id`), which `workspaces.findPersonalByOwnerUserId` reads by. PostgreSQL indexes no foreign key's columns by itself, so each of those reads scanned every membership or workspace; the memberships' unique `(workspace_id, user_id)` key serves a workspace's members, not a person's workspaces. MariaDB and MySQL already index both columns through their foreign keys' own indexes, so there the migration changes nothing. Run `db:migrate`.
|
|
6
|
+
|
|
5
7
|
- `workspaces.core` gains `memberContext({ workspaceId, userId }, { context: systemContext(reason), trx? })`, the context of one member of one workspace for background work done as that member: a record started for the person it is assigned to, a notification for one recipient, a member's template setup, a submission synced for the person who made it. It is resolved as the member's own request on a `workspace_user` route is, by the same reads (the workspace, the active membership with the owner's ensured, the role's permissions and the settings), now shared with that request's resolution through the directory service's new `resolveMemberWorkspaceContextById(user, workspaceId, options)`, and refused as it is: 404 `workspaces.workspace.notFound` for a missing or deleted workspace, 403 `workspaces.workspace.accessDenied` for a user who is no active member (removed, inactive, never one, or no user), 403 `workspaces.workspace.contextDisabled` without workspaces. The context signs the member in (`actor`, so `resolveActorId` answers them and an action checks their `permissions`), carries `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`, and is no system context or job: request row limits apply, other owners' hidden fields stay hidden and a row policy is told `caller.kind` "user". Only a system context makes one; any other context, a `forWorkspace` job's too, and ids that are no record ids are a TypeError before any statement. An action runs in it with `actions.execute({ actionId, input, context: { ...member, surface: "app" } })` and sees what the member's request on that route sees. JSKIT keeps no disabled flag on users, so it reads no sign-in state: an account its auth provider refuses at sign-in is still resolved.
|
|
6
8
|
- `workspaces.listForSystem({ afterId, limit }, { context: systemContext(reason) })` answers one page of the workspaces that are not deleted, `{ id, slug }` in id order, after `afterId` (from the first when it is null) and at most `limit` (1 to `pageLimits().request`, 100 by default), for a background job that visits every workspace. A page is one statement however many workspaces there are: among 10 workspaces and among 200 alike. Any context that is not a system context, a `forWorkspace` or `forUser` job's included, an `afterId` that is no workspace id and a `limit` out of range are a TypeError before any statement. The workspaces table resource's search gains `idAfter` (`id > value`) for it.
|
|
7
9
|
- An invitation's response carries whatever delivery status its invite mailer answers, such as `held` for an email the application keeps until its email is set up. The create-invite output's `inviteDelivery.status` and the invite assistant tool's `deliveryStatus` allowed only `sent`, `simulated`, `failed` and `mailer_unconfigured`, so an invitation the assistant made through a mailer answering another status was saved and then failed with "Assistant tool output validation failed.", and the API contract did not describe the status it sent. Both are now any non-empty string. `WorkspaceInviteMailer`'s documentation names the statuses the members panel words itself and says it shows the result's `message` for any other.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// A person's workspaces are read by person: their memberships by workspace_memberships.user_id (the workspaces
|
|
2
|
+
// list, an application's "homes of this person") and the workspaces they own by workspaces.owner_user_id (their
|
|
3
|
+
// personal workspace). The memberships' unique (workspace_id, user_id) key serves a workspace's members, not a
|
|
4
|
+
// person's workspaces, so without these indexes each such read scans every membership or workspace.
|
|
5
|
+
//
|
|
6
|
+
// PostgreSQL and SQLite index no foreign key's columns by themselves, so there the migration adds both. InnoDB (MySQL
|
|
7
|
+
// and MariaDB) made an index for each foreign key when the tables were created, named after the key
|
|
8
|
+
// (workspace_memberships_user_id_foreign, workspaces_owner_user_id_foreign), which already serves these reads, so
|
|
9
|
+
// there it adds nothing.
|
|
10
|
+
const INDEXES = Object.freeze([
|
|
11
|
+
Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
|
|
12
|
+
Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
function foreignKeysAreIndexed(knex) {
|
|
16
|
+
return /mysql|maria/iu.test(String(knex.client.config.client));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
exports.up = async function up(knex) {
|
|
20
|
+
if (foreignKeysAreIndexed(knex)) return;
|
|
21
|
+
for (const { table, name, column } of INDEXES) {
|
|
22
|
+
await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
exports.down = async function down(knex) {
|
|
27
|
+
if (foreignKeysAreIndexed(knex)) return;
|
|
28
|
+
for (const { name } of INDEXES) {
|
|
29
|
+
await knex.raw("drop index if exists ??", [name]);
|
|
30
|
+
}
|
|
31
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/workspaces-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.45",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@jskit-ai/resource-core": "0.1.217",
|
|
27
27
|
"@jskit-ai/resource-crud-core": "0.1.219",
|
|
28
|
-
"@jskit-ai/users-core": "0.2.
|
|
28
|
+
"@jskit-ai/users-core": "0.2.45",
|
|
29
29
|
"json-rest-schema": "^1.0.20"
|
|
30
30
|
},
|
|
31
31
|
"description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
|
|
@@ -211,10 +211,10 @@
|
|
|
211
211
|
}
|
|
212
212
|
},
|
|
213
213
|
"peerDependencies": {
|
|
214
|
-
"@jskit-ai/auth-core": "0.2.
|
|
214
|
+
"@jskit-ai/auth-core": "0.2.29",
|
|
215
215
|
"@jskit-ai/database-runtime": "0.1.275",
|
|
216
216
|
"@jskit-ai/http-runtime": "0.2.26",
|
|
217
217
|
"@jskit-ai/kernel": "0.2.26",
|
|
218
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
218
|
+
"@jskit-ai/resource-runtime": "0.2.34"
|
|
219
219
|
}
|
|
220
220
|
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import knexLib from "knex";
|
|
4
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
5
|
+
import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
6
|
+
import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
|
|
7
|
+
import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
|
|
8
|
+
import usersInitial from "../../../users-core/migrations/users_core_generic_initial.cjs";
|
|
9
|
+
import usersUsername from "../../../users-core/migrations/users_core_profile_username.cjs";
|
|
10
|
+
import usersUpdatedAt from "../../../users-core/migrations/users_core_profile_updated_at.cjs";
|
|
11
|
+
import indexesByUser from "../../migrations/workspaces_core_indexes_by_user.cjs";
|
|
12
|
+
import workspacesInitial from "../../migrations/workspaces_core_initial.cjs";
|
|
13
|
+
import workspaceSettingsMigration from "../../migrations/workspaces_core_workspace_settings_single_name_source.cjs";
|
|
14
|
+
import workspaceColorMigration from "../../migrations/workspaces_core_workspaces_drop_color.cjs";
|
|
15
|
+
import { WorkspaceRecordsFeature } from "../../src/test/WorkspaceRecordsFeature.js";
|
|
16
|
+
|
|
17
|
+
// A person's workspaces are read through an index on every dialect: the statements workspaces.listForUserId (their
|
|
18
|
+
// memberships by user_id) and workspaces.findPersonalByOwnerUserId (their workspaces by owner_user_id) send, explained
|
|
19
|
+
// by the database's own planner. On SQLite and PostgreSQL the indexes are workspaces_core_indexes_by_user's; on
|
|
20
|
+
// MariaDB/MySQL they are the ones InnoDB made for the foreign keys, and the migration changes nothing.
|
|
21
|
+
|
|
22
|
+
const EARLIER_MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt, workspacesInitial, workspaceSettingsMigration, workspaceColorMigration];
|
|
23
|
+
const PEOPLE = 60;
|
|
24
|
+
// The index each read uses, by dialect: the migration's own, or InnoDB's for the foreign key.
|
|
25
|
+
const READS = Object.freeze({
|
|
26
|
+
memberships: { table: "workspace_memberships", column: "user_id", sqlite: "ix_workspace_memberships_user", postgres: "ix_workspace_memberships_user", mysql: "workspace_memberships_user_id_foreign" },
|
|
27
|
+
owned: { table: "workspaces", column: "owner_user_id", sqlite: "ix_workspaces_owner", postgres: "ix_workspaces_owner", mysql: "workspaces_owner_user_id_foreign" }
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Each index of `table` with its columns in order.
|
|
31
|
+
async function indexColumns(knex, dialect, table) {
|
|
32
|
+
const columns = new Map();
|
|
33
|
+
const add = (name, column) => columns.set(name, [...(columns.get(name) ?? []), column]);
|
|
34
|
+
if (dialect === "sqlite") {
|
|
35
|
+
for (const { name } of await knex.raw("pragma index_list(??)", [table])) {
|
|
36
|
+
for (const { name: column } of await knex.raw("pragma index_info(??)", [name])) add(name, column);
|
|
37
|
+
}
|
|
38
|
+
} else if (dialect === "postgres") {
|
|
39
|
+
const { rows } = await knex.raw(
|
|
40
|
+
`select index.relname as name, attribute.attname as column from pg_index entry
|
|
41
|
+
join pg_class index on index.oid = entry.indexrelid join pg_class source on source.oid = entry.indrelid
|
|
42
|
+
join pg_namespace space on space.oid = source.relnamespace
|
|
43
|
+
cross join lateral unnest(entry.indkey) with ordinality as key(number, position)
|
|
44
|
+
join pg_attribute attribute on attribute.attrelid = source.oid and attribute.attnum = key.number
|
|
45
|
+
where source.relname = ? and space.nspname = current_schema() order by index.relname, key.position`,
|
|
46
|
+
[table]
|
|
47
|
+
);
|
|
48
|
+
for (const { name, column } of rows) add(name, column);
|
|
49
|
+
} else {
|
|
50
|
+
const [rows] = await knex.raw("show index from ??", [table]);
|
|
51
|
+
for (const row of rows.sort((left, right) => left.Seq_in_index - right.Seq_in_index)) add(row.Key_name, row.Column_name);
|
|
52
|
+
}
|
|
53
|
+
return columns;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The indexes the planner reads for one captured statement. PostgreSQL's planner is told to avoid whole-table scans,
|
|
57
|
+
// which it prefers for tables this small, so its plan shows whether an index can serve the statement.
|
|
58
|
+
async function indexesUsed(knex, dialect, { sql, bindings }) {
|
|
59
|
+
if (dialect === "sqlite") {
|
|
60
|
+
const plan = await knex.raw(`explain query plan ${sql}`, bindings);
|
|
61
|
+
return plan.map(({ detail }) => /USING (?:COVERING )?INDEX (\S+)/u.exec(detail)?.[1]).filter(Boolean);
|
|
62
|
+
}
|
|
63
|
+
if (dialect === "postgres") {
|
|
64
|
+
return knex.transaction(async (trx) => {
|
|
65
|
+
await trx.raw("set local enable_seqscan = off");
|
|
66
|
+
const { rows } = await trx.raw(`explain (format json) ${sql.replace(/\$\d+/gu, "?")}`, bindings);
|
|
67
|
+
const names = [];
|
|
68
|
+
const visit = (node) => {
|
|
69
|
+
if (node["Index Name"]) names.push(node["Index Name"]);
|
|
70
|
+
for (const child of node.Plans ?? []) visit(child);
|
|
71
|
+
};
|
|
72
|
+
visit(rows[0]["QUERY PLAN"][0].Plan);
|
|
73
|
+
return names;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const [plan] = await knex.raw(`explain ${sql}`, bindings);
|
|
77
|
+
return plan.map(({ key }) => key).filter(Boolean);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The statement `read` sends that filters `table` by `column`.
|
|
81
|
+
async function statementOf(knex, table, column, read) {
|
|
82
|
+
const sent = [];
|
|
83
|
+
const listener = (query) => sent.push(query);
|
|
84
|
+
knex.on("query", listener);
|
|
85
|
+
try {
|
|
86
|
+
await read();
|
|
87
|
+
} finally {
|
|
88
|
+
knex.removeListener("query", listener);
|
|
89
|
+
}
|
|
90
|
+
const filter = new RegExp(`\\b${table}\\b[\\s\\S]*\\bwhere\\b[\\s\\S]*\\b${column}\\b`, "u");
|
|
91
|
+
const statement = sent.find(({ sql }) => filter.test(sql));
|
|
92
|
+
assert.ok(statement, `a statement reading ${table} by ${column}, among: ${sent.map(({ sql }) => sql).join(" | ")}`);
|
|
93
|
+
return statement;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// PEOPLE people, each owning a personal workspace and a member of the next person's too.
|
|
97
|
+
async function seed(knex) {
|
|
98
|
+
const tag = (number) => `byuser-${number}`;
|
|
99
|
+
await knex.batchInsert("users", Array.from({ length: PEOPLE }, (_, number) => ({
|
|
100
|
+
auth_provider: "local", auth_provider_user_sid: tag(number), email: `${tag(number)}@example.test`, username: tag(number), display_name: tag(number)
|
|
101
|
+
})), 100);
|
|
102
|
+
const users = await knex("users").select("id", "username").orderBy("id");
|
|
103
|
+
await knex.batchInsert("workspaces", users.map(({ id, username }) => ({ slug: username, name: username, owner_user_id: id, is_personal: true })), 100);
|
|
104
|
+
const workspaces = await knex("workspaces").select("id", "owner_user_id").orderBy("id");
|
|
105
|
+
await knex.batchInsert("workspace_memberships", workspaces.flatMap(({ id }, number) => [
|
|
106
|
+
{ workspace_id: id, user_id: workspaces[number].owner_user_id, role_sid: "owner", status: "active" },
|
|
107
|
+
{ workspace_id: id, user_id: workspaces[(number + 1) % PEOPLE].owner_user_id, role_sid: "member", status: "active" }
|
|
108
|
+
]), 100);
|
|
109
|
+
return users[PEOPLE / 2].id;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Registers the test on the database `open(t)` answers: an empty Knex connection of the test's own, dropped after it.
|
|
114
|
+
* @param {(t: import("node:test").TestContext) => Promise<import("knex").Knex>} open
|
|
115
|
+
* @param {{ dialect: "sqlite" | "postgres" | "mysql", database?: boolean, skip?: string | false }} options
|
|
116
|
+
*/
|
|
117
|
+
function indexesByUserCases(open, { dialect, database = true, skip = false }) {
|
|
118
|
+
test(`a person's memberships and owned workspaces are read through an index (${dialect})`, { skip }, async (t) => {
|
|
119
|
+
if (database) requireTestDatabase(process.env);
|
|
120
|
+
const knex = await open(t);
|
|
121
|
+
for (const migration of EARLIER_MIGRATIONS) await migration.up(knex);
|
|
122
|
+
await indexesByUser.up(knex);
|
|
123
|
+
const person = await seed(knex);
|
|
124
|
+
if (dialect === "postgres") await knex.raw("analyze");
|
|
125
|
+
const { capabilities, stop } = await startTestFeatures({
|
|
126
|
+
knex,
|
|
127
|
+
features: [WorkspaceRecordsFeature, UsersIdentityProvider, UsersExtensionsProvider],
|
|
128
|
+
requires: { workspaces: "workspaces" }
|
|
129
|
+
});
|
|
130
|
+
t.after(stop);
|
|
131
|
+
const reads = {
|
|
132
|
+
memberships: async () => assert.equal((await capabilities.workspaces.listForUserId(person)).length, 2),
|
|
133
|
+
owned: async () => assert.equal((await capabilities.workspaces.findPersonalByOwnerUserId(person)).ownerUserId, String(person))
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
for (const [read, { table, column, [dialect]: index }] of Object.entries(READS)) {
|
|
137
|
+
assert.deepEqual((await indexColumns(knex, dialect, table)).get(index), [column], `${index} indexes ${table}.${column}`);
|
|
138
|
+
const statement = await statementOf(knex, table, column, reads[read]);
|
|
139
|
+
assert.ok((await indexesUsed(knex, dialect, statement)).includes(index), `${statement.sql} reads ${index}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Applied again, it changes nothing; taken back, the migration's own indexes go and InnoDB's stay.
|
|
143
|
+
await indexesByUser.up(knex);
|
|
144
|
+
await indexesByUser.down(knex);
|
|
145
|
+
for (const { table, [dialect]: index } of Object.values(READS)) {
|
|
146
|
+
assert.equal((await indexColumns(knex, dialect, table)).has(index), dialect === "mysql", `${index} after down`);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** An in-memory SQLite database. */
|
|
152
|
+
async function openSqlite(t) {
|
|
153
|
+
const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
|
|
154
|
+
t.after(() => knex.destroy());
|
|
155
|
+
return knex;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function serverOf(defaultPort) {
|
|
159
|
+
return { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || defaultPort, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** A MariaDB/MySQL database named after TEST_DB_NAME with `suffix`, made for the test and dropped after it. */
|
|
163
|
+
function openMysql(suffix) {
|
|
164
|
+
return async (t) => {
|
|
165
|
+
const name = `${requireTestDatabase(process.env)}_${suffix}`;
|
|
166
|
+
const server = { ...serverOf(3306), supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" };
|
|
167
|
+
const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
|
|
168
|
+
const knex = knexLib({ client: "mysql2", connection: { ...server, database: name }, pool: { min: 0, max: 4 } });
|
|
169
|
+
t.after(async () => {
|
|
170
|
+
try {
|
|
171
|
+
await knex.destroy();
|
|
172
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
173
|
+
} finally {
|
|
174
|
+
await admin.destroy();
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
178
|
+
await admin.raw("CREATE DATABASE ??", [name]);
|
|
179
|
+
return knex;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A PostgreSQL schema in TEST_DB_NAME named after it with `suffix`, made for the test and dropped after it. */
|
|
184
|
+
function openPostgres(suffix) {
|
|
185
|
+
return async (t) => {
|
|
186
|
+
const database = requireTestDatabase(process.env);
|
|
187
|
+
const schema = `${database}_${suffix}_${process.pid}`;
|
|
188
|
+
const connection = { ...serverOf(5432), database };
|
|
189
|
+
const admin = knexLib({ client: "pg", connection, pool: { min: 0, max: 1 } });
|
|
190
|
+
const knex = knexLib({ client: "pg", connection, searchPath: [schema], pool: { min: 0, max: 4 } });
|
|
191
|
+
t.after(async () => {
|
|
192
|
+
try {
|
|
193
|
+
await knex.destroy();
|
|
194
|
+
await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
|
|
195
|
+
} finally {
|
|
196
|
+
await admin.destroy();
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
|
|
200
|
+
await admin.raw("CREATE SCHEMA ??", [schema]);
|
|
201
|
+
return knex;
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// A PostgreSQL test on a run for another database, such as CI's MariaDB run, is left to the PostgreSQL run.
|
|
206
|
+
const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "pg"
|
|
207
|
+
? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
|
|
208
|
+
: false;
|
|
209
|
+
|
|
210
|
+
export { POSTGRES_ELSEWHERE, indexesByUserCases, openMysql, openPostgres, openSqlite };
|