@tearleads/client-sdk 0.1.39 → 0.1.40
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/client/organizations/organizationGroupPresentation.d.ts +1 -12
- package/data/persistence/organizations/organizationReadModelGrantPersistence.js +2 -1
- package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +9 -0
- package/data/persistence/organizations/organizationReadModelMemberLoad.js +29 -21
- package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +91 -46
- package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPersistence.js +95 -73
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelProjection.js +78 -89
- package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +14 -15
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/sqlite/organizationReadModelSchema.js +23 -28
- package/data/sqlite/organizationReadModelSchema.js.map +1 -1
- package/data/sqlite/organizationReadModelTableRegistry.d.ts +116 -263
- package/data/sqlite/organizationReadModelTableRegistry.js +10 -7
- package/data/sqlite/organizationReadModelTableRegistry.js.map +1 -1
- package/data/sqlite/schema.d.ts +116 -263
- package/data/sqlite/sqliteBindBudget.js +30 -0
- package/data/sqlite/sqliteBindBudget.js.map +1 -0
- package/internal/validators/operation/organizations.d.ts +0 -16
- package/internal/validators/response/index.d.ts +1 -1
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/response/organizationReadModel.d.ts +10 -48
- package/internal/validators/response/organizationReadModel.js +9 -1
- package/internal/validators/response/organizationReadModel.js.map +1 -1
- package/package.json +1 -1
- package/workflows/organizations/readModel.d.ts +8 -3
- package/workflows/organizations/readModel.js.map +1 -1
- package/workflows/organizations/readModelProjection.d.ts +2 -12
- package/workflows/organizations/readModelProjection.js +1 -1
- package/workflows/organizations/readModelProjection.js.map +1 -1
- package/workflows/sync/remoteReset.js +1 -3
- package/workflows/sync/remoteReset.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPolicyHeadPersistence.js +0 -64
- package/data/persistence/organizations/organizationReadModelPolicyHeadPersistence.js.map +0 -1
|
@@ -3,17 +3,17 @@ import { invalidatePrincipalRecovery } from "../../principals/principalRecoveryE
|
|
|
3
3
|
import { organizationDataUsageTables } from "../../sqlite/organizationDataUsageSchema.js";
|
|
4
4
|
import { organizationReadModelDirectoryUsers, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/organizationReadModelSchema.js";
|
|
5
5
|
import { organizationReadModelTables } from "../../sqlite/schema.js";
|
|
6
|
+
import { sqliteInsertBatchSize } from "../../sqlite/sqliteBindBudget.js";
|
|
6
7
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
8
|
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
8
9
|
import { clearOrganizationPresentationDenialInTransaction } from "./organizationPresentationDenialPersistence.js";
|
|
9
10
|
import { applyOrganizationReadModelGrantsLane } from "./organizationReadModelGrantPersistence.js";
|
|
10
|
-
import { applyGroupMembershipsLane, assertStoredGroupMembershipBindings, } from "./organizationReadModelMembershipPersistence.js";
|
|
11
|
-
import { applyOrganizationPolicyLane, replaceGroupPolicyHeads, } from "./organizationReadModelPolicyHeadPersistence.js";
|
|
11
|
+
import { applyGroupMembershipsLane, assertStoredGroupMembershipBindings, OrganizationReadModelBindingError, } from "./organizationReadModelMembershipPersistence.js";
|
|
12
12
|
import { loadOrganizationReadModelProjectionInTransaction, } from "./organizationReadModelProjection.js";
|
|
13
13
|
import { loadWithOrganizationReadModelIntegrityPurge, pruneInactiveOrganizationRequestersInTransaction, purgeOrganizationReadModelProjectionInTransaction, } from "./organizationReadModelPurge.js";
|
|
14
14
|
import { assertOrganizationReadModelResponse } from "./organizationReadModelResponseAssertions.js";
|
|
15
|
-
const DIRECTORY_INSERT_BATCH_SIZE =
|
|
16
|
-
const GROUP_INSERT_BATCH_SIZE =
|
|
15
|
+
const DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelDirectoryUsers);
|
|
16
|
+
const GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelGroups);
|
|
17
17
|
async function replaceDirectoryLane(input) {
|
|
18
18
|
await input.tx
|
|
19
19
|
.delete(organizationReadModelDirectoryUsers)
|
|
@@ -73,43 +73,35 @@ async function upsertRequester(input) {
|
|
|
73
73
|
tx: input.tx,
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
|
-
/** The directory lane is the authoritative roster: requester rows for users
|
|
77
|
-
* it no longer lists as active must fall with it. */
|
|
78
|
-
async function pruneRequestersForDirectoryLane(input) {
|
|
79
|
-
await pruneInactiveOrganizationRequestersInTransaction({
|
|
80
|
-
activeUserIds: input.directory.users
|
|
81
|
-
.filter((user) => user.status === "active")
|
|
82
|
-
.map((user) => user.userId),
|
|
83
|
-
organizationId: input.organizationId,
|
|
84
|
-
retainUserId: input.currentUserId,
|
|
85
|
-
tx: input.tx,
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
76
|
async function replaceGroupsLane(input) {
|
|
77
|
+
// Hydrated names and delivered membership heads outlive a catalog
|
|
78
|
+
// replacement; the groupMemberships lane rebinds any head that changed.
|
|
89
79
|
const previousGroups = await input.tx
|
|
90
80
|
.select({
|
|
91
81
|
groupId: organizationReadModelGroups.groupId,
|
|
82
|
+
membersStateHash: organizationReadModelGroups.membersStateHash,
|
|
92
83
|
name: organizationReadModelGroups.name,
|
|
93
84
|
})
|
|
94
85
|
.from(organizationReadModelGroups)
|
|
95
86
|
.where(eq(organizationReadModelGroups.organizationId, input.organizationId));
|
|
96
|
-
const
|
|
87
|
+
const previousById = new Map(previousGroups.map((group) => [group.groupId, group]));
|
|
97
88
|
await input.tx
|
|
98
89
|
.delete(organizationReadModelGroups)
|
|
99
90
|
.where(eq(organizationReadModelGroups.organizationId, input.organizationId))
|
|
100
91
|
.run();
|
|
101
|
-
await replaceGroupPolicyHeads(input);
|
|
102
92
|
const rows = input.groups.groups.map((group, sortOrder) => ({
|
|
103
93
|
organizationId: input.organizationId,
|
|
104
94
|
groupId: group.groupId,
|
|
105
95
|
sortOrder,
|
|
106
|
-
name:
|
|
96
|
+
name: previousById.get(group.groupId)?.name ?? "",
|
|
107
97
|
createdAt: group.createdAt,
|
|
108
98
|
isBuiltin: group.isBuiltin,
|
|
109
99
|
stateHash: group.currentState?.stateHash ?? null,
|
|
110
100
|
stateVersion: group.currentState?.version ?? null,
|
|
111
101
|
keyEpoch: group.currentState?.keyEpoch ?? null,
|
|
102
|
+
keyFingerprint: group.currentState?.keyFingerprint ?? null,
|
|
112
103
|
memberCount: group.currentState?.memberCount ?? null,
|
|
104
|
+
membersStateHash: previousById.get(group.groupId)?.membersStateHash ?? null,
|
|
113
105
|
}));
|
|
114
106
|
for (let index = 0; index < rows.length; index += GROUP_INSERT_BATCH_SIZE) {
|
|
115
107
|
await input.tx
|
|
@@ -122,13 +114,32 @@ async function loadCurrentState(tx, organizationId) {
|
|
|
122
114
|
const [current] = await tx
|
|
123
115
|
.select({
|
|
124
116
|
cursor: organizationReadModelState.cursor,
|
|
117
|
+
keyEpoch: organizationReadModelState.organizationKeyEpoch,
|
|
118
|
+
keyFingerprint: organizationReadModelState.organizationKeyFingerprint,
|
|
119
|
+
memberCount: organizationReadModelState.organizationMemberCount,
|
|
125
120
|
memberGroupId: organizationReadModelState.memberGroupId,
|
|
121
|
+
memberGroupStateHash: organizationReadModelState.memberGroupStateHash,
|
|
126
122
|
profileDocumentId: organizationReadModelState.profileDocumentId,
|
|
123
|
+
stateHash: organizationReadModelState.organizationStateHash,
|
|
124
|
+
version: organizationReadModelState.organizationStateVersion,
|
|
127
125
|
})
|
|
128
126
|
.from(organizationReadModelState)
|
|
129
127
|
.where(eq(organizationReadModelState.organizationId, organizationId))
|
|
130
128
|
.limit(1);
|
|
131
|
-
|
|
129
|
+
if (!current) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
const { keyEpoch, keyFingerprint, memberCount, stateHash, version, ...rest } = current;
|
|
133
|
+
return {
|
|
134
|
+
...rest,
|
|
135
|
+
organizationHead: {
|
|
136
|
+
keyEpoch,
|
|
137
|
+
keyFingerprint,
|
|
138
|
+
memberCount,
|
|
139
|
+
stateHash,
|
|
140
|
+
version,
|
|
141
|
+
},
|
|
142
|
+
};
|
|
132
143
|
}
|
|
133
144
|
function resolveApplyDisposition(input) {
|
|
134
145
|
const currentCursor = input.current?.cursor ?? null;
|
|
@@ -142,67 +153,92 @@ function resolveApplyDisposition(input) {
|
|
|
142
153
|
}
|
|
143
154
|
return null;
|
|
144
155
|
}
|
|
156
|
+
/** Apply every carried lane and return the reserved Members head. */
|
|
145
157
|
async function replaceResponseLanes(input) {
|
|
158
|
+
const { organizationId } = input.response;
|
|
146
159
|
const directory = input.response.lanes.directory;
|
|
147
160
|
if (directory) {
|
|
148
|
-
await replaceDirectoryLane({
|
|
149
|
-
directory,
|
|
150
|
-
organizationId: input.response.organizationId,
|
|
151
|
-
tx: input.tx,
|
|
152
|
-
});
|
|
161
|
+
await replaceDirectoryLane({ directory, organizationId, tx: input.tx });
|
|
153
162
|
}
|
|
154
163
|
const groups = input.response.lanes.groups;
|
|
155
164
|
if (groups) {
|
|
156
|
-
await replaceGroupsLane({
|
|
157
|
-
groups,
|
|
158
|
-
organizationId: input.response.organizationId,
|
|
159
|
-
tx: input.tx,
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
const organizationPolicy = input.response.lanes.organizationPolicy;
|
|
163
|
-
if (organizationPolicy) {
|
|
164
|
-
await applyOrganizationPolicyLane({
|
|
165
|
-
organizationId: input.response.organizationId,
|
|
166
|
-
organizationPolicy,
|
|
167
|
-
tx: input.tx,
|
|
168
|
-
});
|
|
165
|
+
await replaceGroupsLane({ groups, organizationId, tx: input.tx });
|
|
169
166
|
}
|
|
170
167
|
const groupMemberships = input.response.lanes.groupMemberships;
|
|
171
|
-
|
|
172
|
-
await applyGroupMembershipsLane({
|
|
168
|
+
const memberGroupStateHash = groupMemberships
|
|
169
|
+
? await applyGroupMembershipsLane({
|
|
170
|
+
currentMemberGroupStateHash: input.current?.memberGroupStateHash ?? null,
|
|
173
171
|
lane: groupMemberships,
|
|
174
|
-
|
|
172
|
+
memberGroupId: input.memberGroupId,
|
|
173
|
+
organizationId,
|
|
175
174
|
replaceAll: input.response.mode === "snapshot",
|
|
176
175
|
tx: input.tx,
|
|
177
|
-
})
|
|
178
|
-
|
|
176
|
+
})
|
|
177
|
+
: (input.current?.memberGroupStateHash ?? null);
|
|
179
178
|
const grants = input.response.lanes.grants;
|
|
180
179
|
if (grants) {
|
|
181
180
|
await applyOrganizationReadModelGrantsLane({
|
|
182
181
|
lane: grants,
|
|
183
|
-
organizationId
|
|
182
|
+
organizationId,
|
|
184
183
|
tx: input.tx,
|
|
185
184
|
});
|
|
186
185
|
}
|
|
186
|
+
return memberGroupStateHash;
|
|
187
187
|
}
|
|
188
188
|
async function applyResponseLanes(input) {
|
|
189
|
-
await replaceResponseLanes(
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
directory: directoryLane,
|
|
189
|
+
const memberGroupStateHash = await replaceResponseLanes(input);
|
|
190
|
+
// The directory lane is the authoritative roster, already persisted above:
|
|
191
|
+
// requester rows for users it no longer lists as active fall with it.
|
|
192
|
+
if (input.response.lanes.directory) {
|
|
193
|
+
await pruneInactiveOrganizationRequestersInTransaction({
|
|
195
194
|
organizationId: input.response.organizationId,
|
|
195
|
+
retainUserId: input.currentUserId,
|
|
196
196
|
tx: input.tx,
|
|
197
197
|
});
|
|
198
198
|
}
|
|
199
199
|
if (input.response.lanes.groups || input.response.lanes.groupMemberships) {
|
|
200
200
|
await assertStoredGroupMembershipBindings({
|
|
201
201
|
memberGroupId: input.memberGroupId,
|
|
202
|
+
memberGroupStateHash,
|
|
202
203
|
organizationId: input.response.organizationId,
|
|
203
204
|
tx: input.tx,
|
|
204
205
|
});
|
|
205
206
|
}
|
|
207
|
+
return memberGroupStateHash;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Write the cursor with the organization policy head and the reserved Members
|
|
211
|
+
* head in one row, so a failure anywhere in the page rolls them back together.
|
|
212
|
+
*/
|
|
213
|
+
async function upsertOrganizationReadModelState(input) {
|
|
214
|
+
const organizationHead = input.response.lanes.organizationPolicy?.currentState ??
|
|
215
|
+
input.current?.organizationHead;
|
|
216
|
+
if (!organizationHead || input.memberGroupStateHash === null) {
|
|
217
|
+
throw new OrganizationReadModelBindingError("Organization read-model policy or Members head is missing");
|
|
218
|
+
}
|
|
219
|
+
const directoryLane = input.response.lanes.directory;
|
|
220
|
+
const values = {
|
|
221
|
+
cursor: input.response.nextCursor,
|
|
222
|
+
profileDocumentId: directoryLane !== undefined
|
|
223
|
+
? directoryLane.profileDocumentId
|
|
224
|
+
: (input.current?.profileDocumentId ?? null),
|
|
225
|
+
memberGroupId: input.memberGroupId,
|
|
226
|
+
memberGroupStateHash: input.memberGroupStateHash,
|
|
227
|
+
organizationStateHash: organizationHead.stateHash,
|
|
228
|
+
organizationStateVersion: organizationHead.version,
|
|
229
|
+
organizationKeyEpoch: organizationHead.keyEpoch,
|
|
230
|
+
organizationKeyFingerprint: organizationHead.keyFingerprint,
|
|
231
|
+
organizationMemberCount: organizationHead.memberCount,
|
|
232
|
+
updatedAt: input.now,
|
|
233
|
+
};
|
|
234
|
+
await input.tx
|
|
235
|
+
.insert(organizationReadModelState)
|
|
236
|
+
.values({ ...values, organizationId: input.response.organizationId })
|
|
237
|
+
.onConflictDoUpdate({
|
|
238
|
+
target: organizationReadModelState.organizationId,
|
|
239
|
+
set: values,
|
|
240
|
+
})
|
|
241
|
+
.run();
|
|
206
242
|
}
|
|
207
243
|
function requireMemberGroupId(input) {
|
|
208
244
|
const memberGroupId = input.response.lanes.groups?.memberGroupId ?? input.current?.memberGroupId;
|
|
@@ -257,35 +293,21 @@ export async function applyOrganizationReadModelResponse(input) {
|
|
|
257
293
|
current,
|
|
258
294
|
response: input.response,
|
|
259
295
|
});
|
|
260
|
-
await applyResponseLanes({
|
|
296
|
+
const memberGroupStateHash = await applyResponseLanes({
|
|
297
|
+
current,
|
|
261
298
|
currentUserId: input.currentUserId,
|
|
262
299
|
memberGroupId,
|
|
263
300
|
response: input.response,
|
|
264
301
|
tx,
|
|
265
302
|
});
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
organizationId: input.response.organizationId,
|
|
269
|
-
cursor: input.response.nextCursor,
|
|
270
|
-
profileDocumentId: directoryLane !== undefined
|
|
271
|
-
? directoryLane.profileDocumentId
|
|
272
|
-
: (current?.profileDocumentId ?? null),
|
|
303
|
+
await upsertOrganizationReadModelState({
|
|
304
|
+
current,
|
|
273
305
|
memberGroupId,
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
.onConflictDoUpdate({
|
|
280
|
-
target: organizationReadModelState.organizationId,
|
|
281
|
-
set: {
|
|
282
|
-
cursor: stateRow.cursor,
|
|
283
|
-
profileDocumentId: stateRow.profileDocumentId,
|
|
284
|
-
memberGroupId: stateRow.memberGroupId,
|
|
285
|
-
updatedAt: stateRow.updatedAt,
|
|
286
|
-
},
|
|
287
|
-
})
|
|
288
|
-
.run();
|
|
306
|
+
memberGroupStateHash,
|
|
307
|
+
now,
|
|
308
|
+
response: input.response,
|
|
309
|
+
tx,
|
|
310
|
+
});
|
|
289
311
|
return "applied";
|
|
290
312
|
});
|
|
291
313
|
// An applied change follows an organization hint or mutation; in-flight
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationReadModelPersistence.js","sourceRoot":"","sources":["organizationReadModelPersistence.ts"],"names":[],"mappings":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KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iDAAiD,CAAC;YACtD,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;YAChD,cAAc;YACd,EAAE;SACH,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationReadModelDirectoryResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport { invalidatePrincipalRecovery } from \"../../principals/principalRecoveryEpoch\";\nimport { organizationDataUsageTables } from \"../../sqlite/organizationDataUsageSchema\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/organizationReadModelSchema\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n} from \"./organizationReadModelMembershipPersistence\";\nimport {\n applyOrganizationPolicyLane,\n replaceGroupPolicyHeads,\n} from \"./organizationReadModelPolicyHeadPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport {\n loadWithOrganizationReadModelIntegrityPurge,\n pruneInactiveOrganizationRequestersInTransaction,\n purgeOrganizationReadModelProjectionInTransaction,\n} from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nexport type { OrganizationReadModelProjection } from \"./organizationReadModelProjection\";\n\nconst DIRECTORY_INSERT_BATCH_SIZE = 64;\nconst GROUP_INSERT_BATCH_SIZE = 90;\n\ntype ApplyOrganizationReadModelResponseResult =\n | \"already-applied\"\n | \"applied\"\n | \"stale\";\n\ninterface CurrentOrganizationReadModelState {\n readonly cursor: string;\n readonly memberGroupId: string;\n readonly profileDocumentId: string | null;\n}\n\nasync function replaceDirectoryLane(input: {\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await input.tx\n .delete(organizationReadModelDirectoryUsers)\n .where(\n eq(\n organizationReadModelDirectoryUsers.organizationId,\n input.organizationId,\n ),\n )\n .run();\n\n const rows = input.directory.users.map((user, sortOrder) => ({\n organizationId: input.organizationId,\n userId: user.userId,\n sortOrder,\n signingKeyFingerprint: user.signingKeyFingerprint,\n signingPublicKey: user.signingPublicKey,\n encapsulationPublicKey: user.encapsulationPublicKey,\n encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,\n isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,\n createdAt: user.createdAt,\n status: user.status,\n profileDocumentId: user.profileDocumentId,\n joinedAt: user.joinedAt,\n updatedAt: user.updatedAt,\n disabledAt: user.disabledAt,\n disabledByUserId: user.disabledByUserId,\n }));\n for (\n let index = 0;\n index < rows.length;\n index += DIRECTORY_INSERT_BATCH_SIZE\n ) {\n await input.tx\n .insert(organizationReadModelDirectoryUsers)\n .values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function upsertRequester(input: {\n readonly currentUserId: string;\n readonly isOrgAdmin: boolean;\n readonly now: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const requesterRow = {\n organizationId: input.organizationId,\n userId: input.currentUserId,\n isOrgAdmin: input.isOrgAdmin,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelRequesters)\n .values(requesterRow)\n .onConflictDoUpdate({\n target: [\n organizationReadModelRequesters.organizationId,\n organizationReadModelRequesters.userId,\n ],\n set: {\n isOrgAdmin: requesterRow.isOrgAdmin,\n updatedAt: requesterRow.updatedAt,\n },\n })\n .run();\n // Storing an authoritative response proves access: retire the durable\n // denial marker for this scope in the same transaction.\n await clearOrganizationPresentationDenialInTransaction({\n organizationId: input.organizationId,\n projection: \"readModel\",\n requesterUserId: input.currentUserId,\n tx: input.tx,\n });\n}\n\n/** The directory lane is the authoritative roster: requester rows for users\n * it no longer lists as active must fall with it. */\nasync function pruneRequestersForDirectoryLane(input: {\n readonly currentUserId: string;\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await pruneInactiveOrganizationRequestersInTransaction({\n activeUserIds: input.directory.users\n .filter((user) => user.status === \"active\")\n .map((user) => user.userId),\n organizationId: input.organizationId,\n retainUserId: input.currentUserId,\n tx: input.tx,\n });\n}\n\nasync function replaceGroupsLane(input: {\n readonly groups: ListOrganizationGroupsResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const previousGroups = await input.tx\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(\n eq(organizationReadModelGroups.organizationId, input.organizationId),\n );\n const names = new Map(\n previousGroups.map((group) => [group.groupId, group.name]),\n );\n await input.tx\n .delete(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, input.organizationId))\n .run();\n await replaceGroupPolicyHeads(input);\n\n const rows = input.groups.groups.map((group, sortOrder) => ({\n organizationId: input.organizationId,\n groupId: group.groupId,\n sortOrder,\n name: names.get(group.groupId) ?? \"\",\n createdAt: group.createdAt,\n isBuiltin: group.isBuiltin,\n stateHash: group.currentState?.stateHash ?? null,\n stateVersion: group.currentState?.version ?? null,\n keyEpoch: group.currentState?.keyEpoch ?? null,\n memberCount: group.currentState?.memberCount ?? null,\n }));\n for (let index = 0; index < rows.length; index += GROUP_INSERT_BATCH_SIZE) {\n await input.tx\n .insert(organizationReadModelGroups)\n .values(rows.slice(index, index + GROUP_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function loadCurrentState(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<CurrentOrganizationReadModelState | null> {\n const [current] = await tx\n .select({\n cursor: organizationReadModelState.cursor,\n memberGroupId: organizationReadModelState.memberGroupId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n return current ?? null;\n}\n\nfunction resolveApplyDisposition(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): ApplyOrganizationReadModelResponseResult | null {\n const currentCursor = input.current?.cursor ?? null;\n if (currentCursor !== input.requestedCursor) {\n return currentCursor === input.response.nextCursor\n ? \"already-applied\"\n : \"stale\";\n }\n if (!input.current && input.response.mode !== \"snapshot\") {\n throw new Error(\"Organization read-model delta requires a local snapshot\");\n }\n return null;\n}\n\nasync function replaceResponseLanes(input: {\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const directory = input.response.lanes.directory;\n if (directory) {\n await replaceDirectoryLane({\n directory,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n const groups = input.response.lanes.groups;\n if (groups) {\n await replaceGroupsLane({\n groups,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n const organizationPolicy = input.response.lanes.organizationPolicy;\n if (organizationPolicy) {\n await applyOrganizationPolicyLane({\n organizationId: input.response.organizationId,\n organizationPolicy,\n tx: input.tx,\n });\n }\n const groupMemberships = input.response.lanes.groupMemberships;\n if (groupMemberships) {\n await applyGroupMembershipsLane({\n lane: groupMemberships,\n organizationId: input.response.organizationId,\n replaceAll: input.response.mode === \"snapshot\",\n tx: input.tx,\n });\n }\n const grants = input.response.lanes.grants;\n if (grants) {\n await applyOrganizationReadModelGrantsLane({\n lane: grants,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n}\n\nasync function applyResponseLanes(input: {\n readonly currentUserId: string;\n readonly memberGroupId: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await replaceResponseLanes({ response: input.response, tx: input.tx });\n const directoryLane = input.response.lanes.directory;\n if (directoryLane) {\n await pruneRequestersForDirectoryLane({\n currentUserId: input.currentUserId,\n directory: directoryLane,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n if (input.response.lanes.groups || input.response.lanes.groupMemberships) {\n await assertStoredGroupMembershipBindings({\n memberGroupId: input.memberGroupId,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n}\n\nfunction requireMemberGroupId(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly response: OrganizationReadModelResponse;\n}): string {\n const memberGroupId =\n input.response.lanes.groups?.memberGroupId ?? input.current?.memberGroupId;\n if (!memberGroupId) {\n throw new Error(\"Organization read-model member group is missing\");\n }\n return memberGroupId;\n}\n\nexport async function loadOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n currentUserId: string,\n): Promise<OrganizationReadModelProjection | null> {\n return loadWithOrganizationReadModelIntegrityPurge({\n execSql,\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n}\n\nexport async function applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune below also retires pruned users' usage projections.\n await ensureSqlTables(input.execSql, [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n ]);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n input.execSql,\n ).transaction(\n async (tx): Promise<ApplyOrganizationReadModelResponseResult> => {\n const current = await loadCurrentState(tx, input.response.organizationId);\n const disposition = resolveApplyDisposition({\n current,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n if (disposition === \"stale\") {\n return disposition;\n }\n const now = new Date().toISOString();\n await upsertRequester({\n currentUserId: input.currentUserId,\n isOrgAdmin: input.response.currentUser.isOrgAdmin,\n now,\n organizationId: input.response.organizationId,\n tx,\n });\n if (disposition === \"already-applied\") {\n return disposition;\n }\n const memberGroupId = requireMemberGroupId({\n current,\n response: input.response,\n });\n await applyResponseLanes({\n currentUserId: input.currentUserId,\n memberGroupId,\n response: input.response,\n tx,\n });\n const directoryLane = input.response.lanes.directory;\n const stateRow = {\n organizationId: input.response.organizationId,\n cursor: input.response.nextCursor,\n profileDocumentId:\n directoryLane !== undefined\n ? directoryLane.profileDocumentId\n : (current?.profileDocumentId ?? null),\n memberGroupId,\n updatedAt: now,\n };\n await tx\n .insert(organizationReadModelState)\n .values(stateRow)\n .onConflictDoUpdate({\n target: organizationReadModelState.organizationId,\n set: {\n cursor: stateRow.cursor,\n profileDocumentId: stateRow.profileDocumentId,\n memberGroupId: stateRow.memberGroupId,\n updatedAt: stateRow.updatedAt,\n },\n })\n .run();\n\n return \"applied\";\n },\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n invalidatePrincipalRecovery(input.execSql, input.response.organizationId);\n return disposition;\n}\n\nexport async function purgeOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n): Promise<void> {\n await ensureSqlTables(execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationReadModelPersistence.js","s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E,CAAC;YACtC,OAAO,WAAW,CAAC;QACrB,CAAC;QACD,MAAM,aAAa,GAAG,oBAAoB,CAAC;YACzC,OAAO;YACP,QAAQ,EAAE,KAAK,CAAC,QAAQ;SACzB,CAAC,CAAC;QACH,MAAM,oBAAoB,GAAG,MAAM,kBAAkB,CAAC;YACpD,OAAO;YACP,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,aAAa;YACb,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QACH,MAAM,gCAAgC,CAAC;YACrC,OAAO;YACP,aAAa;YACb,oBAAoB;YACpB,GAAG;YACH,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;IACF,wEAAwE;IACxE,wEAAwE;IACxE,IAAI,WAAW,KAAK,SAAS;QAC3B,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC5E,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,cAAsB,EACtB,UAAqD,EAAE;IAEvD,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iDAAiD,CAAC;YACtD,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;YAChD,cAAc;YACd,EAAE;SACH,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationReadModelDirectoryResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport { invalidatePrincipalRecovery } from \"../../principals/principalRecoveryEpoch\";\nimport { organizationDataUsageTables } from \"../../sqlite/organizationDataUsageSchema\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/organizationReadModelSchema\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { sqliteInsertBatchSize } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n OrganizationReadModelBindingError,\n} from \"./organizationReadModelMembershipPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport {\n loadWithOrganizationReadModelIntegrityPurge,\n pruneInactiveOrganizationRequestersInTransaction,\n purgeOrganizationReadModelProjectionInTransaction,\n} from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nexport type { OrganizationReadModelProjection } from \"./organizationReadModelProjection\";\n\nconst DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelDirectoryUsers,\n);\nconst GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelGroups,\n);\n\ntype ApplyOrganizationReadModelResponseResult =\n | \"already-applied\"\n | \"applied\"\n | \"stale\";\n\ninterface CurrentOrganizationReadModelState {\n readonly cursor: string;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string;\n readonly organizationHead: OrganizationGroupCurrentStateResponse;\n readonly profileDocumentId: string | null;\n}\n\nasync function replaceDirectoryLane(input: {\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await input.tx\n .delete(organizationReadModelDirectoryUsers)\n .where(\n eq(\n organizationReadModelDirectoryUsers.organizationId,\n input.organizationId,\n ),\n )\n .run();\n\n const rows = input.directory.users.map((user, sortOrder) => ({\n organizationId: input.organizationId,\n userId: user.userId,\n sortOrder,\n signingKeyFingerprint: user.signingKeyFingerprint,\n signingPublicKey: user.signingPublicKey,\n encapsulationPublicKey: user.encapsulationPublicKey,\n encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,\n isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,\n createdAt: user.createdAt,\n status: user.status,\n profileDocumentId: user.profileDocumentId,\n joinedAt: user.joinedAt,\n updatedAt: user.updatedAt,\n disabledAt: user.disabledAt,\n disabledByUserId: user.disabledByUserId,\n }));\n for (\n let index = 0;\n index < rows.length;\n index += DIRECTORY_INSERT_BATCH_SIZE\n ) {\n await input.tx\n .insert(organizationReadModelDirectoryUsers)\n .values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function upsertRequester(input: {\n readonly currentUserId: string;\n readonly isOrgAdmin: boolean;\n readonly now: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const requesterRow = {\n organizationId: input.organizationId,\n userId: input.currentUserId,\n isOrgAdmin: input.isOrgAdmin,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelRequesters)\n .values(requesterRow)\n .onConflictDoUpdate({\n target: [\n organizationReadModelRequesters.organizationId,\n organizationReadModelRequesters.userId,\n ],\n set: {\n isOrgAdmin: requesterRow.isOrgAdmin,\n updatedAt: requesterRow.updatedAt,\n },\n })\n .run();\n // Storing an authoritative response proves access: retire the durable\n // denial marker for this scope in the same transaction.\n await clearOrganizationPresentationDenialInTransaction({\n organizationId: input.organizationId,\n projection: \"readModel\",\n requesterUserId: input.currentUserId,\n tx: input.tx,\n });\n}\n\nasync function replaceGroupsLane(input: {\n readonly groups: ListOrganizationGroupsResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // Hydrated names and delivered membership heads outlive a catalog\n // replacement; the groupMemberships lane rebinds any head that changed.\n const previousGroups = await input.tx\n .select({\n groupId: organizationReadModelGroups.groupId,\n membersStateHash: organizationReadModelGroups.membersStateHash,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(\n eq(organizationReadModelGroups.organizationId, input.organizationId),\n );\n const previousById = new Map(\n previousGroups.map((group) => [group.groupId, group]),\n );\n await input.tx\n .delete(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, input.organizationId))\n .run();\n\n const rows = input.groups.groups.map((group, sortOrder) => ({\n organizationId: input.organizationId,\n groupId: group.groupId,\n sortOrder,\n name: previousById.get(group.groupId)?.name ?? \"\",\n createdAt: group.createdAt,\n isBuiltin: group.isBuiltin,\n stateHash: group.currentState?.stateHash ?? null,\n stateVersion: group.currentState?.version ?? null,\n keyEpoch: group.currentState?.keyEpoch ?? null,\n keyFingerprint: group.currentState?.keyFingerprint ?? null,\n memberCount: group.currentState?.memberCount ?? null,\n membersStateHash: previousById.get(group.groupId)?.membersStateHash ?? null,\n }));\n for (let index = 0; index < rows.length; index += GROUP_INSERT_BATCH_SIZE) {\n await input.tx\n .insert(organizationReadModelGroups)\n .values(rows.slice(index, index + GROUP_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function loadCurrentState(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<CurrentOrganizationReadModelState | null> {\n const [current] = await tx\n .select({\n cursor: organizationReadModelState.cursor,\n keyEpoch: organizationReadModelState.organizationKeyEpoch,\n keyFingerprint: organizationReadModelState.organizationKeyFingerprint,\n memberCount: organizationReadModelState.organizationMemberCount,\n memberGroupId: organizationReadModelState.memberGroupId,\n memberGroupStateHash: organizationReadModelState.memberGroupStateHash,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n stateHash: organizationReadModelState.organizationStateHash,\n version: organizationReadModelState.organizationStateVersion,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n if (!current) {\n return null;\n }\n const { keyEpoch, keyFingerprint, memberCount, stateHash, version, ...rest } =\n current;\n return {\n ...rest,\n organizationHead: {\n keyEpoch,\n keyFingerprint,\n memberCount,\n stateHash,\n version,\n },\n };\n}\n\nfunction resolveApplyDisposition(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): ApplyOrganizationReadModelResponseResult | null {\n const currentCursor = input.current?.cursor ?? null;\n if (currentCursor !== input.requestedCursor) {\n return currentCursor === input.response.nextCursor\n ? \"already-applied\"\n : \"stale\";\n }\n if (!input.current && input.response.mode !== \"snapshot\") {\n throw new Error(\"Organization read-model delta requires a local snapshot\");\n }\n return null;\n}\n\ninterface ResponseLanesInput {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}\n\n/** Apply every carried lane and return the reserved Members head. */\nasync function replaceResponseLanes(\n input: ResponseLanesInput,\n): Promise<string | null> {\n const { organizationId } = input.response;\n const directory = input.response.lanes.directory;\n if (directory) {\n await replaceDirectoryLane({ directory, organizationId, tx: input.tx });\n }\n const groups = input.response.lanes.groups;\n if (groups) {\n await replaceGroupsLane({ groups, organizationId, tx: input.tx });\n }\n const groupMemberships = input.response.lanes.groupMemberships;\n const memberGroupStateHash = groupMemberships\n ? await applyGroupMembershipsLane({\n currentMemberGroupStateHash:\n input.current?.memberGroupStateHash ?? null,\n lane: groupMemberships,\n memberGroupId: input.memberGroupId,\n organizationId,\n replaceAll: input.response.mode === \"snapshot\",\n tx: input.tx,\n })\n : (input.current?.memberGroupStateHash ?? null);\n const grants = input.response.lanes.grants;\n if (grants) {\n await applyOrganizationReadModelGrantsLane({\n lane: grants,\n organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\nasync function applyResponseLanes(\n input: ResponseLanesInput & { readonly currentUserId: string },\n): Promise<string | null> {\n const memberGroupStateHash = await replaceResponseLanes(input);\n // The directory lane is the authoritative roster, already persisted above:\n // requester rows for users it no longer lists as active fall with it.\n if (input.response.lanes.directory) {\n await pruneInactiveOrganizationRequestersInTransaction({\n organizationId: input.response.organizationId,\n retainUserId: input.currentUserId,\n tx: input.tx,\n });\n }\n if (input.response.lanes.groups || input.response.lanes.groupMemberships) {\n await assertStoredGroupMembershipBindings({\n memberGroupId: input.memberGroupId,\n memberGroupStateHash,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\n/**\n * Write the cursor with the organization policy head and the reserved Members\n * head in one row, so a failure anywhere in the page rolls them back together.\n */\nasync function upsertOrganizationReadModelState(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string | null;\n readonly now: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const organizationHead =\n input.response.lanes.organizationPolicy?.currentState ??\n input.current?.organizationHead;\n if (!organizationHead || input.memberGroupStateHash === null) {\n throw new OrganizationReadModelBindingError(\n \"Organization read-model policy or Members head is missing\",\n );\n }\n const directoryLane = input.response.lanes.directory;\n const values = {\n cursor: input.response.nextCursor,\n profileDocumentId:\n directoryLane !== undefined\n ? directoryLane.profileDocumentId\n : (input.current?.profileDocumentId ?? null),\n memberGroupId: input.memberGroupId,\n memberGroupStateHash: input.memberGroupStateHash,\n organizationStateHash: organizationHead.stateHash,\n organizationStateVersion: organizationHead.version,\n organizationKeyEpoch: organizationHead.keyEpoch,\n organizationKeyFingerprint: organizationHead.keyFingerprint,\n organizationMemberCount: organizationHead.memberCount,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelState)\n .values({ ...values, organizationId: input.response.organizationId })\n .onConflictDoUpdate({\n target: organizationReadModelState.organizationId,\n set: values,\n })\n .run();\n}\n\nfunction requireMemberGroupId(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly response: OrganizationReadModelResponse;\n}): string {\n const memberGroupId =\n input.response.lanes.groups?.memberGroupId ?? input.current?.memberGroupId;\n if (!memberGroupId) {\n throw new Error(\"Organization read-model member group is missing\");\n }\n return memberGroupId;\n}\n\nexport async function loadOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n currentUserId: string,\n): Promise<OrganizationReadModelProjection | null> {\n return loadWithOrganizationReadModelIntegrityPurge({\n execSql,\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n}\n\nexport async function applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune below also retires pruned users' usage projections.\n await ensureSqlTables(input.execSql, [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n ]);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n input.execSql,\n ).transaction(\n async (tx): Promise<ApplyOrganizationReadModelResponseResult> => {\n const current = await loadCurrentState(tx, input.response.organizationId);\n const disposition = resolveApplyDisposition({\n current,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n if (disposition === \"stale\") {\n return disposition;\n }\n const now = new Date().toISOString();\n await upsertRequester({\n currentUserId: input.currentUserId,\n isOrgAdmin: input.response.currentUser.isOrgAdmin,\n now,\n organizationId: input.response.organizationId,\n tx,\n });\n if (disposition === \"already-applied\") {\n return disposition;\n }\n const memberGroupId = requireMemberGroupId({\n current,\n response: input.response,\n });\n const memberGroupStateHash = await applyResponseLanes({\n current,\n currentUserId: input.currentUserId,\n memberGroupId,\n response: input.response,\n tx,\n });\n await upsertOrganizationReadModelState({\n current,\n memberGroupId,\n memberGroupStateHash,\n now,\n response: input.response,\n tx,\n });\n\n return \"applied\";\n },\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n invalidatePrincipalRecovery(input.execSql, input.response.organizationId);\n return disposition;\n}\n\nexport async function purgeOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n): Promise<void> {\n await ensureSqlTables(execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n });\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { compareCanonicalStrings } from "../../../internal/crypto/index.js";
|
|
1
2
|
import { and, asc, eq } from "drizzle-orm";
|
|
2
|
-
import { organizationReadModelDirectoryUsers, organizationReadModelGroupMembers, organizationReadModelGroups,
|
|
3
|
+
import { organizationReadModelDirectoryUsers, organizationReadModelGroupMembers, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/organizationReadModelSchema.js";
|
|
3
4
|
import { loadOrganizationReadModelGrantsInTransaction } from "./organizationReadModelGrantPersistence.js";
|
|
4
5
|
import { ORGANIZATION_READ_MODEL_PROTOCOL_VERSION, OrganizationReadModelIntegrityError, } from "./organizationReadModelProtocol.js";
|
|
5
6
|
function isOrganizationRosterStatus(value) {
|
|
@@ -26,69 +27,77 @@ function toDirectoryUser(row, currentUserId) {
|
|
|
26
27
|
disabledByUserId: row.disabledByUserId,
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
+
function isValidPolicyHead(head) {
|
|
31
|
+
return (head.stateHash.length > 0 &&
|
|
32
|
+
Number.isInteger(head.version) &&
|
|
33
|
+
head.version > 0 &&
|
|
34
|
+
Number.isSafeInteger(head.keyEpoch) &&
|
|
35
|
+
head.keyEpoch > 0 &&
|
|
36
|
+
head.keyFingerprint.length > 0 &&
|
|
37
|
+
Number.isInteger(head.memberCount) &&
|
|
38
|
+
head.memberCount >= 0);
|
|
39
|
+
}
|
|
40
|
+
/** A group's state columns are all null (stateless) or one valid head. */
|
|
41
|
+
function toGroupCurrentState(row) {
|
|
30
42
|
const values = [
|
|
31
43
|
row.stateHash,
|
|
32
44
|
row.stateVersion,
|
|
33
45
|
row.keyEpoch,
|
|
46
|
+
row.keyFingerprint,
|
|
34
47
|
row.memberCount,
|
|
35
48
|
];
|
|
36
49
|
if (values.every((value) => value === null)) {
|
|
37
|
-
if (policyHead) {
|
|
38
|
-
throw new OrganizationReadModelIntegrityError("Stored organization group policy head is orphaned");
|
|
39
|
-
}
|
|
40
50
|
return null;
|
|
41
51
|
}
|
|
42
|
-
|
|
52
|
+
const head = row.stateHash === null ||
|
|
43
53
|
row.stateVersion === null ||
|
|
44
54
|
row.keyEpoch === null ||
|
|
45
|
-
row.
|
|
46
|
-
row.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
policyHead.keyEpoch !== row.keyEpoch ||
|
|
57
|
-
policyHead.memberCount !== row.memberCount) {
|
|
55
|
+
row.keyFingerprint === null ||
|
|
56
|
+
row.memberCount === null
|
|
57
|
+
? null
|
|
58
|
+
: {
|
|
59
|
+
stateHash: row.stateHash,
|
|
60
|
+
version: row.stateVersion,
|
|
61
|
+
keyEpoch: row.keyEpoch,
|
|
62
|
+
keyFingerprint: row.keyFingerprint,
|
|
63
|
+
memberCount: row.memberCount,
|
|
64
|
+
};
|
|
65
|
+
if (!head || !isValidPolicyHead(head)) {
|
|
58
66
|
throw new OrganizationReadModelIntegrityError("Stored organization group state is invalid");
|
|
59
67
|
}
|
|
60
|
-
return
|
|
61
|
-
stateHash: row.stateHash,
|
|
62
|
-
version: row.stateVersion,
|
|
63
|
-
keyEpoch: row.keyEpoch,
|
|
64
|
-
keyFingerprint: policyHead.keyFingerprint,
|
|
65
|
-
memberCount: row.memberCount,
|
|
66
|
-
};
|
|
68
|
+
return head;
|
|
67
69
|
}
|
|
68
|
-
function
|
|
69
|
-
if ((
|
|
70
|
-
row.principalId.length === 0 ||
|
|
71
|
-
row.stateHash.length === 0 ||
|
|
72
|
-
!Number.isInteger(row.stateVersion) ||
|
|
73
|
-
row.stateVersion <= 0 ||
|
|
74
|
-
!Number.isSafeInteger(row.keyEpoch) ||
|
|
75
|
-
row.keyEpoch <= 0 ||
|
|
76
|
-
row.keyFingerprint.length === 0 ||
|
|
77
|
-
!Number.isInteger(row.memberCount) ||
|
|
78
|
-
row.memberCount < 0) {
|
|
70
|
+
function toOrganizationPolicyHead(organizationId, head) {
|
|
71
|
+
if (!isValidPolicyHead(head)) {
|
|
79
72
|
throw new OrganizationReadModelIntegrityError("Stored organization policy head is invalid");
|
|
80
73
|
}
|
|
81
74
|
return {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
principalId:
|
|
85
|
-
|
|
86
|
-
version: row.stateVersion,
|
|
87
|
-
keyEpoch: row.keyEpoch,
|
|
88
|
-
keyFingerprint: row.keyFingerprint,
|
|
89
|
-
memberCount: row.memberCount,
|
|
75
|
+
...head,
|
|
76
|
+
organizationId,
|
|
77
|
+
principalId: organizationId,
|
|
78
|
+
principalType: "organization",
|
|
90
79
|
};
|
|
91
80
|
}
|
|
81
|
+
/** The organization head from the state row plus every stateful group head. */
|
|
82
|
+
function toProjectionPolicyHeads(input) {
|
|
83
|
+
const groupHeads = input.groups
|
|
84
|
+
.flatMap((group) => group.currentState
|
|
85
|
+
? [
|
|
86
|
+
{
|
|
87
|
+
...group.currentState,
|
|
88
|
+
organizationId: input.organizationId,
|
|
89
|
+
principalId: group.groupId,
|
|
90
|
+
principalType: "group",
|
|
91
|
+
},
|
|
92
|
+
]
|
|
93
|
+
: [])
|
|
94
|
+
.sort((left, right) => compareCanonicalStrings(left.principalId, right.principalId));
|
|
95
|
+
// Group heads precede the organization head, ordered by principal ID.
|
|
96
|
+
return [
|
|
97
|
+
...groupHeads,
|
|
98
|
+
toOrganizationPolicyHead(input.organizationId, input.organizationHead),
|
|
99
|
+
];
|
|
100
|
+
}
|
|
92
101
|
async function loadDirectoryRows(tx, organizationId) {
|
|
93
102
|
return tx
|
|
94
103
|
.select({
|
|
@@ -117,6 +126,7 @@ async function loadGroupRows(tx, organizationId) {
|
|
|
117
126
|
groupId: organizationReadModelGroups.groupId,
|
|
118
127
|
isBuiltin: organizationReadModelGroups.isBuiltin,
|
|
119
128
|
keyEpoch: organizationReadModelGroups.keyEpoch,
|
|
129
|
+
keyFingerprint: organizationReadModelGroups.keyFingerprint,
|
|
120
130
|
memberCount: organizationReadModelGroups.memberCount,
|
|
121
131
|
name: organizationReadModelGroups.name,
|
|
122
132
|
stateHash: organizationReadModelGroups.stateHash,
|
|
@@ -126,22 +136,6 @@ async function loadGroupRows(tx, organizationId) {
|
|
|
126
136
|
.where(eq(organizationReadModelGroups.organizationId, organizationId))
|
|
127
137
|
.orderBy(asc(organizationReadModelGroups.sortOrder), asc(organizationReadModelGroups.groupId));
|
|
128
138
|
}
|
|
129
|
-
async function loadPolicyHeadRows(tx, organizationId) {
|
|
130
|
-
return tx
|
|
131
|
-
.select({
|
|
132
|
-
keyEpoch: organizationReadModelPolicyHeads.keyEpoch,
|
|
133
|
-
keyFingerprint: organizationReadModelPolicyHeads.keyFingerprint,
|
|
134
|
-
memberCount: organizationReadModelPolicyHeads.memberCount,
|
|
135
|
-
organizationId: organizationReadModelPolicyHeads.organizationId,
|
|
136
|
-
principalId: organizationReadModelPolicyHeads.principalId,
|
|
137
|
-
principalType: organizationReadModelPolicyHeads.principalType,
|
|
138
|
-
stateHash: organizationReadModelPolicyHeads.stateHash,
|
|
139
|
-
stateVersion: organizationReadModelPolicyHeads.stateVersion,
|
|
140
|
-
})
|
|
141
|
-
.from(organizationReadModelPolicyHeads)
|
|
142
|
-
.where(eq(organizationReadModelPolicyHeads.organizationId, organizationId))
|
|
143
|
-
.orderBy(asc(organizationReadModelPolicyHeads.principalType), asc(organizationReadModelPolicyHeads.principalId));
|
|
144
|
-
}
|
|
145
139
|
async function loadMembershipEdges(tx, organizationId) {
|
|
146
140
|
return tx
|
|
147
141
|
.select({
|
|
@@ -152,27 +146,16 @@ async function loadMembershipEdges(tx, organizationId) {
|
|
|
152
146
|
.where(eq(organizationReadModelGroupMembers.organizationId, organizationId))
|
|
153
147
|
.orderBy(asc(organizationReadModelGroupMembers.groupId), asc(organizationReadModelGroupMembers.sortOrder), asc(organizationReadModelGroupMembers.userId));
|
|
154
148
|
}
|
|
155
|
-
function validatePolicyHeads(input) {
|
|
156
|
-
const policyHeads = input.policyHeadRows.map(toPolicyHead);
|
|
157
|
-
const organizationPolicyHeads = policyHeads.filter((head) => head.principalType === "organization");
|
|
158
|
-
if (organizationPolicyHeads.length !== 1 ||
|
|
159
|
-
organizationPolicyHeads[0]?.principalId !== input.organizationId) {
|
|
160
|
-
throw new OrganizationReadModelIntegrityError("Stored organization policy head is missing or ambiguous");
|
|
161
|
-
}
|
|
162
|
-
const groupPolicyHeads = new Map(policyHeads
|
|
163
|
-
.filter((head) => head.principalType === "group")
|
|
164
|
-
.map((head) => [head.principalId, head]));
|
|
165
|
-
const visibleGroupIds = new Set(input.groupRows.map((row) => row.groupId));
|
|
166
|
-
if ([...groupPolicyHeads.keys()].some((principalId) => !visibleGroupIds.has(principalId))) {
|
|
167
|
-
throw new OrganizationReadModelIntegrityError("Stored organization group policy head is not visible");
|
|
168
|
-
}
|
|
169
|
-
return { groupPolicyHeads, policyHeads };
|
|
170
|
-
}
|
|
171
149
|
export async function loadOrganizationReadModelProjectionInTransaction(input) {
|
|
172
150
|
const [state] = await input.tx
|
|
173
151
|
.select({
|
|
174
152
|
cursor: organizationReadModelState.cursor,
|
|
175
153
|
memberGroupId: organizationReadModelState.memberGroupId,
|
|
154
|
+
organizationKeyEpoch: organizationReadModelState.organizationKeyEpoch,
|
|
155
|
+
organizationKeyFingerprint: organizationReadModelState.organizationKeyFingerprint,
|
|
156
|
+
organizationMemberCount: organizationReadModelState.organizationMemberCount,
|
|
157
|
+
organizationStateHash: organizationReadModelState.organizationStateHash,
|
|
158
|
+
organizationStateVersion: organizationReadModelState.organizationStateVersion,
|
|
176
159
|
profileDocumentId: organizationReadModelState.profileDocumentId,
|
|
177
160
|
updatedAt: organizationReadModelState.updatedAt,
|
|
178
161
|
})
|
|
@@ -191,11 +174,24 @@ export async function loadOrganizationReadModelProjectionInTransaction(input) {
|
|
|
191
174
|
const groupRows = await loadGroupRows(input.tx, input.organizationId);
|
|
192
175
|
const grants = await loadOrganizationReadModelGrantsInTransaction(input);
|
|
193
176
|
const membershipEdges = await loadMembershipEdges(input.tx, input.organizationId);
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
177
|
+
const groups = groupRows.map((row) => ({
|
|
178
|
+
groupId: row.groupId,
|
|
179
|
+
organizationId: input.organizationId,
|
|
180
|
+
name: row.name,
|
|
181
|
+
createdAt: row.createdAt,
|
|
182
|
+
isBuiltin: row.isBuiltin,
|
|
183
|
+
currentState: toGroupCurrentState(row),
|
|
184
|
+
}));
|
|
185
|
+
const policyHeads = toProjectionPolicyHeads({
|
|
186
|
+
groups,
|
|
187
|
+
organizationHead: {
|
|
188
|
+
keyEpoch: state.organizationKeyEpoch,
|
|
189
|
+
keyFingerprint: state.organizationKeyFingerprint,
|
|
190
|
+
memberCount: state.organizationMemberCount,
|
|
191
|
+
stateHash: state.organizationStateHash,
|
|
192
|
+
version: state.organizationStateVersion,
|
|
193
|
+
},
|
|
197
194
|
organizationId: input.organizationId,
|
|
198
|
-
policyHeadRows,
|
|
199
195
|
});
|
|
200
196
|
return {
|
|
201
197
|
cursor: state.cursor,
|
|
@@ -208,14 +204,7 @@ export async function loadOrganizationReadModelProjectionInTransaction(input) {
|
|
|
208
204
|
groups: {
|
|
209
205
|
organizationId: input.organizationId,
|
|
210
206
|
memberGroupId: state.memberGroupId,
|
|
211
|
-
groups
|
|
212
|
-
groupId: row.groupId,
|
|
213
|
-
organizationId: input.organizationId,
|
|
214
|
-
name: row.name,
|
|
215
|
-
createdAt: row.createdAt,
|
|
216
|
-
isBuiltin: row.isBuiltin,
|
|
217
|
-
currentState: toGroupCurrentState(row, groupPolicyHeads.get(row.groupId)),
|
|
218
|
-
})),
|
|
207
|
+
groups,
|
|
219
208
|
},
|
|
220
209
|
membershipEdges,
|
|
221
210
|
organizationId: input.organizationId,
|