@jskit-ai/workspaces-core 0.2.45 → 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,9 @@
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
+
5
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`.
6
9
 
7
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.
@@ -7,6 +7,11 @@
7
7
  // and MariaDB) made an index for each foreign key when the tables were created, named after the key
8
8
  // (workspace_memberships_user_id_foreign, workspaces_owner_user_id_foreign), which already serves these reads, so
9
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.
10
15
  const INDEXES = Object.freeze([
11
16
  Object.freeze({ table: "workspace_memberships", name: "ix_workspace_memberships_user", column: "user_id" }),
12
17
  Object.freeze({ table: "workspaces", name: "ix_workspaces_owner", column: "owner_user_id" })
@@ -18,6 +23,9 @@ function foreignKeysAreIndexed(knex) {
18
23
 
19
24
  exports.up = async function up(knex) {
20
25
  if (foreignKeysAreIndexed(knex)) return;
26
+ for (const { table } of INDEXES) {
27
+ if (!(await knex.schema.hasTable(table))) return;
28
+ }
21
29
  for (const { table, name, column } of INDEXES) {
22
30
  await knex.raw("create index if not exists ?? on ?? (??)", [name, table, column]);
23
31
  }
@@ -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.45",
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.45",
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.",
@@ -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,
@@ -1,4 +1,6 @@
1
- import { indexesByUserCases, openMysql } from "./support/indexesByUserCases.js";
1
+ import { indexesByUserCases, migrationOrderCases, openMysql } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on MariaDB/MySQL, whose foreign keys' own indexes serve these reads.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on MariaDB/MySQL, whose foreign keys' own indexes
4
+ // serve these reads.
4
5
  indexesByUserCases(openMysql("ws_by_user"), { dialect: "mysql" });
6
+ migrationOrderCases(openMysql("ws_order"), { dialect: "mysql" });
@@ -1,4 +1,5 @@
1
- import { POSTGRES_ELSEWHERE, indexesByUserCases, openPostgres } from "./support/indexesByUserCases.js";
1
+ import { POSTGRES_ELSEWHERE, indexesByUserCases, migrationOrderCases, openPostgres } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on PostgreSQL.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on PostgreSQL.
4
4
  indexesByUserCases(openPostgres("ws_by_user"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
5
+ migrationOrderCases(openPostgres("ws_order"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
@@ -1,4 +1,5 @@
1
- import { indexesByUserCases, openSqlite } from "./support/indexesByUserCases.js";
1
+ import { indexesByUserCases, migrationOrderCases, openSqlite } from "./support/indexesByUserCases.js";
2
2
 
3
- // workspaces_core_indexes_by_user on SQLite.
3
+ // workspaces_core_indexes_by_user and workspaces_core_person_indexes on SQLite.
4
4
  indexesByUserCases(openSqlite, { dialect: "sqlite", database: false });
5
+ migrationOrderCases(openSqlite, { dialect: "sqlite", database: false });
@@ -1,5 +1,9 @@
1
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";
2
5
  import test from "node:test";
6
+ import { fileURLToPath } from "node:url";
3
7
  import knexLib from "knex";
4
8
  import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
5
9
  import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
@@ -26,6 +30,14 @@ const READS = Object.freeze({
26
30
  memberships: { table: "workspace_memberships", column: "user_id", sqlite: "ix_workspace_memberships_user", postgres: "ix_workspace_memberships_user", mysql: "workspace_memberships_user_id_foreign" },
27
31
  owned: { table: "workspaces", column: "owner_user_id", sqlite: "ix_workspaces_owner", postgres: "ix_workspaces_owner", mysql: "workspaces_owner_user_id_foreign" }
28
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);
29
41
 
30
42
  // Each index of `table` with its columns in order.
31
43
  async function indexColumns(knex, dialect, table) {
@@ -53,6 +65,28 @@ async function indexColumns(knex, dialect, table) {
53
65
  return columns;
54
66
  }
55
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
+
56
90
  // The indexes the planner reads for one captured statement. PostgreSQL's planner is told to avoid whole-table scans,
57
91
  // which it prefers for tables this small, so its plan shows whether an index can serve the statement.
58
92
  async function indexesUsed(knex, dialect, { sql, bindings }) {
@@ -148,6 +182,43 @@ function indexesByUserCases(open, { dialect, database = true, skip = false }) {
148
182
  });
149
183
  }
150
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
+
151
222
  /** An in-memory SQLite database. */
152
223
  async function openSqlite(t) {
153
224
  const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
@@ -207,4 +278,4 @@ const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "p
207
278
  ? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
208
279
  : false;
209
280
 
210
- export { POSTGRES_ELSEWHERE, indexesByUserCases, openMysql, openPostgres, openSqlite };
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({