@jskit-ai/workspaces-core 0.2.23 → 0.2.24

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,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The optional `workspaces.workspace-created-participant` capability writes an application's records for every new workspace in the creation's transaction, as `workspaces.invite-acceptance-participant` does for an accepted invitation: one function `({ workspace, owner }, { trx, context })`, with `workspace` and `owner` shallow frozen. Both creation paths call it, the `workspace.workspaces.create` action (`createWorkspaceForAuthenticatedUser`) and a personal workspace's provisioning (`ensurePersonalWorkspaceForUser`, inside a first sign-in's profile sync), after the workspace, its owner's membership and its settings are written. Creating a workspace is now one transaction, the caller's or its own, where the named create wrote its three rows one after the other: a failure, the participant's or a later write's, leaves no workspace, membership or settings row and none of the participant's writes, and the caller receives the failure itself. A create that loses its slug to another create runs again with the next free slug, and one that loses it to the same owner's identical create answers that workspace, as the repository's insert did, without calling the participant twice. Without the capability, creation writes the workspace, membership and settings only.
5
6
  - A member's role change and their removal lock the membership before they check it, so two at once run one after the other and the second decides on what the first left: a role change that waited for a removal answers 404 `workspaces.member.notFound` instead of making the removed member active again, and a removal that waited for a role change keeps the new role instead of writing back the one it read. `workspaces.memberships` gains `lockByWorkspaceIdAndUserId(workspaceId, userId, txOptions)`, the membership locked until the caller's transaction ends, or null.
6
7
  - Expiring an email's pending invites (`expirePendingByWorkspaceIdAndEmail`, which every new invite runs first) is one `patchWhere` on the invites, where it locked them and then patched them one at a time: its statements no longer grow with the invites the email had.
7
8
  - `workspaces.joinSource` and `workspaces.memberships.joinSource` are the handle's `joinSource` (`@jskit-ai/resource-runtime`): the same `{ query, column }` for the same params, carrying the columns a read answers instead of every column of the table. A report that names its columns with `column(field)` reads as before.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.23",
3
+ "version": "0.2.24",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,10 +23,10 @@
23
23
  "./locales/en.json": "./locales/en.json"
24
24
  },
25
25
  "dependencies": {
26
- "@jskit-ai/resource-core": "0.1.208",
27
- "@jskit-ai/resource-crud-core": "0.1.208",
28
- "@jskit-ai/users-core": "0.2.23",
29
- "json-rest-schema": "^1.0.17"
26
+ "@jskit-ai/resource-core": "0.1.209",
27
+ "@jskit-ai/resource-crud-core": "0.1.209",
28
+ "@jskit-ai/users-core": "0.2.24",
29
+ "json-rest-schema": "^1.0.20"
30
30
  },
31
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
32
32
  "jskit": {
@@ -206,10 +206,10 @@
206
206
  }
207
207
  },
208
208
  "peerDependencies": {
209
- "@jskit-ai/auth-core": "0.2.17",
210
- "@jskit-ai/database-runtime": "0.1.266",
211
- "@jskit-ai/http-runtime": "0.2.17",
212
- "@jskit-ai/kernel": "0.2.17",
213
- "@jskit-ai/resource-runtime": "0.2.19"
209
+ "@jskit-ai/auth-core": "0.2.18",
210
+ "@jskit-ai/database-runtime": "0.1.267",
211
+ "@jskit-ai/http-runtime": "0.2.18",
212
+ "@jskit-ai/kernel": "0.2.18",
213
+ "@jskit-ai/resource-runtime": "0.2.20"
214
214
  }
215
215
  }
@@ -74,6 +74,15 @@ external effects out of it. Without the capability, acceptance activates the
74
74
  membership only. Allow ordinary invitations; reject stale, revoked, conflicting
75
75
  or unexpectedly missing application associations.
76
76
 
77
+ Provide the optional `workspaces.workspace-created-participant` capability the
78
+ same way to write application records for every new workspace. The
79
+ `workspace.workspaces.create` action and personal workspace provisioning invoke
80
+ `fn({ workspace, owner }, txOptions)` after writing the workspace, its owner's
81
+ membership and its settings, in the creation's uncommitted transaction (the
82
+ caller's when it passes one). Pass `txOptions` on and propagate failures: a
83
+ failure rolls the whole creation back. An existing personal workspace does not
84
+ call it.
85
+
77
86
  Call `members.prepareInvite(workspace, actor, payload, txOptions)` inside
78
87
  `repositories.workspaceInvites.withTransaction(options, async (txOptions) => …)`
