@jskit-ai/workspaces-core 0.2.44 → 0.2.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A new PostgreSQL or SQLite database migrates again with workspaces-core. In 0.2.80 its first `db:migrate` failed with `migration file "workspaces_core_indexes_by_user.cjs" failed` (`relation "workspace_memberships" does not exist` on PostgreSQL, `no such table` on SQLite): Knex runs a package's migrations in file name order, which put the new index migration before `workspaces_core_initial`, the one that makes the tables. `workspaces_core_indexes_by_user` now does nothing when the tables do not exist yet, and the new `workspaces_core_person_indexes`, which runs after `workspaces_core_initial`, adds `ix_workspace_memberships_user` and `ix_workspaces_owner` when they are missing. A database that already ran `workspaces_core_indexes_by_user` keeps its two indexes, and the new migration adds no second copy. MariaDB and MySQL were not affected and nothing changes there. Run `db:migrate`.
6
+ - Making a workspace (`workspace.workspaces.create`) and changing its name or avatar (`workspace.workspaces.update`) publish an entity change of the workspace itself on `runtime.events`: `type` "entity.changed", `source` "workspace", `entity` "workspace", `operation` "created" or "updated", `entityId` the workspace's id from the action's answer. Before, neither action published anything, so an application keeping its own copy of workspace facts (a directory, an index of names) heard of a member or a settings change but never of a new or renamed workspace. The events carry no realtime delivery; no browser is told.
7
+
8
+ - 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`.
9
+
5
10
  - `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