79
88
  or another resource handle's `withTransaction`. It returns
@@ -10,6 +10,7 @@ import { registerWorkspaceSettingsRoutes } from "./workspaceSettings/workspaceSe
10
10
  import { unconfiguredWorkspaceInviteMailer } from "./workspaceMembers/unconfiguredWorkspaceInviteMailer.js";
11
11
  import { renderDefaultWorkspaceInviteEmail } from "./workspaceMembers/defaultWorkspaceInviteEmail.js";
12
12
  import { noInviteAcceptanceParticipant } from "./workspacePendingInvitations/noInviteAcceptanceParticipant.js";
13
+ import { noWorkspaceCreatedParticipant } from "./workspaceDirectory/noWorkspaceCreatedParticipant.js";
13
14
  import { buildWorkspaceName } from "./common/services/workspaceDirectoryService.js";
14
15
  import { createWorkspaceSettingsActions } from "./workspaceSettings/workspaceSettingsActions.js";
15
16
  import { WORKSPACES_TABLES, createWorkspaceRecords, createWorkspacesRuntime } from "./workspacesRuntime.js";
@@ -31,7 +32,8 @@ const WorkspacesFeature = defineFeature({
31
32
  inviteAcceptanceParticipant: "workspaces.invite-acceptance-participant",
32
33
  inviteEmailTemplate: "workspaces.invite-email-template",
33
34
  inviteMailer: "workspaces.invite-mailer",
34
- personalWorkspaceName: "workspaces.personal-workspace-name"
35
+ personalWorkspaceName: "workspaces.personal-workspace-name",
36
+ workspaceCreatedParticipant: "workspaces.workspace-created-participant"
35
37
  },
36
38
  provides: {
37
39
  workspaces: "workspaces.core",
@@ -52,6 +54,7 @@ const WorkspacesFeature = defineFeature({
52
54
  * @param {import("./types.js").WorkspacesResources} capabilities.resources
53
55
  * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} capabilities.userProfiles
54
56
  * @param {import("@jskit-ai/users-core/server/types").UsersSettings} capabilities.userSettings
57
+ * @param {import("./types.js").WorkspaceCreatedParticipant | null} capabilities.workspaceCreatedParticipant
55
58
  */
56
59
  async setup({
57
60
  appRoot,
@@ -65,7 +68,8 @@ const WorkspacesFeature = defineFeature({
65
68
  personalWorkspaceName,
66
69
  resources,
67
70
  userProfiles,
68
- userSettings
71
+ userSettings,
72
+ workspaceCreatedParticipant
69
73
  }) {
70
74
  const records = createWorkspaceRecords(resources);
71
75
  const workspaces = createWorkspacesRuntime({
@@ -79,6 +83,7 @@ const WorkspacesFeature = defineFeature({
79
83
  resources,
80
84
  userProfiles,
81
85
  userSettings,
86
+ workspaceCreatedParticipant: workspaceCreatedParticipant ?? noWorkspaceCreatedParticipant,
82
87
  workspaces: records.workspaces,
83
88
  workspaceMemberships: records.memberships
84
89
  });
@@ -139,6 +144,7 @@ export {
139
144
  createWorkspaceRecords,
140
145
  createWorkspacesRuntime,
141
146
  noInviteAcceptanceParticipant,
147
+ noWorkspaceCreatedParticipant,
142
148
  renderDefaultWorkspaceInviteEmail,
143
149
  unconfiguredWorkspaceInviteMailer
144
150
  };
@@ -58,6 +58,7 @@ function buildWorkspaceName(user) {
58
58
  * @param {import("../../types.js").WorkspaceTenancyProfile} dependencies.tenancyProfile
59
59
  * @param {import("../../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
60
60
  * @param {import("../../types.js").PersonalWorkspaceName} dependencies.personalWorkspaceName
61
+ * @param {import("../../types.js").WorkspaceCreatedParticipant} dependencies.createdParticipant
61
62
  * @param {import("../../types.js").WorkspacesRepository} dependencies.workspacesRepository
62
63
  * @param {import("../../types.js").WorkspaceMembershipsRepository} dependencies.workspaceMembershipsRepository
63
64
  * @param {import("../../types.js").WorkspaceSettingsRepository} dependencies.workspaceSettingsRepository
@@ -66,6 +67,7 @@ function createService({
66
67
  tenancyProfile,
67
68
  roleCatalog,
68
69
  personalWorkspaceName,
70
+ createdParticipant,
69
71
  workspacesRepository,
70
72
  workspaceMembershipsRepository,
71
73
  workspaceSettingsRepository
@@ -88,33 +90,54 @@ function createService({
88
90
  throw new Error("Unable to generate unique workspace slug.");
89
91
  }
90
92
 
93
+ async function ensureWorkspaceSettingsForWorkspace(workspace, options = {}) {
94
+ return workspaceSettingsRepository.ensureForWorkspaceId(workspace.id, {
95
+ ...options,
96
+ workspace
97
+ });
98
+ }
99
+
91
100
  /**
92
- * Creates a workspace under the first free slug from baseSlug. When another owner's create takes that slug between
93
- * the read and the insert, it picks again; inside the caller's transaction the duplicate fails the transaction.
101
+ * Creates a workspace under the first free slug from baseSlug, its owner's membership and its settings, then runs the
102
+ * `workspaces.workspace-created-participant`, all in one transaction: the caller's (`options.trx`), or one of its own.
103
+ * Any failure, the participant's included, rolls the whole creation back. When another create takes the slug between
104
+ * the read and the insert, a transaction of its own answers the winner when it is the same owner's same kind of
105
+ * workspace (a personal workspace made at two first sign-ins at once, a form sent twice), and otherwise runs again
106
+ * under a new slug; inside the caller's transaction the duplicate fails the caller's transaction.
94
107
  * @param {string} baseSlug
95
- * @param {Record<string, unknown>} payload The workspace, without its slug.
108
+ * @param {{ name: string, isPersonal: boolean, avatarUrl: string }} payload The workspace, without its slug and owner.
109
+ * @param {{ id: string }} owner The user who owns it.
96
110
  * @param {object} [options]
97
111
  */
98
- async function insertWithFreeSlug(baseSlug, payload, options = {}) {
112
+ async function createOwnedWorkspace(baseSlug, payload, owner, options = {}) {
113
+ // The slug while the workspace's own insert runs: a duplicate from a later write is not a lost slug.
114
+ let insertingSlug = null;
99
115
  for (let attempt = 1; ; attempt += 1) {
100
- const slug = await ensureUniqueWorkspaceSlug(baseSlug, options);
101
116
  try {
102
- return await workspacesRepository.insert({ ...payload, slug }, options);
117
+ return await workspacesRepository.withTransaction(options, async (txOptions) => {
118
+ insertingSlug = await ensureUniqueWorkspaceSlug(baseSlug, txOptions);
119
+ const workspace = await workspacesRepository.insert(
120
+ { ...payload, slug: insertingSlug, ownerUserId: owner.id },
121
+ txOptions
122
+ );
123
+ insertingSlug = null;
124
+ await workspaceMembershipsRepository.ensureOwnerMembership(workspace.id, owner.id, txOptions);
125
+ await ensureWorkspaceSettingsForWorkspace(workspace, txOptions);
126
+ await createdParticipant({ workspace: Object.freeze({ ...workspace }), owner: Object.freeze({ ...owner }) }, txOptions);
127
+ return workspace;
128
+ });
103
129
  } catch (error) {
104
- if (attempt >= WORKSPACE_SLUG_ATTEMPTS || !isLostDuplicateInsertRace(error, options)) {
130
+ if (attempt >= WORKSPACE_SLUG_ATTEMPTS || !insertingSlug || !isLostDuplicateInsertRace(error, options)) {
105
131
  throw error;
106
132
  }
133
+ const winner = await workspacesRepository.findBySlug(insertingSlug, options);
134
+ if (winner && winner.ownerUserId === owner.id && winner.isPersonal === payload.isPersonal) {
135
+ return winner;
136
+ }
107
137
  }
108
138
  }
109
139
  }
110
140
 
111
- async function ensureWorkspaceSettingsForWorkspace(workspace, options = {}) {
112
- return workspaceSettingsRepository.ensureForWorkspaceId(workspace.id, {
113
- ...options,
114
- workspace
115
- });
116
- }
117
-
118
141
  async function ensurePersonalWorkspaceForUser(user, options = {}) {
119
142
  const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
120
143
  if (!normalizedUserId) {
@@ -128,20 +151,16 @@ function createService({
128
151
  return existing;
129
152
  }
130
153
 
131
- const inserted = await insertWithFreeSlug(
154
+ return createOwnedWorkspace(
132
155
  buildWorkspaceBaseSlug(user),
133
156
  {
134
157
  name: normalizeText(personalWorkspaceName(user)) || buildWorkspaceName(user),
135
- ownerUserId: normalizedUserId,
136
158
  isPersonal: true,
137
159
  avatarUrl: ""
138
160
  },
161
+ { ...user, id: normalizedUserId },
139
162
  options
140
163
  );
141
-
142
- await workspaceMembershipsRepository.ensureOwnerMembership(inserted.id, normalizedUserId, options);
143
- await ensureWorkspaceSettingsForWorkspace(inserted, options);
144
- return inserted;
145
164
  }
146
165
 
147
166
  async function listWorkspacesForUser(user, options = {}) {
@@ -205,20 +224,16 @@ function createService({
205
224
  });
206
225
  }
207
226
 
208
- const inserted = await insertWithFreeSlug(
227
+ return returnJsonApiData(await createOwnedWorkspace(
209
228
  requestedSlug || toSlugPart(name),
210
229
  {
211
230
  name,
212
- ownerUserId: normalizedUserId,
213
231
  isPersonal: false,
214
232
  avatarUrl: ""
215
233
  },
234
+ { ...user, id: normalizedUserId },
216
235
  options
217
- );
218
-
219
- await workspaceMembershipsRepository.ensureOwnerMembership(inserted.id, normalizedUserId, options);
220
- await ensureWorkspaceSettingsForWorkspace(inserted, options);
221
- return returnJsonApiData(inserted);
236
+ ));
222
237
  }
223
238
 
224
239
  async function getWorkspaceForAuthenticatedUser(user, workspaceSlug, options = {}) {
@@ -49,6 +49,16 @@
49
49
  * @typedef {(acceptance: { invite: object, user: object }, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceInviteAcceptanceParticipant
50
50
  */
51
51
 
52
+ /**
53
+ * The `workspaces.workspace-created-participant` capability: the application's
54
+ * writes for a new workspace, personal (provisioned at sign-in) or created by
55
+ * `workspace.workspaces.create`. It runs after the workspace, its owner's
56
+ * membership and its settings are written, inside the uncommitted creation
57
+ * transaction, and a failure rolls the whole creation back. `owner` is the user
58
+ * who owns the workspace. Its options join that transaction: pass them to every call.
59
+ * @typedef {(created: { workspace: object, owner: object }, options: { trx: unknown, context?: object }) => Promise<void>} WorkspaceCreatedParticipant
60
+ */
61
+
52
62
  /**
53
63
  * The `workspaces.personal-workspace-name` capability: names the personal
54
64
  * workspace provisioned for a user. An empty name falls back to the default.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The `workspaces.workspace-created-participant` default when no feature
3
+ * provides one: creating a workspace writes the workspace, its owner
4
+ * membership and its settings only.
5
+ * @type {import("../types.js").WorkspaceCreatedParticipant}
6
+ */
7
+ async function noWorkspaceCreatedParticipant() {}
8
+
9
+ export { noWorkspaceCreatedParticipant };
@@ -82,6 +82,7 @@ function createWorkspaceRecords(resources) {
82
82
  * @param {import("./types.js").WorkspacesResources} dependencies.resources The handles of the tables `workspaces.core` owns.
83
83
  * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
84
84
  * @param {import("@jskit-ai/users-core/server/types").UsersSettings} dependencies.userSettings
85
+ * @param {import("./types.js").WorkspaceCreatedParticipant} dependencies.workspaceCreatedParticipant
85
86
  * @param {import("./types.js").Workspaces} dependencies.workspaces
86
87
  * @param {import("./types.js").WorkspacesMemberships} dependencies.workspaceMemberships
87
88
  */
@@ -96,6 +97,7 @@ function createWorkspacesRuntime({
96
97
  resources,
97
98
  userProfiles,
98
99
  userSettings,
100
+ workspaceCreatedParticipant,
99
101
  workspaces: workspacesRepository,
100
102
  workspaceMemberships: workspaceMembershipsRepository
101
103
  }) {
@@ -119,6 +121,7 @@ function createWorkspacesRuntime({
119
121
  tenancyProfile,
120
122
  roleCatalog,
121
123
  personalWorkspaceName,
124
+ createdParticipant: workspaceCreatedParticipant,
122
125
  workspacesRepository,
123
126
  workspaceMembershipsRepository,
124
127
  workspaceSettingsRepository
@@ -3,6 +3,7 @@ import { before, beforeEach, after, describe, test } from "node:test";
3
3
  import knexLib from "knex";
4
4
  import { findDuplicateEntryError } from "@jskit-ai/database-runtime/shared";
5
5
  import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
6
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
6
7
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
7
8
  import { checkForeignKeys } from "@jskit-ai/resource-runtime/server";
8
9
  import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
@@ -25,6 +26,7 @@ import { unconfiguredWorkspaceInviteMailer } from "../src/server/workspaceMember
25
26
  import { createWorkspaceInviteUrlBuilder } from "../src/server/workspaceMembers/workspaceInviteUrls.js";
26
27
  import { createService as createMembersService } from "../src/server/workspaceMembers/workspaceMembersService.js";
27
28
  import { buildWorkspaceName, createService as createDirectoryService } from "../src/server/common/services/workspaceDirectoryService.js";
29
+ import { noWorkspaceCreatedParticipant } from "../src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js";
28
30
  import { resolveTenancyProfile } from "../src/shared/tenancyProfile.js";
29
31
  import { createWorkspacesServerI18n } from "../src/server/i18n.js";
30
32
  import { createWorkspaceRoleCatalog } from "../src/shared/roles.js";
@@ -600,6 +602,7 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
600
602
  tenancyProfile: resolveTenancyProfile({ tenancyMode: "workspaces", tenancyPolicy: { workspace: { allowSelfCreate: true } } }),
601
603
  roleCatalog: createWorkspaceRoleCatalog(),
602
604
  personalWorkspaceName: buildWorkspaceName,
605
+ createdParticipant: noWorkspaceCreatedParticipant,
603
606
  workspacesRepository: workspaces,
604
607
  workspaceMembershipsRepository: memberships,
605
608
  workspaceSettingsRepository: settings
@@ -619,6 +622,7 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
619
622
  tenancyProfile: resolveTenancyProfile({ tenancyMode: "personal" }),
620
623
  roleCatalog: createWorkspaceRoleCatalog(),
621
624
  personalWorkspaceName: buildWorkspaceName,
625
+ createdParticipant: noWorkspaceCreatedParticipant,
622
626
  workspacesRepository: workspaces,
623
627
  workspaceMembershipsRepository: memberships,
624
628
  workspaceSettingsRepository: settings
@@ -837,6 +841,7 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
837
841
  tenancyProfile: resolveTenancyProfile({ tenancyMode: "workspaces", tenancyPolicy: { workspace: { allowSelfCreate: true } } }),
838
842
  roleCatalog: createWorkspaceRoleCatalog(),
839
843
  personalWorkspaceName: buildWorkspaceName,
844
+ createdParticipant: noWorkspaceCreatedParticipant,
840
845
  workspacesRepository: racing,
841
846
  workspaceMembershipsRepository: memberships,
842
847
  workspaceSettingsRepository: settings
@@ -848,6 +853,108 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
848
853
  assert.equal(String((await workspaces.findBySlug("acme-2")).ownerUserId), String(grace.id));
849
854
  });
850
855
 
856
+ test("a new workspace's created participant runs in its creation transaction, and its failure leaves nothing of the creation", async () => {
857
+ const count = async (table, where = {}) => Number((await knex(table).where(where).count({ count: "*" }).first()).count);
858
+ const seen = [];
859
+ let refusal = null;
860
+ let duplicateWrite = false;
861
+ // The application's participant reads what the creation wrote and makes a write of its own in the same transaction.
862
+ async function createdParticipant({ workspace, owner }, options) {
863
+ const ownerMembership = await memberships.findByWorkspaceIdAndUserId(workspace.id, owner.id, options);
864
+ const workspaceSettings = await settings.findByWorkspaceId(workspace.id, options);
865
+ seen.push({
866
+ slug: workspace.slug,
867
+ isPersonal: workspace.isPersonal,
868
+ owner: owner.id,
869
+ role: ownerMembership.roleSid,
870
+ settings: String(workspaceSettings.id) === String(workspace.id),
871
+ frozen: Object.isFrozen(workspace) && Object.isFrozen(owner),
872
+ trx: options.trx
873
+ });
874
+ await profiles.updateDisplayNameById(owner.id, `${owner.displayName} of ${workspace.slug}`, options);
875
+ if (duplicateWrite) await workspaces.insert({ slug: "acme", name: "Copy", ownerUserId: owner.id }, options);
876
+ if (refusal) throw refusal;
877
+ }
878
+ let missOwnSlug = false;
879
+ const directory = createDirectoryService({
880
+ tenancyProfile: resolveTenancyProfile({ tenancyMode: "workspaces", tenancyPolicy: { workspace: { allowSelfCreate: true } } }),
881
+ roleCatalog: createWorkspaceRoleCatalog(),
882
+ personalWorkspaceName: buildWorkspaceName,
883
+ createdParticipant,
884
+ // The free-slug read can miss a workspace once, as when another create inserts it between the read and the insert.
885
+ workspacesRepository: {
886
+ ...workspaces,
887
+ async listSlugsIn(slugs, options) {
888
+ if (missOwnSlug) {
889
+ missOwnSlug = false;
890
+ return new Set();
891
+ }
892
+ return workspaces.listSlugsIn(slugs, options);
893
+ }
894
+ },
895
+ workspaceMembershipsRepository: memberships,
896
+ workspaceSettingsRepository: settings
897
+ });
898
+ const ada = await createProfile("ada");
899
+ const grace = await createProfile("grace");
900
+
901
+ const team = (await directory.createWorkspaceForAuthenticatedUser(ada, { name: "Acme", slug: "acme" })).value;
902
+ const personal = await directory.ensurePersonalWorkspaceForUser(grace);
903
+ assert.deepEqual(seen.map(({ trx, ...entry }) => entry), [
904
+ { slug: "acme", isPersonal: false, owner: ada.id, role: "owner", settings: true, frozen: true },
905
+ { slug: "grace", isPersonal: true, owner: grace.id, role: "owner", settings: true, frozen: true }
906
+ ]);
907
+ assert.ok(seen.every(({ trx }) => trx), "each ran inside its creation's transaction");
908
+ assert.equal((await profiles.findById(ada.id)).displayName, "ada of acme");
909
+ assert.equal((await directory.ensurePersonalWorkspaceForUser(grace)).id, personal.id);
910
+ assert.equal(seen.length, 2, "an existing personal workspace is not created again, and runs no participant");
911
+
912
+ // A create that loses its slug to the same owner's same kind of workspace answers that workspace, and runs no participant.
913
+ missOwnSlug = true;
914
+ assert.equal((await directory.createWorkspaceForAuthenticatedUser(ada, { name: "Acme", slug: "acme" })).value.id, team.id);
915
+ assert.equal(seen.length, 2);
916
+
917
+ // Inside the caller's transaction, the participant runs in that transaction.
918
+ const carol = await createProfile("carol");
919
+ await userSettings.withTransaction({}, async (txOptions) => {
920
+ await directory.ensurePersonalWorkspaceForUser(carol, txOptions);
921
+ assert.equal(seen.at(-1).trx, txOptions.trx);
922
+ });
923
+
924
+ // A participant's refusal rolls back the workspace, its owner's membership, its settings and the participant's own write.
925
+ refusal = new AppError(409, "This workspace cannot be set up yet.", { code: "test.workspace.setupRefused" });
926
+ const workspacesBefore = await count("workspaces");
927
+ const settingsBefore = await count("workspace_settings");
928
+ const bob = await createProfile("bob");
929
+ for (const create of [
930
+ () => directory.createWorkspaceForAuthenticatedUser(bob, { name: "Refused", slug: "refused" }),
931
+ () => directory.ensurePersonalWorkspaceForUser(bob)
932
+ ]) {
933
+ await assert.rejects(create(), (error) => {
934
+ assert.equal(error, refusal);
935
+ assert.equal(error.transactionOutcome, "rolledBack");
936
+ return true;
937
+ });
938
+ }
939
+ assert.equal(await count("workspaces"), workspacesBefore);
940
+ assert.equal(await count("workspaces", { owner_user_id: bob.id }), 0);
941
+ assert.equal(await count("workspace_memberships", { user_id: bob.id }), 0);
942
+ assert.equal(await count("workspace_settings"), settingsBefore);
943
+ assert.equal((await profiles.findById(bob.id)).displayName, "bob");
944
+
945
+ // A duplicate from the participant's own write is not a lost slug: the creation fails once and does not run again.
946
+ refusal = null;
947
+ duplicateWrite = true;
948
+ const runs = seen.length;
949
+ await assert.rejects(directory.createWorkspaceForAuthenticatedUser(bob, { name: "Copy", slug: "copy" }), (error) => {
950
+ assert.ok(findDuplicateEntryError(error));
951
+ assert.equal(error.transactionOutcome, "rolledBack");
952
+ return true;
953
+ });
954
+ assert.equal(seen.length, runs + 1);
955
+ assert.equal(await count("workspaces", { owner_user_id: bob.id }), 0);
956
+ });
957
+
851
958
  test("a duplicate participant poisons its managed transaction even when its caller catches the failure", async () => {
852
959
  const owner = await createProfile("Ada");
853
960
  await workspaces.insert({ slug: "duplicate", name: "Original", ownerUserId: owner.id });
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
4
4
  import { buildWorkspaceName, createService as createDirectoryService } from "../src/server/common/services/workspaceDirectoryService.js";
5
+ import { noWorkspaceCreatedParticipant } from "../src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js";
5
6
  import { listCatalogRolePermissions } from "../src/shared/roles.js";
6
7
  import { resolveTenancyProfile } from "../src/shared/tenancyProfile.js";
7
8
  import { workspacesDatabase } from "./support/mysqlWorkspaces.js";
@@ -21,6 +22,7 @@ function directoryOf(db, tenancy) {
21
22
  tenancyProfile: resolveTenancyProfile(tenancy),
22
23
  roleCatalog: db.roleCatalog,
23
24
  personalWorkspaceName: buildWorkspaceName,
25
+ createdParticipant: noWorkspaceCreatedParticipant,
24
26
  workspacesRepository: db.workspaces,
25
27
  workspaceMembershipsRepository: db.memberships,
26
28
  workspaceSettingsRepository: db.settings
@@ -3,9 +3,12 @@ import assert from "node:assert/strict";
3
3
  import { createWorkspaceActionContextContributor } from "../src/server/common/contributors/workspaceActionContextContributor.js";
4
4
  import { createWorkspaceAuthPolicyContextResolver } from "../src/server/common/contributors/workspaceAuthPolicyContextResolver.js";
5
5
  import { buildWorkspaceName, createService } from "../src/server/common/services/workspaceDirectoryService.js";
6
+ import { noWorkspaceCreatedParticipant } from "../src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js";
6
7
  import { createWorkspaceRoleCatalog } from "../src/shared/roles.js";
7
8
  import { resolveTenancyProfile } from "../src/shared/tenancyProfile.js";
8
9
 
10
+ const TEST_TRX = Object.freeze({ name: "the creation transaction" });
11
+
9
12
  // The service receives what the workspaces feature resolves from its config.
10
13
  function resolvedSettings(appConfig) {
11
14
  return {
@@ -41,6 +44,7 @@ function createWorkspaceServiceFixture({
41
44
  userWorkspaceRows = null,
42
45
  membershipResolver = null,
43
46
  personalWorkspaceName = undefined,
47
+ createdParticipant = noWorkspaceCreatedParticipant,
44
48
  personalWorkspace = {
45
49
  id: "1",
46
50
  slug: "tony3",
@@ -50,7 +54,10 @@ function createWorkspaceServiceFixture({
50
54
  avatarUrl: ""
51
55
  }
52
56
  } = {}) {
57
+ // Each write and the participant, with the transaction it ran in: withTransaction hands work TEST_TRX.
58
+ const steps = [];
53
59
  const calls = {
60
+ withTransaction: 0,
54
61
  findBySlug: 0,
55
62
  listSlugsIn: 0,
56
63
  findPersonalByOwnerUserId: 0,
@@ -91,7 +98,15 @@ function createWorkspaceServiceFixture({
91
98
  personalWorkspaceName,
92
99
  roleCatalog: roleCatalog && typeof roleCatalog === "object" ? { ...roleCatalog } : roleCatalog
93
100
  }),
101
+ async createdParticipant(created, options) {
102
+ steps.push(["participant", options.trx]);
103
+ return createdParticipant(created, options);
104
+ },
94
105
  workspacesRepository: {
106
+ async withTransaction(options, work) {
107
+ calls.withTransaction += 1;
108
+ return work(Object.freeze({ ...options, trx: TEST_TRX }));
109
+ },
95
110
  async findBySlug(slug) {
96
111
  calls.findBySlug += 1;
97
112
  const normalizedSlug = String(slug || "").trim().toLowerCase();
@@ -133,8 +148,9 @@ function createWorkspaceServiceFixture({
133
148
  }
134
149
  ];
135
150
  },
136
- async insert(payload) {
151
+ async insert(payload, options = {}) {
137
152
  calls.insert += 1;
153
+ steps.push(["insert", options.trx]);
138
154
  insertedPayloads.push(payload);
139
155
  const workspaceId = String(nextWorkspaceId++);
140
156
  const inserted = {
@@ -173,8 +189,9 @@ function createWorkspaceServiceFixture({
173
189
  }
174
190
  },
175
191
  workspaceMembershipsRepository: {
176
- async ensureOwnerMembership() {
192
+ async ensureOwnerMembership(workspaceId, userId, options = {}) {
177
193
  calls.ensureOwnerMembership += 1;
194
+ steps.push(["membership", options.trx]);
178
195
  },
179
196
  async findByWorkspaceIdAndUserId(workspaceId, userId) {
180
197
  if (typeof membershipResolver === "function") {
@@ -189,8 +206,9 @@ function createWorkspaceServiceFixture({
189
206
  }
190
207
  },
191
208
  workspaceSettingsRepository: {
192
- async ensureForWorkspaceId() {
209
+ async ensureForWorkspaceId(workspaceId, options = {}) {
193
210
  calls.ensureWorkspaceSettings += 1;
211
+ steps.push(["settings", options.trx]);
194
212
  return {
195
213
  invitesEnabled: true
196
214
  };
@@ -198,7 +216,7 @@ function createWorkspaceServiceFixture({
198
216
  }
199
217
  });
200
218
 
201
- return { service, calls, insertedPayloads };
219
+ return { service, calls, insertedPayloads, steps };
202
220
  }
203
221
 
204
222
  test("workspaceService keeps bootstrap payload assembly outside its API", () => {
@@ -421,6 +439,60 @@ test("workspaceService.createWorkspaceForAuthenticatedUser generates an omitted
421
439
  assert.equal(insertedPayloads[0].ownerUserId, "7");
422
440
  });
423
441
 
442
+ test("both ways of creating a workspace run the created participant last, in the creation's transaction", async () => {
443
+ const chiara = { id: "7", email: "chiara@example.com", displayName: "Chiara" };
444
+ const creations = {
445
+ named: async (service) => (await service.createWorkspaceForAuthenticatedUser(chiara, { name: "Operations Team" })).value,
446
+ personal: (service) => service.ensureProvisionedWorkspaceForAuthenticatedUser(chiara)
447
+ };
448
+ for (const [kind, create] of Object.entries(creations)) {
449
+ const received = [];
450
+ const { service, calls, steps } = createWorkspaceServiceFixture({
451
+ tenancyMode: kind === "personal" ? "personal" : "workspaces",
452
+ tenancyPolicy: { workspace: { allowSelfCreate: true } },
453
+ personalWorkspace: null,
454
+ async createdParticipant(created, options) {
455
+ received.push({ created, options });
456
+ }
457
+ });
458
+ const workspace = await create(service);
459
+ assert.equal(calls.withTransaction, 1, kind);
460
+ assert.deepEqual(steps, [
461
+ ["insert", TEST_TRX], ["membership", TEST_TRX], ["settings", TEST_TRX], ["participant", TEST_TRX]
462
+ ], kind);
463
+ assert.equal(received.length, 1, kind);
464
+ const [{ created, options }] = received;
465
+ assert.deepEqual(Object.keys(created).sort(), ["owner", "workspace"]);
466
+ assert.equal(created.workspace.id, workspace.id);
467
+ assert.equal(created.workspace.isPersonal, kind === "personal");
468
+ assert.deepEqual(created.owner, chiara);
469
+ assert.ok(Object.isFrozen(created.workspace) && Object.isFrozen(created.owner), kind);
470
+ assert.equal(options.trx, TEST_TRX);
471
+ }
472
+ });
473
+
474
+ test("a created participant's failure fails the creation, and an existing personal workspace runs no participant", async () => {
475
+ const refusal = new Error("the application cannot set this workspace up");
476
+ async function refuse() {
477
+ throw refusal;
478
+ }
479
+ const { service, steps } = createWorkspaceServiceFixture({
480
+ tenancyMode: "workspaces",
481
+ tenancyPolicy: { workspace: { allowSelfCreate: true } },
482
+ createdParticipant: refuse
483
+ });
484
+ await assert.rejects(service.createWorkspaceForAuthenticatedUser({ id: "7" }, { name: "Operations Team" }), (error) => error === refusal);
485
+ assert.equal(steps.at(-1)[0], "participant");
486
+
487
+ const { service: personal, steps: personalSteps } = createWorkspaceServiceFixture({
488
+ tenancyMode: "personal",
489
+ createdParticipant: refuse
490
+ });
491
+ const existing = await personal.ensureProvisionedWorkspaceForAuthenticatedUser({ id: "7", displayName: "Chiara" });
492
+ assert.equal(existing.id, "1");
493
+ assert.ok(!personalSteps.some(([step]) => step === "participant"));
494
+ });
495
+
424
496
  // The slug a new workspace named `name` gets while `takenSlugs` are held, and how many reads chose it.
425
497
  async function chooseWorkspaceSlug(name, takenSlugs) {
426
498
  const { service, calls } = createWorkspaceServiceFixture({