11
  - `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
12
  - 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,39 @@
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
+ //
11
+ // Knex runs a directory's migrations in file name order, which puts this one before workspaces_core_initial: on a new
12
+ // database the tables do not exist yet when it runs, so it does nothing, and workspaces_core_person_indexes, which runs
13
+ // after workspaces_core_initial, adds the indexes. On a database that already had the tables it adds them, as it always
14
+ // did; every database it ran on is one of those, since on any other it failed.
15
+ const INDEXES = Object.freeze([
16
+ Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
17
+ Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
18
+ ]);
19
+
20
+ function foreignKeysAreIndexed(knex) {
21
+ return /mysql|maria/iu.test(String(knex.client.config.client));
22
+ }
23
+
24
+ exports.up = async function up(knex) {
25
+ if (foreignKeysAreIndexed(knex)) return;
26
+ for (const { table } of INDEXES) {
27
+ if (!(await knex.schema.hasTable(table))) return;
28
+ }
29
+ for (const { table, name, column } of INDEXES) {
30
+ await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
31
+ }
32
+ };
33
+
34
+ exports.down = async function down(knex) {
35
+ if (foreignKeysAreIndexed(knex)) return;
36
+ for (const { name } of INDEXES) {
37
+ await knex.raw("drop index if exists ??", [name]);
38
+ }
39
+ };
@@ -0,0 +1,30 @@
1
+ // The indexes a person's workspaces are read through, as workspaces_core_indexes_by_user describes them:
2
+ // ix_workspace_memberships_user (workspace_memberships.user_id) and ix_workspaces_owner (workspaces.owner_user_id), on
3
+ // PostgreSQL and SQLite. MySQL and MariaDB index both columns through their foreign keys, so there it adds nothing.
4
+ //
5
+ // workspaces_core_indexes_by_user runs before workspaces_core_initial (Knex runs a directory's migrations in file name
6
+ // order), so on a new database it finds no tables and adds nothing; this one runs after workspaces_core_initial and
7
+ // adds them. On a database that had the tables when workspaces_core_indexes_by_user ran, the indexes exist already and
8
+ // this one leaves them as they are.
9
+ const INDEXES = Object.freeze([
10
+ Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
11
+ Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
12
+ ]);
13
+
14
+ function foreignKeysAreIndexed(knex) {
15
+ return /mysql|maria/iu.test(String(knex.client.config.client));
16
+ }
17
+
18
+ exports.up = async function up(knex) {
19
+ if (foreignKeysAreIndexed(knex)) return;
20
+ for (const { table, name, column } of INDEXES) {
21
+ await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
22
+ }
23
+ };
24
+
25
+ exports.down = async function down(knex) {
26
+ if (foreignKeysAreIndexed(knex)) return;
27
+ for (const { name } of INDEXES) {
28
+ await knex.raw("drop index if exists ??", [name]);
29
+ }
30
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.44",
3
+ "version": "0.2.46",
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.44",
28
+ "@jskit-ai/users-core": "0.2.46",
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.",
@@ -215,6 +215,6 @@
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.33"
218
+ "@jskit-ai/resource-runtime": "0.2.34"
219
219
  }
220
220
  }
@@ -1,3 +1,5 @@
1
+ import { jsonApiResultValue } from "@jskit-ai/http-runtime/shared";
2
+ import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
1
3
  import { emptyInputValidator } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
2
4
  import { composeSchemaDefinitions } from "@jskit-ai/kernel/shared/validators";
3
5
  import { workspaceCrud } from "../../shared/resources/workspaceResource.js";
@@ -8,6 +10,15 @@ function workspaceAssistantSummary({ id, slug, name, ownerUserId, avatarUrl }) {
8
10
  return { id, slug, name, ownerUserId, avatarUrl };
9
11
  }
10
12
 
13
+ // A workspace made or changed (its name, its avatar) is an entity change of the workspace itself, for the application's
14
+ // listeners on runtime.events; the workspace's id is the action's answer's.
15
+ const workspaceChanged = (operation) => Object.freeze([createEntityChangedActionEvent({
16
+ source: "workspace",
17
+ entity: "workspace",
18
+ operation,
19
+ entityId: ({ result }) => jsonApiResultValue(result)?.id
20
+ })]);
21
+
11
22
  const workspaceUpdateInputValidator = composeSchemaDefinitions([
12
23
  workspaceSlugParamsValidator,
13
24
  workspaceCrud.operations.patch.body
@@ -37,6 +48,7 @@ function createWorkspaceDirectoryActions({ workspaceService }) {
37
48
  transformResult: (result) => workspaceAssistantSummary(result.value)
38
49
  }
39
50
  },
51
+ events: workspaceChanged("created"),
40
52
  execute: (input, context) => workspaceService.createWorkspaceForAuthenticatedUser(
41
53
  resolveActionUser(context, input),
42
54
  input,
@@ -114,6 +126,7 @@ function createWorkspaceDirectoryActions({ workspaceService }) {
114
126
  transformResult: (result) => workspaceAssistantSummary(result.value)
115
127
  }
116
128
  },
129
+ events: workspaceChanged("updated"),
117
130
  execute: (input, context) => workspaceService.updateWorkspaceForAuthenticatedUser(
118
131
  resolveActionUser(context, input),
119
132
  input.workspaceSlug,
@@ -0,0 +1,6 @@
1
+ import { indexesByUserCases, migrationOrderCases, openMysql } from "./support/indexesByUserCases.js";
2
+
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on MariaDB/MySQL, whose foreign keys' own indexes
4
+ // serve these reads.
5
+ indexesByUserCases(openMysql("ws_by_user"), { dialect: "mysql" });
6
+ migrationOrderCases(openMysql("ws_order"), { dialect: "mysql" });
@@ -0,0 +1,5 @@
1
+ import { POSTGRES_ELSEWHERE, indexesByUserCases, migrationOrderCases, openPostgres } from "./support/indexesByUserCases.js";
2
+
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on PostgreSQL.
4
+ indexesByUserCases(openPostgres("ws_by_user"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
5
+ migrationOrderCases(openPostgres("ws_order"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
@@ -0,0 +1,5 @@
1
+ import { indexesByUserCases, migrationOrderCases, openSqlite } from "./support/indexesByUserCases.js";
2
+
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on SQLite.
4
+ indexesByUserCases(openSqlite, { dialect: "sqlite", database: false });
5
+ migrationOrderCases(openSqlite, { dialect: "sqlite", database: false });
@@ -0,0 +1,281 @@
1
+ import assert from "node:assert/strict";
2
+ import { readdirSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { fileURLToPath } from "node:url";
7
+ import knexLib from "knex";
8
+ import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
9
+ import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
10
+ import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
11
+ import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
12
+ import usersInitial from "../../../users-core/migrations/users_core_generic_initial.cjs";
13
+ import usersUsername from "../../../users-core/migrations/users_core_profile_username.cjs";
14
+ import usersUpdatedAt from "../../../users-core/migrations/users_core_profile_updated_at.cjs";
15
+ import indexesByUser from "../../migrations/workspaces_core_indexes_by_user.cjs";
16
+ import workspacesInitial from "../../migrations/workspaces_core_initial.cjs";
17
+ import workspaceSettingsMigration from "../../migrations/workspaces_core_workspace_settings_single_name_source.cjs";
18
+ import workspaceColorMigration from "../../migrations/workspaces_core_workspaces_drop_color.cjs";
19
+ import { WorkspaceRecordsFeature } from "../../src/test/WorkspaceRecordsFeature.js";
20
+
21
+ // A person's workspaces are read through an index on every dialect: the statements workspaces.listForUserId (their
22
+ // memberships by user_id) and workspaces.findPersonalByOwnerUserId (their workspaces by owner_user_id) send, explained
23
+ // by the database's own planner. On SQLite and PostgreSQL the indexes are workspaces_core_indexes_by_user's; on
24
+ // MariaDB/MySQL they are the ones InnoDB made for the foreign keys, and the migration changes nothing.
25
+
26
+ const EARLIER_MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt, workspacesInitial, workspaceSettingsMigration, workspaceColorMigration];
27
+ const PEOPLE = 60;
28
+ // The index each read uses, by dialect: the migration's own, or InnoDB's for the foreign key.
29
+ const READS = Object.freeze({
30
+ memberships: { table: "workspace_memberships", column: "user_id", sqlite: "ix_workspace_memberships_user", postgres: "ix_workspace_memberships_user", mysql: "workspace_memberships_user_id_foreign" },
31
+ owned: { table: "workspaces", column: "owner_user_id", sqlite: "ix_workspaces_owner", postgres: "ix_workspaces_owner", mysql: "workspaces_owner_user_id_foreign" }
32
+ });
33
+ // The migration directories of users-core and workspaces-core, in the order an application migrates them, each in
34
+ // file name order, as createKnexMigrationConfig has Knex run them.
35
+ const MIGRATION_DIRECTORIES = ["../../../users-core/migrations", "../../migrations"]
36
+ .map((directory) => fileURLToPath(new URL(directory, import.meta.url)));
37
+ const DIRECTORY_MIGRATIONS = Object.freeze({ directory: MIGRATION_DIRECTORIES, extension: "cjs", sortDirsSeparately: true });
38
+ const INDEXES_BY_USER = "workspaces_core_indexes_by_user.cjs";
39
+ const PERSON_INDEXES = "workspaces_core_person_indexes.cjs";
40
+ const require = createRequire(import.meta.url);
41
+
42
+ // Each index of `table` with its columns in order.
43
+ async function indexColumns(knex, dialect, table) {
44
+ const columns = new Map();
45
+ const add = (name, column) => columns.set(name, [...(columns.get(name) ?? []), column]);
46
+ if (dialect === "sqlite") {
47
+ for (const { name } of await knex.raw("pragma index_list(??)", [table])) {
48
+ for (const { name: column } of await knex.raw("pragma index_info(??)", [name])) add(name, column);
49
+ }
50
+ } else if (dialect === "postgres") {
51
+ const { rows } = await knex.raw(
52
+ `select index.relname as name, attribute.attname as column from pg_index entry
53
+ join pg_class index on index.oid = entry.indexrelid join pg_class source on source.oid = entry.indrelid
54
+ join pg_namespace space on space.oid = source.relnamespace
55
+ cross join lateral unnest(entry.indkey) with ordinality as key(number, position)
56
+ join pg_attribute attribute on attribute.attrelid = source.oid and attribute.attnum = key.number
57
+ where source.relname = ? and space.nspname = current_schema() order by index.relname, key.position`,
58
+ [table]
59
+ );
60
+ for (const { name, column } of rows) add(name, column);
61
+ } else {
62
+ const [rows] = await knex.raw("show index from ??", [table]);
63
+ for (const row of rows.sort((left, right) => left.Seq_in_index - right.Seq_in_index)) add(row.Key_name, row.Column_name);
64
+ }
65
+ return columns;
66
+ }
67
+
68
+ // The indexes of `table` on `column` alone.
69
+ async function indexesOn(knex, dialect, table, column) {
70
+ const indexes = [...(await indexColumns(knex, dialect, table))];
71
+ return indexes.filter(([, columns]) => columns.length === 1 && columns[0] === column).map(([name]) => name);
72
+ }
73
+
74
+ // The migrations of a database made before workspaces_core_indexes_by_user existed and then upgraded to the release
75
+ // that added it: every other migration of both directories in Knex's order, then that one. The migrations are named
76
+ // by their files, as Knex names a directory's, so a later run on the directories finds them run.
77
+ function upgradedDatabaseMigrations() {
78
+ const files = MIGRATION_DIRECTORIES.flatMap((directory) =>
79
+ readdirSync(directory).filter((file) => file.endsWith(".cjs")).sort().map((file) => ({ directory, file })));
80
+ return {
81
+ getMigrations: async () => [
82
+ ...files.filter(({ file }) => file !== INDEXES_BY_USER && file !== PERSON_INDEXES),
83
+ files.find(({ file }) => file === INDEXES_BY_USER)
84
+ ],
85
+ getMigrationName: ({ file }) => file,
86
+ getMigration: async ({ directory, file }) => require(path.join(directory, file))
87
+ };
88
+ }
89
+
90
+ // The indexes the planner reads for one captured statement. PostgreSQL's planner is told to avoid whole-table scans,
91
+ // which it prefers for tables this small, so its plan shows whether an index can serve the statement.
92
+ async function indexesUsed(knex, dialect, { sql, bindings }) {
93
+ if (dialect === "sqlite") {
94
+ const plan = await knex.raw(`explain query plan ${sql}`, bindings);
95
+ return plan.map(({ detail }) => /USING (?:COVERING )?INDEX (\S+)/u.exec(detail)?.[1]).filter(Boolean);
96
+ }
97
+ if (dialect === "postgres") {
98
+ return knex.transaction(async (trx) => {
99
+ await trx.raw("set local enable_seqscan = off");
100
+ const { rows } = await trx.raw(`explain (format json) ${sql.replace(/\$\d+/gu, "?")}`, bindings);
101
+ const names = [];
102
+ const visit = (node) => {
103
+ if (node["Index Name"]) names.push(node["Index Name"]);
104
+ for (const child of node.Plans ?? []) visit(child);
105
+ };
106
+ visit(rows[0]["QUERY PLAN"][0].Plan);
107
+ return names;
108
+ });
109
+ }
110
+ const [plan] = await knex.raw(`explain ${sql}`, bindings);
111
+ return plan.map(({ key }) => key).filter(Boolean);
112
+ }
113
+
114
+ // The statement `read` sends that filters `table` by `column`.
115
+ async function statementOf(knex, table, column, read) {
116
+ const sent = [];
117
+ const listener = (query) => sent.push(query);
118
+ knex.on("query", listener);
119
+ try {
120
+ await read();
121
+ } finally {
122
+ knex.removeListener("query", listener);
123
+ }
124
+ const filter = new RegExp(`\\b${table}\\b[\\s\\S]*\\bwhere\\b[\\s\\S]*\\b${column}\\b`, "u");
125
+ const statement = sent.find(({ sql }) => filter.test(sql));
126
+ assert.ok(statement, `a statement reading ${table} by ${column}, among: ${sent.map(({ sql }) => sql).join(" | ")}`);
127
+ return statement;
128
+ }
129
+
130
+ // PEOPLE people, each owning a personal workspace and a member of the next person's too.
131
+ async function seed(knex) {
132
+ const tag = (number) => `byuser-${number}`;
133
+ await knex.batchInsert("users", Array.from({ length: PEOPLE }, (_, number) => ({
134
+ auth_provider: "local", auth_provider_user_sid: tag(number), email: `${tag(number)}@example.test`, username: tag(number), display_name: tag(number)
135
+ })), 100);
136
+ const users = await knex("users").select("id", "username").orderBy("id");
137
+ await knex.batchInsert("workspaces", users.map(({ id, username }) => ({ slug: username, name: username, owner_user_id: id, is_personal: true })), 100);
138
+ const workspaces = await knex("workspaces").select("id", "owner_user_id").orderBy("id");
139
+ await knex.batchInsert("workspace_memberships", workspaces.flatMap(({ id }, number) => [
140
+ { workspace_id: id, user_id: workspaces[number].owner_user_id, role_sid: "owner", status: "active" },
141
+ { workspace_id: id, user_id: workspaces[(number + 1) % PEOPLE].owner_user_id, role_sid: "member", status: "active" }
142
+ ]), 100);
143
+ return users[PEOPLE / 2].id;
144
+ }
145
+
146
+ /**
147
+ * Registers the test on the database `open(t)` answers: an empty Knex connection of the test's own, dropped after it.
148
+ * @param {(t: import("node:test").TestContext) => Promise<import("knex").Knex>} open
149
+ * @param {{ dialect: "sqlite" | "postgres" | "mysql", database?: boolean, skip?: string | false }} options
150
+ */
151
+ function indexesByUserCases(open, { dialect, database = true, skip = false }) {
152
+ test(`a person's memberships and owned workspaces are read through an index (${dialect})`, { skip }, async (t) => {
153
+ if (database) requireTestDatabase(process.env);
154
+ const knex = await open(t);
155
+ for (const migration of EARLIER_MIGRATIONS) await migration.up(knex);
156
+ await indexesByUser.up(knex);
157
+ const person = await seed(knex);
158
+ if (dialect === "postgres") await knex.raw("analyze");
159
+ const { capabilities, stop } = await startTestFeatures({
160
+ knex,
161
+ features: [WorkspaceRecordsFeature, UsersIdentityProvider, UsersExtensionsProvider],
162
+ requires: { workspaces: "workspaces" }
163
+ });
164
+ t.after(stop);
165
+ const reads = {
166
+ memberships: async () => assert.equal((await capabilities.workspaces.listForUserId(person)).length, 2),
167
+ owned: async () => assert.equal((await capabilities.workspaces.findPersonalByOwnerUserId(person)).ownerUserId, String(person))
168
+ };
169
+
170
+ for (const [read, { table, column, [dialect]: index }] of Object.entries(READS)) {
171
+ assert.deepEqual((await indexColumns(knex, dialect, table)).get(index), [column], `${index} indexes ${table}.${column}`);
172
+ const statement = await statementOf(knex, table, column, reads[read]);
173
+ assert.ok((await indexesUsed(knex, dialect, statement)).includes(index), `${statement.sql} reads ${index}`);
174
+ }
175
+
176
+ // Applied again, it changes nothing; taken back, the migration's own indexes go and InnoDB's stay.
177
+ await indexesByUser.up(knex);
178
+ await indexesByUser.down(knex);
179
+ for (const { table, [dialect]: index } of Object.values(READS)) {
180
+ assert.equal((await indexColumns(knex, dialect, table)).has(index), dialect === "mysql", `${index} after down`);
181
+ }
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Registers the tests of the migrations as Knex runs them, on the empty database `open(t)` answers: a new database
187
+ * migrated from nothing, and one that ran workspaces_core_indexes_by_user after workspaces_core_initial. Each ends with
188
+ * `ix_workspace_memberships_user` and `ix_workspaces_owner` (InnoDB's foreign key indexes on MariaDB/MySQL), each the
189
+ * one index on its column.
190
+ * @param {(t: import("node:test").TestContext) => Promise<import("knex").Knex>} open
191
+ * @param {{ dialect: "sqlite" | "postgres" | "mysql", database?: boolean, skip?: string | false }} options
192
+ */
193
+ function migrationOrderCases(open, { dialect, database = true, skip = false }) {
194
+ async function indexedOnce(knex) {
195
+ for (const { table, column, [dialect]: index } of Object.values(READS)) {
196
+ assert.deepEqual(await indexesOn(knex, dialect, table, column), [index], `${table}.${column} has one index, ${index}`);
197
+ }
198
+ }
199
+
200
+ test(`a new database migrated in Knex's order has a person's indexes (${dialect})`, { skip }, async (t) => {
201
+ if (database) requireTestDatabase(process.env);
202
+ const knex = await open(t);
203
+ await knex.migrate.latest(DIRECTORY_MIGRATIONS);
204
+ await indexedOnce(knex);
205
+ // Rolled back in the reverse order, workspaces_core_person_indexes takes the indexes back before the tables go and
206
+ // workspaces_core_indexes_by_user, last, finds nothing to drop.
207
+ await knex.migrate.rollback(DIRECTORY_MIGRATIONS, true);
208
+ assert.equal(await knex.schema.hasTable("workspace_memberships"), false);
209
+ });
210
+
211
+ test(`a database that ran ${INDEXES_BY_USER} after the tables keeps its indexes, once (${dialect})`, { skip }, async (t) => {
212
+ if (database) requireTestDatabase(process.env);
213
+ const knex = await open(t);
214
+ await knex.migrate.latest({ migrationSource: upgradedDatabaseMigrations() });
215
+ await indexedOnce(knex);
216
+ const [, ran] = await knex.migrate.latest(DIRECTORY_MIGRATIONS);
217
+ assert.deepEqual(ran, [PERSON_INDEXES]);
218
+ await indexedOnce(knex);
219
+ });
220
+ }
221
+
222
+ /** An in-memory SQLite database. */
223
+ async function openSqlite(t) {
224
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
225
+ t.after(() => knex.destroy());
226
+ return knex;
227
+ }
228
+
229
+ function serverOf(defaultPort) {
230
+ return { host: process.env.DB_HOST, port: Number(process.env.DB_PORT) || defaultPort, user: process.env.DB_USER, password: process.env.DB_PASSWORD };
231
+ }
232
+
233
+ /** A MariaDB/MySQL database named after TEST_DB_NAME with `suffix`, made for the test and dropped after it. */
234
+ function openMysql(suffix) {
235
+ return async (t) => {
236
+ const name = `${requireTestDatabase(process.env)}_${suffix}`;
237
+ const server = { ...serverOf(3306), supportBigNumbers: true, bigNumberStrings: true, dateStrings: ["DATE"], timezone: "Z" };
238
+ const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
239
+ const knex = knexLib({ client: "mysql2", connection: { ...server, database: name }, pool: { min: 0, max: 4 } });
240
+ t.after(async () => {
241
+ try {
242
+ await knex.destroy();
243
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
244
+ } finally {
245
+ await admin.destroy();
246
+ }
247
+ });
248
+ await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
249
+ await admin.raw("CREATE DATABASE ??", [name]);
250
+ return knex;
251
+ };
252
+ }
253
+
254
+ /** A PostgreSQL schema in TEST_DB_NAME named after it with `suffix`, made for the test and dropped after it. */
255
+ function openPostgres(suffix) {
256
+ return async (t) => {
257
+ const database = requireTestDatabase(process.env);
258
+ const schema = `${database}_${suffix}_${process.pid}`;
259
+ const connection = { ...serverOf(5432), database };
260
+ const admin = knexLib({ client: "pg", connection, pool: { min: 0, max: 1 } });
261
+ const knex = knexLib({ client: "pg", connection, searchPath: [schema], pool: { min: 0, max: 4 } });
262
+ t.after(async () => {
263
+ try {
264
+ await knex.destroy();
265
+ await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
266
+ } finally {
267
+ await admin.destroy();
268
+ }
269
+ });
270
+ await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
271
+ await admin.raw("CREATE SCHEMA ??", [schema]);
272
+ return knex;
273
+ };
274
+ }
275
+
276
+ // A PostgreSQL test on a run for another database, such as CI's MariaDB run, is left to the PostgreSQL run.
277
+ const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "pg"
278
+ ? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
279
+ : false;
280
+
281
+ export { POSTGRES_ELSEWHERE, indexesByUserCases, migrationOrderCases, openMysql, openPostgres, openSqlite };
@@ -84,6 +84,26 @@ test("workspace mutation actions declare their domain and bootstrap changes expl
84
84
  assert.deepEqual(events[0].realtime.payload, { workspaceSlug: "acme" });
85
85
  });
86
86
 
87
+ test("making and changing a workspace are entity changes of the workspace, named by the id the action answers", async () => {
88
+ const context = { actor: { id: 7 }, requestMeta: {} };
89
+ const [create, update] = ["workspace.workspaces.create", "workspace.workspaces.update"]
90
+ .map((id) => workspaceDirectoryActionSpecifications.find((action) => action.id === id));
91
+ assert.deepEqual([create.events.length, update.events.length], [1, 1]);
92
+ const [created] = await Promise.all(create.events.map((builder) => builder({
93
+ input: { name: "Acme" },
94
+ result: returnJsonApiData({ id: "11", slug: "acme", name: "Acme", ownerUserId: "7" }),
95
+ context
96
+ })));
97
+ assert.deepEqual([created.type, created.source, created.entity, created.operation, created.entityId], ["entity.changed", "workspace", "workspace", "created", "11"]);
98
+ assert.equal(created.realtime, undefined);
99
+ const [updated] = await Promise.all(update.events.map((builder) => builder({
100
+ input: { workspaceSlug: "acme", name: "Acme Ltd" },
101
+ result: returnJsonApiData({ id: "11", slug: "acme", name: "Acme Ltd", ownerUserId: "7" }),
102
+ context
103
+ })));
104
+ assert.deepEqual([updated.entity, updated.operation, updated.entityId], ["workspace", "updated", "11"]);
105
+ });
106
+
87
107
  test("workspace invite actions reach the invite's recipient through the members service, once per event", async () => {
88
108
  const lookups = [];
89
109
  const [create, revoke] = ["workspace.invite.create", "workspace.invite.revoke"].map((id) => createWorkspaceMembersActions({