@tearleads/client-sdk 0.1.237 → 0.1.239
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/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +0 -2
- package/data/persistence/documents/records/documentSyncFailurePersistence.js +0 -2
- package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelDirectoryPersistence.js +88 -0
- package/data/persistence/organizations/organizationReadModelDirectoryPersistence.js.map +1 -0
- package/data/persistence/organizations/organizationReadModelPersistence.js +8 -46
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelProjection.js +0 -4
- package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
- package/data/sqlite/migrations/localSchemaMigrations.js +30 -1
- package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
- package/data/sqlite/schema/documentRecordSchema.js +4 -6
- package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +0 -55
- package/data/sqlite/schema/organizationReadModelSchema.js +4 -3
- package/data/sqlite/schema/organizationReadModelSchema.js.map +1 -1
- package/data/sqlite/schema/organizationReadModelTableRegistry.d.ts +0 -38
- package/internal/api-client/ApiClient.d.ts +0 -6
- package/internal/api-client/client/organizations.d.ts +0 -6
- package/internal/validators/operation/organizations.d.ts +0 -32
- package/internal/validators/response/organization.d.ts +5 -63
- package/internal/validators/response/organization.js +5 -7
- package/internal/validators/response/organization.js.map +1 -1
- package/internal/validators/response/organizationReadModel.d.ts +3 -23
- package/internal/validators/response/organizationReadModel.js +4 -7
- package/internal/validators/response/organizationReadModel.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js +0 -1
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +0 -1
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
|
@@ -3,13 +3,11 @@ import type { DocumentScope } from "./documentPersistenceTypes.js";
|
|
|
3
3
|
export interface DocumentSyncFailureFields {
|
|
4
4
|
readonly attemptedAt: string;
|
|
5
5
|
readonly message: string;
|
|
6
|
-
readonly status: number | null;
|
|
7
6
|
}
|
|
8
7
|
/** The `documents` column values of a scope with no recorded failure. */
|
|
9
8
|
export declare const CLEARED_DOCUMENT_SYNC_FAILURE: {
|
|
10
9
|
readonly syncFailureAttemptedAt: null;
|
|
11
10
|
readonly syncFailureMessage: null;
|
|
12
|
-
readonly syncFailureStatus: null;
|
|
13
11
|
};
|
|
14
12
|
/**
|
|
15
13
|
* Record the last terminal failure or incoming-update quarantine on a document
|
|
@@ -5,7 +5,6 @@ import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
|
|
|
5
5
|
export const CLEARED_DOCUMENT_SYNC_FAILURE = {
|
|
6
6
|
syncFailureAttemptedAt: null,
|
|
7
7
|
syncFailureMessage: null,
|
|
8
|
-
syncFailureStatus: null,
|
|
9
8
|
};
|
|
10
9
|
function scopeWhere(scope) {
|
|
11
10
|
return and(eq(documents.appKind, scope.appKind), eq(documents.localId, scope.localId));
|
|
@@ -23,7 +22,6 @@ export async function recordDocumentSyncFailureInTransaction(tx, scope, failure)
|
|
|
23
22
|
.set({
|
|
24
23
|
syncFailureAttemptedAt: failure.attemptedAt,
|
|
25
24
|
syncFailureMessage: failure.message,
|
|
26
|
-
syncFailureStatus: failure.status,
|
|
27
25
|
})
|
|
28
26
|
.where(scopeWhere(scope))
|
|
29
27
|
.run();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentSyncFailurePersistence.js","sourceRoot":"","sources":["documentSyncFailurePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;
|
|
1
|
+
{"version":3,"file":"documentSyncFailurePersistence.js","sourceRoot":"","sources":["documentSyncFailurePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AASxE,yEAAyE;AACzE,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,sBAAsB,EAAE,IAAI;IAC5B,kBAAkB,EAAE,IAAI;CAChB,CAAC;AAEX,SAAS,UAAU,CAAC,KAAoB;IACtC,OAAO,GAAG,CACR,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,EACpC,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,CACrC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,EAAgC,EAChC,KAAoB,EACpB,OAAkC;IAElC,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,GAAG,CAAC;QACH,sBAAsB,EAAE,OAAO,CAAC,WAAW;QAC3C,kBAAkB,EAAE,OAAO,CAAC,OAAO;KACpC,CAAC;SACD,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;SACxB,GAAG,EAAE,CAAC;AACX,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAgD;IAEhD,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE;SACvB,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;SACtC,IAAI,CAAC,SAAS,CAAC;SACf,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAC;SAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC,EAAE,EAAE,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC;SAC/B,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CAAC,SAAS,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;SACxC,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,MAAM,KAAK,SAAS,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,EAAgC,EAChC,KAAoB;IAEpB,MAAM,EAAE;SACL,MAAM,CAAC,SAAS,CAAC;SACjB,GAAG,CAAC,6BAA6B,CAAC;SAClC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;SACxB,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { localIntents } from \"../../../sqlite/schema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { DocumentScope } from \"./documentPersistenceTypes\";\n\nexport interface DocumentSyncFailureFields {\n readonly attemptedAt: string;\n readonly message: string;\n}\n\n/** The `documents` column values of a scope with no recorded failure. */\nexport const CLEARED_DOCUMENT_SYNC_FAILURE = {\n syncFailureAttemptedAt: null,\n syncFailureMessage: null,\n} as const;\n\nfunction scopeWhere(scope: DocumentScope) {\n return and(\n eq(documents.appKind, scope.appKind),\n eq(documents.localId, scope.localId),\n );\n}\n\n/**\n * Record the last terminal failure or incoming-update quarantine on a document\n * scope's row. The durable pending-update queue has no status columns, so\n * these columns let the write-queue view explain a blocked document. A newer\n * failure replaces the old. A scope with no `documents` row has nothing left\n * to explain, so the update is a no-op there.\n */\nexport async function recordDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n failure: DocumentSyncFailureFields,\n): Promise<void> {\n await tx\n .update(documents)\n .set({\n syncFailureAttemptedAt: failure.attemptedAt,\n syncFailureMessage: failure.message,\n })\n .where(scopeWhere(scope))\n .run();\n}\n\n/**\n * Whether any queued local write has recorded a terminal failure — a document\n * row carrying a sync failure or an intent row carrying `last_error`. This is\n * the evidence gate for recovery triggers (e.g. re-arming write lanes when org\n * access is restored): without it a transient denial during bootstrap would\n * fire recovery work with nothing to recover, racing the startup sync passes.\n */\nexport async function selectHasRecordedTerminalSyncFailures(\n db: Pick<ClientSQLiteTransactionScope, \"select\">,\n): Promise<boolean> {\n const [failure] = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(isNotNull(documents.syncFailureMessage))\n .limit(1);\n if (failure) {\n return true;\n }\n const [intent] = await db\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(isNotNull(localIntents.lastError))\n .limit(1);\n return intent !== undefined;\n}\n\n/**\n * Clear a scope's recorded failure inside a caller's transaction. Called when\n * a later sync pass for the scope succeeds and whenever the scope's local sync\n * state is torn down, so a stale failure never outlives the condition it\n * describes.\n */\nexport async function clearDocumentSyncFailureInTransaction(\n tx: ClientSQLiteTransactionScope,\n scope: DocumentScope,\n): Promise<void> {\n await tx\n .update(documents)\n .set(CLEARED_DOCUMENT_SYNC_FAILURE)\n .where(scopeWhere(scope))\n .run();\n}\n"]}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { and, eq, getTableColumns, inArray } from "drizzle-orm";
|
|
2
|
+
import { organizationReadModelDirectoryUsers as directoryUsers } from "../../sqlite/schema/organizationReadModelSchema.js";
|
|
3
|
+
import { sqliteInsertBatchSize, sqliteRowsPerStatement, } from "../../sqlite/sqliteBindBudget.js";
|
|
4
|
+
import { excludedValue } from "../../sqlite/sqliteUpsert.js";
|
|
5
|
+
const DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(directoryUsers);
|
|
6
|
+
// The organization id binds once; each removed user binds one more.
|
|
7
|
+
const DIRECTORY_DELETE_BATCH_SIZE = sqliteRowsPerStatement(1, 1);
|
|
8
|
+
// A changed row takes every non-key column from the row the delta carried.
|
|
9
|
+
const directoryUpsertSet = Object.fromEntries(Object.entries(getTableColumns(directoryUsers))
|
|
10
|
+
.filter(([key]) => key !== "organizationId" && key !== "userId")
|
|
11
|
+
.map(([key, column]) => [key, excludedValue(column)]));
|
|
12
|
+
/**
|
|
13
|
+
* The member's leave request as stored JSON, kept only when it names this
|
|
14
|
+
* organization and member. Its signature is checked when read, against the
|
|
15
|
+
* member's trusted identity rather than anything the directory served.
|
|
16
|
+
*/
|
|
17
|
+
function storedLeaveRequestJson(organizationId, user) {
|
|
18
|
+
const request = user.leaveRequest;
|
|
19
|
+
return request &&
|
|
20
|
+
request.organizationId === organizationId &&
|
|
21
|
+
request.userId === user.userId
|
|
22
|
+
? JSON.stringify(request)
|
|
23
|
+
: null;
|
|
24
|
+
}
|
|
25
|
+
function toDirectoryRows(directory, organizationId) {
|
|
26
|
+
return directory.users.map((user, sortOrder) => ({
|
|
27
|
+
organizationId,
|
|
28
|
+
userId: user.userId,
|
|
29
|
+
sortOrder,
|
|
30
|
+
signingKeyFingerprint: user.signingKeyFingerprint,
|
|
31
|
+
encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,
|
|
32
|
+
isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,
|
|
33
|
+
createdAt: user.createdAt,
|
|
34
|
+
status: user.status,
|
|
35
|
+
profileDocumentId: user.profileDocumentId,
|
|
36
|
+
joinedAt: user.joinedAt,
|
|
37
|
+
updatedAt: user.updatedAt,
|
|
38
|
+
disabledAt: user.disabledAt,
|
|
39
|
+
disabledByUserId: user.disabledByUserId,
|
|
40
|
+
leaveRequest: storedLeaveRequestJson(organizationId, user),
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
function sameDirectoryRow(stored, next) {
|
|
44
|
+
if (!stored)
|
|
45
|
+
return false;
|
|
46
|
+
return Object.entries(next).every(([key, value]) => Reflect.get(stored, key) === value);
|
|
47
|
+
}
|
|
48
|
+
async function insertDirectoryRows(tx, rows, upsert) {
|
|
49
|
+
for (let index = 0; index < rows.length; index += DIRECTORY_INSERT_BATCH_SIZE) {
|
|
50
|
+
const insert = tx
|
|
51
|
+
.insert(directoryUsers)
|
|
52
|
+
.values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE));
|
|
53
|
+
await (upsert
|
|
54
|
+
? insert.onConflictDoUpdate({
|
|
55
|
+
target: [directoryUsers.organizationId, directoryUsers.userId],
|
|
56
|
+
set: directoryUpsertSet,
|
|
57
|
+
})
|
|
58
|
+
: insert).run();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Makes the stored directory equal the lane. A snapshot replaces every row;
|
|
63
|
+
* a delta, which repeats the whole lane, writes only the rows that differ and
|
|
64
|
+
* deletes users it no longer lists, so one changed member costs one row.
|
|
65
|
+
*/
|
|
66
|
+
export async function applyDirectoryLane(input) {
|
|
67
|
+
const rows = toDirectoryRows(input.directory, input.organizationId);
|
|
68
|
+
const scope = eq(directoryUsers.organizationId, input.organizationId);
|
|
69
|
+
if (input.replaceAll) {
|
|
70
|
+
await input.tx.delete(directoryUsers).where(scope).run();
|
|
71
|
+
await insertDirectoryRows(input.tx, rows, false);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const stored = await input.tx.select().from(directoryUsers).where(scope);
|
|
75
|
+
const storedByUserId = new Map(stored.map((row) => [row.userId, row]));
|
|
76
|
+
const listed = new Set(rows.map((row) => row.userId));
|
|
77
|
+
const removedUserIds = stored
|
|
78
|
+
.map((row) => row.userId)
|
|
79
|
+
.filter((userId) => !listed.has(userId));
|
|
80
|
+
for (let index = 0; index < removedUserIds.length; index += DIRECTORY_DELETE_BATCH_SIZE) {
|
|
81
|
+
await input.tx
|
|
82
|
+
.delete(directoryUsers)
|
|
83
|
+
.where(and(scope, inArray(directoryUsers.userId, removedUserIds.slice(index, index + DIRECTORY_DELETE_BATCH_SIZE))))
|
|
84
|
+
.run();
|
|
85
|
+
}
|
|
86
|
+
await insertDirectoryRows(input.tx, rows.filter((row) => !sameDirectoryRow(storedByUserId.get(row.userId), row)), true);
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=organizationReadModelDirectoryPersistence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"organizationReadModelDirectoryPersistence.js","sourceRoot":"","sources":["organizationReadModelDirectoryPersistence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,mCAAmC,IAAI,cAAc,EAAE,MAAM,iDAAiD,CAAC;AACxH,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAI1D,MAAM,2BAA2B,GAAG,qBAAqB,CAAC,cAAc,CAAC,CAAC;AAC1E,oEAAoE;AACpE,MAAM,2BAA2B,GAAG,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAEjE,2EAA2E;AAC3E,MAAM,kBAAkB,GAAG,MAAM,CAAC,WAAW,CAC3C,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC;KAC5C,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,gBAAgB,IAAI,GAAG,KAAK,QAAQ,CAAC;KAC/D,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CACxD,CAAC;AAEF;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,cAAsB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E,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACvE,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IACtD,MAAM,cAAc,GAAG,MAAM;SAC1B,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC;SACxB,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3C,KACE,IAAI,KAAK,GAAG,CAAC,EACb,KAAK,GAAG,cAAc,CAAC,MAAM,EAC7B,KAAK,IAAI,2BAA2B,EACpC,CAAC;QACD,MAAM,KAAK,CAAC,EAAE;aACX,MAAM,CAAC,cAAc,CAAC;aACtB,KAAK,CACJ,GAAG,CACD,KAAK,EACL,OAAO,CACL,cAAc,CAAC,MAAM,EACrB,cAAc,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,2BAA2B,CAAC,CACjE,CACF,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC;IACD,MAAM,mBAAmB,CACvB,KAAK,CAAC,EAAE,EACR,IAAI,CAAC,MAAM,CACT,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,gBAAgB,CAAC,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,CAChE,EACD,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import type { OrganizationReadModelDirectoryResponse } from \"@tearleads/validators/response\";\nimport { and, eq, getTableColumns, inArray } from \"drizzle-orm\";\nimport { organizationReadModelDirectoryUsers as directoryUsers } from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n sqliteInsertBatchSize,\n sqliteRowsPerStatement,\n} from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../sqlite/sqliteUpsert\";\n\ntype DirectoryRow = typeof directoryUsers.$inferSelect;\n\nconst DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(directoryUsers);\n// The organization id binds once; each removed user binds one more.\nconst DIRECTORY_DELETE_BATCH_SIZE = sqliteRowsPerStatement(1, 1);\n\n// A changed row takes every non-key column from the row the delta carried.\nconst directoryUpsertSet = Object.fromEntries(\n Object.entries(getTableColumns(directoryUsers))\n .filter(([key]) => key !== \"organizationId\" && key !== \"userId\")\n .map(([key, column]) => [key, excludedValue(column)]),\n);\n\n/**\n * The member's leave request as stored JSON, kept only when it names this\n * organization and member. Its signature is checked when read, against the\n * member's trusted identity rather than anything the directory served.\n */\nfunction storedLeaveRequestJson(\n organizationId: string,\n user: OrganizationReadModelDirectoryResponse[\"users\"][number],\n): string | null {\n const request = user.leaveRequest;\n return request &&\n request.organizationId === organizationId &&\n request.userId === user.userId\n ? JSON.stringify(request)\n : null;\n}\n\nfunction toDirectoryRows(\n directory: OrganizationReadModelDirectoryResponse,\n organizationId: string,\n): DirectoryRow[] {\n return directory.users.map((user, sortOrder) => ({\n organizationId,\n userId: user.userId,\n sortOrder,\n signingKeyFingerprint: user.signingKeyFingerprint,\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 leaveRequest: storedLeaveRequestJson(organizationId, user),\n }));\n}\n\nfunction sameDirectoryRow(\n stored: DirectoryRow | undefined,\n next: DirectoryRow,\n): boolean {\n if (!stored) return false;\n return Object.entries(next).every(\n ([key, value]) => Reflect.get(stored, key) === value,\n );\n}\n\nasync function insertDirectoryRows(\n tx: ClientSQLiteTransactionScope,\n rows: ReadonlyArray<DirectoryRow>,\n upsert: boolean,\n): Promise<void> {\n for (\n let index = 0;\n index < rows.length;\n index += DIRECTORY_INSERT_BATCH_SIZE\n ) {\n const insert = tx\n .insert(directoryUsers)\n .values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE));\n await (upsert\n ? insert.onConflictDoUpdate({\n target: [directoryUsers.organizationId, directoryUsers.userId],\n set: directoryUpsertSet,\n })\n : insert\n ).run();\n }\n}\n\n/**\n * Makes the stored directory equal the lane. A snapshot replaces every row;\n * a delta, which repeats the whole lane, writes only the rows that differ and\n * deletes users it no longer lists, so one changed member costs one row.\n */\nexport async function applyDirectoryLane(input: {\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly replaceAll: boolean;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const rows = toDirectoryRows(input.directory, input.organizationId);\n const scope = eq(directoryUsers.organizationId, input.organizationId);\n if (input.replaceAll) {\n await input.tx.delete(directoryUsers).where(scope).run();\n await insertDirectoryRows(input.tx, rows, false);\n return;\n }\n\n const stored = await input.tx.select().from(directoryUsers).where(scope);\n const storedByUserId = new Map(stored.map((row) => [row.userId, row]));\n const listed = new Set(rows.map((row) => row.userId));\n const removedUserIds = stored\n .map((row) => row.userId)\n .filter((userId) => !listed.has(userId));\n for (\n let index = 0;\n index < removedUserIds.length;\n index += DIRECTORY_DELETE_BATCH_SIZE\n ) {\n await input.tx\n .delete(directoryUsers)\n .where(\n and(\n scope,\n inArray(\n directoryUsers.userId,\n removedUserIds.slice(index, index + DIRECTORY_DELETE_BATCH_SIZE),\n ),\n ),\n )\n .run();\n }\n await insertDirectoryRows(\n input.tx,\n rows.filter(\n (row) => !sameDirectoryRow(storedByUserId.get(row.userId), row),\n ),\n true,\n );\n}\n"]}
|
|
@@ -1,55 +1,12 @@
|
|
|
1
1
|
import { eq } from "drizzle-orm";
|
|
2
|
-
import {
|
|
2
|
+
import { organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/schema/organizationReadModelSchema.js";
|
|
3
3
|
import { sqliteInsertBatchSize } from "../../sqlite/sqliteBindBudget.js";
|
|
4
4
|
import { clearOrganizationPresentationDenialInTransaction } from "./organizationPresentationDenialPersistence.js";
|
|
5
|
+
import { applyDirectoryLane } from "./organizationReadModelDirectoryPersistence.js";
|
|
5
6
|
import { applyOrganizationReadModelGrantsLane } from "./organizationReadModelGrantPersistence.js";
|
|
6
7
|
import { applyGroupMembershipsLane, assertStoredGroupMembershipBindings, OrganizationReadModelBindingError, } from "./organizationReadModelMembershipPersistence.js";
|
|
7
8
|
import { pruneInactiveOrganizationRequestersInTransaction } from "./organizationReadModelPurge.js";
|
|
8
|
-
const DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelDirectoryUsers);
|
|
9
9
|
const GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelGroups);
|
|
10
|
-
/**
|
|
11
|
-
* The member's leave request as stored JSON, kept only when it names this
|
|
12
|
-
* organization and member. Its signature is checked when read, against the
|
|
13
|
-
* member's trusted identity rather than the key served beside it.
|
|
14
|
-
*/
|
|
15
|
-
function storedLeaveRequestJson(organizationId, user) {
|
|
16
|
-
const request = user.leaveRequest;
|
|
17
|
-
return request &&
|
|
18
|
-
request.organizationId === organizationId &&
|
|
19
|
-
request.userId === user.userId
|
|
20
|
-
? JSON.stringify(request)
|
|
21
|
-
: null;
|
|
22
|
-
}
|
|
23
|
-
async function replaceDirectoryLane(input) {
|
|
24
|
-
await input.tx
|
|
25
|
-
.delete(organizationReadModelDirectoryUsers)
|
|
26
|
-
.where(eq(organizationReadModelDirectoryUsers.organizationId, input.organizationId))
|
|
27
|
-
.run();
|
|
28
|
-
const rows = input.directory.users.map((user, sortOrder) => ({
|
|
29
|
-
organizationId: input.organizationId,
|
|
30
|
-
userId: user.userId,
|
|
31
|
-
sortOrder,
|
|
32
|
-
signingKeyFingerprint: user.signingKeyFingerprint,
|
|
33
|
-
signingPublicKey: user.signingPublicKey,
|
|
34
|
-
encapsulationPublicKey: user.encapsulationPublicKey,
|
|
35
|
-
encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,
|
|
36
|
-
isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,
|
|
37
|
-
createdAt: user.createdAt,
|
|
38
|
-
status: user.status,
|
|
39
|
-
profileDocumentId: user.profileDocumentId,
|
|
40
|
-
joinedAt: user.joinedAt,
|
|
41
|
-
updatedAt: user.updatedAt,
|
|
42
|
-
disabledAt: user.disabledAt,
|
|
43
|
-
disabledByUserId: user.disabledByUserId,
|
|
44
|
-
leaveRequest: storedLeaveRequestJson(input.organizationId, user),
|
|
45
|
-
}));
|
|
46
|
-
for (let index = 0; index < rows.length; index += DIRECTORY_INSERT_BATCH_SIZE) {
|
|
47
|
-
await input.tx
|
|
48
|
-
.insert(organizationReadModelDirectoryUsers)
|
|
49
|
-
.values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE))
|
|
50
|
-
.run();
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
10
|
async function upsertRequester(input) {
|
|
54
11
|
const requesterRow = {
|
|
55
12
|
organizationId: input.organizationId,
|
|
@@ -167,7 +124,12 @@ async function replaceResponseLanes(input) {
|
|
|
167
124
|
const { organizationId } = input.response;
|
|
168
125
|
const directory = input.response.lanes.directory;
|
|
169
126
|
if (directory) {
|
|
170
|
-
await
|
|
127
|
+
await applyDirectoryLane({
|
|
128
|
+
directory,
|
|
129
|
+
organizationId,
|
|
130
|
+
replaceAll: input.response.mode === "snapshot",
|
|
131
|
+
tx: input.tx,
|
|
132
|
+
});
|
|
171
133
|
}
|
|
172
134
|
const groups = input.response.lanes.groups;
|
|
173
135
|
if (groups) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationReadMod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,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationReadModelDirectoryResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport { sqliteInsertBatchSize } from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n OrganizationReadModelBindingError,\n} from \"./organizationReadModelMembershipPersistence\";\nimport { pruneInactiveOrganizationRequestersInTransaction } from \"./organizationReadModelPurge\";\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\nexport type 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\n/**\n * The member's leave request as stored JSON, kept only when it names this\n * organization and member. Its signature is checked when read, against the\n * member's trusted identity rather than the key served beside it.\n */\nfunction storedLeaveRequestJson(\n organizationId: string,\n user: OrganizationReadModelDirectoryResponse[\"users\"][number],\n): string | null {\n const request = user.leaveRequest;\n return request &&\n request.organizationId === organizationId &&\n request.userId === user.userId\n ? JSON.stringify(request)\n : 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 leaveRequest: storedLeaveRequestJson(input.organizationId, user),\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 appliedCursor: string;\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 appliedCursor: input.appliedCursor,\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 appliedCursor: requesterRow.appliedCursor,\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\n/** The transaction body of applying one read-model response. */\nexport async function applyOrganizationReadModelResponseInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly currentUserId: string;\n readonly now: () => Date;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n },\n): 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 = input.now().toISOString();\n await upsertRequester({\n appliedCursor: input.response.nextCursor,\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"]}
|
|
1
|
+
{"version":3,"file":"organizationReadModelPersistence.js","sourceRoot":"","sources":["organization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E,CAAC;QAC5B,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC;IACtC,MAAM,eAAe,CAAC;QACpB,aAAa,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;QACxC,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU;QACjD,GAAG;QACH,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;QAC7C,EAAE;KACH,CAAC,CAAC;IACH,IAAI,WAAW,KAAK,iBAAiB,EAAE,CAAC;QACtC,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,MAAM,aAAa,GAAG,oBAAoB,CAAC;QACzC,OAAO;QACP,QAAQ,EAAE,KAAK,CAAC,QAAQ;KACzB,CAAC,CAAC;IACH,MAAM,oBAAoB,GAAG,MAAM,kBAAkB,CAAC;QACpD,OAAO;QACP,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,aAAa;QACb,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,EAAE;KACH,CAAC,CAAC;IACH,MAAM,gCAAgC,CAAC;QACrC,OAAO;QACP,aAAa;QACb,oBAAoB;QACpB,GAAG;QACH,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,EAAE;KACH,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport {\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport { sqliteInsertBatchSize } from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyDirectoryLane } from \"./organizationReadModelDirectoryPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n OrganizationReadModelBindingError,\n} from \"./organizationReadModelMembershipPersistence\";\nimport { pruneInactiveOrganizationRequestersInTransaction } from \"./organizationReadModelPurge\";\n\nexport type { OrganizationReadModelProjection } from \"./organizationReadModelProjection\";\n\nconst GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelGroups,\n);\n\nexport type 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 upsertRequester(input: {\n readonly appliedCursor: string;\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 appliedCursor: input.appliedCursor,\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 appliedCursor: requesterRow.appliedCursor,\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 applyDirectoryLane({\n directory,\n organizationId,\n replaceAll: input.response.mode === \"snapshot\",\n tx: input.tx,\n });\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\n/** The transaction body of applying one read-model response. */\nexport async function applyOrganizationReadModelResponseInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly currentUserId: string;\n readonly now: () => Date;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n },\n): 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 = input.now().toISOString();\n await upsertRequester({\n appliedCursor: input.response.nextCursor,\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"]}
|
|
@@ -14,8 +14,6 @@ function toDirectoryUser(row, currentUserId) {
|
|
|
14
14
|
return {
|
|
15
15
|
userId: row.userId,
|
|
16
16
|
signingKeyFingerprint: row.signingKeyFingerprint,
|
|
17
|
-
signingPublicKey: row.signingPublicKey,
|
|
18
|
-
encapsulationPublicKey: row.encapsulationPublicKey,
|
|
19
17
|
encapsulationKeyFingerprint: row.encapsulationKeyFingerprint,
|
|
20
18
|
createdAt: row.createdAt,
|
|
21
19
|
isPersonalOrganizationOwner: row.isPersonalOrganizationOwner,
|
|
@@ -116,13 +114,11 @@ async function loadDirectoryRows(tx, organizationId) {
|
|
|
116
114
|
disabledAt: organizationReadModelDirectoryUsers.disabledAt,
|
|
117
115
|
disabledByUserId: organizationReadModelDirectoryUsers.disabledByUserId,
|
|
118
116
|
encapsulationKeyFingerprint: organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,
|
|
119
|
-
encapsulationPublicKey: organizationReadModelDirectoryUsers.encapsulationPublicKey,
|
|
120
117
|
joinedAt: organizationReadModelDirectoryUsers.joinedAt,
|
|
121
118
|
leaveRequest: organizationReadModelDirectoryUsers.leaveRequest,
|
|
122
119
|
isPersonalOrganizationOwner: organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,
|
|
123
120
|
profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,
|
|
124
121
|
signingKeyFingerprint: organizationReadModelDirectoryUsers.signingKeyFingerprint,
|
|
125
|
-
signingPublicKey: organizationReadModelDirectoryUsers.signingPublicKey,
|
|
126
122
|
status: organizationReadModelDirectoryUsers.status,
|
|
127
123
|
updatedAt: organizationReadModelDirectoryUsers.updatedAt,
|
|
128
124
|
userId: organizationReadModelDirectoryUsers.userId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationReadModelProjection.js","sourceRoot":"","sources":["organizationReadModelProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAS5D,OAAO,EACL,0BAA0B,GAE3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,mCAAmC,EACnC,iCAAiC,EACjC,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AAEzD,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AC;QAC1C,MAAM;QACN,gBAAgB,EAAE;YAChB,QAAQ,EAAE,KAAK,CAAC,oBAAoB;YACpC,cAAc,EAAE,KAAK,CAAC,0BAA0B;YAChD,WAAW,EAAE,KAAK,CAAC,uBAAuB;YAC1C,SAAS,EAAE,KAAK,CAAC,qBAAqB;YACtC,OAAO,EAAE,KAAK,CAAC,wBAAwB;SACxC;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IAEH,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,SAAS,EAAE;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC/B,eAAe,CAAC,GAAG,EAAE,KAAK,CAAC,aAAa,CAAC,CAC1C;SACF;QACD,MAAM;QACN,MAAM,EAAE;YACN,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,MAAM;SACP;QACD,eAAe;QACf,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW;QACX,eAAe,EAAE,wCAAwC;QACzD,SAAS,EACP,KAAK,CAAC,mBAAmB,KAAK,IAAI;YAChC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,mBAAmB,EAAE;QAC/C,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport type {\n ListOrganizationGroupsResponse,\n OrganizationContainerGrantsResponse,\n OrganizationDirectoryResponse,\n OrganizationDirectoryUserResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationRosterStatus,\n} from \"@tearleads/validators/response\";\nimport {\n isOrganizationLeaveRequest,\n type OrganizationLeaveRequest,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadOrganizationReadModelGrantsInTransaction } from \"./organizationReadModelGrantPersistence\";\nimport {\n ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n OrganizationReadModelIntegrityError,\n} from \"./organizationReadModelProtocol\";\n\nexport type OrganizationDirectoryProjection = Omit<\n OrganizationDirectoryResponse,\n \"currentUser\"\n>;\n\nexport interface OrganizationReadModelProjection {\n readonly cursor: string;\n readonly directory: OrganizationDirectoryProjection;\n readonly grants: OrganizationContainerGrantsResponse;\n readonly groups: Omit<ListOrganizationGroupsResponse, \"groups\"> & {\n groups: Array<\n ListOrganizationGroupsResponse[\"groups\"][number] & { name: string }\n >;\n };\n readonly membershipEdges: OrganizationReadModelMembershipEdge[];\n readonly organizationId: string;\n readonly policyHeads: readonly OrganizationReadModelPolicyHead[];\n readonly protocolVersion: typeof ORGANIZATION_READ_MODEL_PROTOCOL_VERSION;\n readonly requester: OrganizationDirectoryResponse[\"currentUser\"] | null;\n readonly updatedAt: string;\n}\n\nexport interface OrganizationReadModelPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly organizationId: string;\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n readonly stateHash: string;\n readonly version: number;\n}\n\nexport interface OrganizationReadModelMembershipEdge {\n readonly groupId: string;\n readonly userId: string;\n}\n\ninterface SelectedDirectoryUser {\n readonly createdAt: string;\n readonly disabledAt: string | null;\n readonly disabledByUserId: string | null;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly isPersonalOrganizationOwner: boolean;\n readonly joinedAt: string;\n readonly leaveRequest: string | null;\n readonly profileDocumentId: string | null;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly status: string;\n readonly updatedAt: string;\n readonly userId: string;\n}\n\ninterface SelectedGroup {\n readonly createdAt: string;\n readonly groupId: string;\n readonly isBuiltin: boolean;\n readonly keyEpoch: number | null;\n readonly keyFingerprint: string | null;\n readonly memberCount: number | null;\n readonly name: string;\n readonly stateHash: string | null;\n readonly stateVersion: number | null;\n}\n\n/** A stored policy head before validation; `version` is the state version. */\ninterface StoredPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isOrganizationRosterStatus(\n value: string,\n): value is OrganizationRosterStatus {\n return value === \"active\" || value === \"disabled\";\n}\n\nfunction toDirectoryUser(\n row: SelectedDirectoryUser,\n currentUserId: string,\n): OrganizationDirectoryUserResponse {\n if (!isOrganizationRosterStatus(row.status)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization directory status is invalid\",\n );\n }\n\n return {\n userId: row.userId,\n signingKeyFingerprint: row.signingKeyFingerprint,\n signingPublicKey: row.signingPublicKey,\n encapsulationPublicKey: row.encapsulationPublicKey,\n encapsulationKeyFingerprint: row.encapsulationKeyFingerprint,\n createdAt: row.createdAt,\n isPersonalOrganizationOwner: row.isPersonalOrganizationOwner,\n isSelf: row.userId === currentUserId,\n status: row.status,\n profileDocumentId: row.profileDocumentId,\n joinedAt: row.joinedAt,\n leaveRequest: readStoredLeaveRequest(row.leaveRequest),\n updatedAt: row.updatedAt,\n disabledAt: row.disabledAt,\n disabledByUserId: row.disabledByUserId,\n };\n}\n\nfunction readStoredLeaveRequest(\n stored: string | null,\n): OrganizationLeaveRequest | null {\n if (stored === null) return null;\n const parsed: unknown = JSON.parse(stored);\n if (!isOrganizationLeaveRequest(parsed)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization leave request is invalid\",\n );\n }\n return parsed;\n}\n\nfunction isValidPolicyHead(head: StoredPolicyHead): boolean {\n return (\n head.stateHash.length > 0 &&\n Number.isInteger(head.version) &&\n head.version > 0 &&\n Number.isSafeInteger(head.keyEpoch) &&\n head.keyEpoch > 0 &&\n head.keyFingerprint.length > 0 &&\n Number.isInteger(head.memberCount) &&\n head.memberCount >= 0\n );\n}\n\n/** A group's state columns are all null (stateless) or one valid head. */\nfunction toGroupCurrentState(\n row: SelectedGroup,\n): OrganizationGroupCurrentStateResponse | null {\n const values = [\n row.stateHash,\n row.stateVersion,\n row.keyEpoch,\n row.keyFingerprint,\n row.memberCount,\n ];\n if (values.every((value) => value === null)) {\n return null;\n }\n const head =\n row.stateHash === null ||\n row.stateVersion === null ||\n row.keyEpoch === null ||\n row.keyFingerprint === null ||\n row.memberCount === null\n ? null\n : {\n stateHash: row.stateHash,\n version: row.stateVersion,\n keyEpoch: row.keyEpoch,\n keyFingerprint: row.keyFingerprint,\n memberCount: row.memberCount,\n };\n if (!head || !isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization group state is invalid\",\n );\n }\n return head;\n}\n\nfunction toOrganizationPolicyHead(\n organizationId: string,\n head: StoredPolicyHead,\n): OrganizationReadModelPolicyHead {\n if (!isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization policy head is invalid\",\n );\n }\n return {\n ...head,\n organizationId,\n principalId: organizationId,\n principalType: \"organization\",\n };\n}\n\n/** The organization head from the state row plus every stateful group head. */\nfunction toProjectionPolicyHeads(input: {\n readonly groups: ReadonlyArray<{\n readonly currentState: OrganizationGroupCurrentStateResponse | null;\n readonly groupId: string;\n }>;\n readonly organizationHead: StoredPolicyHead;\n readonly organizationId: string;\n}): OrganizationReadModelPolicyHead[] {\n const groupHeads = input.groups\n .flatMap((group): OrganizationReadModelPolicyHead[] =>\n group.currentState\n ? [\n {\n ...group.currentState,\n organizationId: input.organizationId,\n principalId: group.groupId,\n principalType: \"group\",\n },\n ]\n : [],\n )\n .sort((left, right) =>\n compareCanonicalStrings(left.principalId, right.principalId),\n );\n // Group heads precede the organization head, ordered by principal ID.\n return [\n ...groupHeads,\n toOrganizationPolicyHead(input.organizationId, input.organizationHead),\n ];\n}\n\nasync function loadDirectoryRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedDirectoryUser[]> {\n return tx\n .select({\n createdAt: organizationReadModelDirectoryUsers.createdAt,\n disabledAt: organizationReadModelDirectoryUsers.disabledAt,\n disabledByUserId: organizationReadModelDirectoryUsers.disabledByUserId,\n encapsulationKeyFingerprint:\n organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,\n encapsulationPublicKey:\n organizationReadModelDirectoryUsers.encapsulationPublicKey,\n joinedAt: organizationReadModelDirectoryUsers.joinedAt,\n leaveRequest: organizationReadModelDirectoryUsers.leaveRequest,\n isPersonalOrganizationOwner:\n organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,\n profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,\n signingKeyFingerprint:\n organizationReadModelDirectoryUsers.signingKeyFingerprint,\n signingPublicKey: organizationReadModelDirectoryUsers.signingPublicKey,\n status: organizationReadModelDirectoryUsers.status,\n updatedAt: organizationReadModelDirectoryUsers.updatedAt,\n userId: organizationReadModelDirectoryUsers.userId,\n })\n .from(organizationReadModelDirectoryUsers)\n .where(\n eq(organizationReadModelDirectoryUsers.organizationId, organizationId),\n )\n .orderBy(\n asc(organizationReadModelDirectoryUsers.sortOrder),\n asc(organizationReadModelDirectoryUsers.userId),\n );\n}\n\nasync function loadGroupRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedGroup[]> {\n return tx\n .select({\n createdAt: organizationReadModelGroups.createdAt,\n groupId: organizationReadModelGroups.groupId,\n isBuiltin: organizationReadModelGroups.isBuiltin,\n keyEpoch: organizationReadModelGroups.keyEpoch,\n keyFingerprint: organizationReadModelGroups.keyFingerprint,\n memberCount: organizationReadModelGroups.memberCount,\n name: organizationReadModelGroups.name,\n stateHash: organizationReadModelGroups.stateHash,\n stateVersion: organizationReadModelGroups.stateVersion,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroups.sortOrder),\n asc(organizationReadModelGroups.groupId),\n );\n}\n\nasync function loadMembershipEdges(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<OrganizationReadModelMembershipEdge[]> {\n return tx\n .select({\n groupId: organizationReadModelGroupMembers.groupId,\n userId: organizationReadModelGroupMembers.userId,\n })\n .from(organizationReadModelGroupMembers)\n .where(eq(organizationReadModelGroupMembers.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroupMembers.groupId),\n asc(organizationReadModelGroupMembers.sortOrder),\n asc(organizationReadModelGroupMembers.userId),\n );\n}\n\nexport async function loadOrganizationReadModelProjectionInTransaction(input: {\n readonly currentUserId: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<OrganizationReadModelProjection | null> {\n const [state] = await input.tx\n .select({\n cursor: organizationReadModelState.cursor,\n requesterIsOrgAdmin: organizationReadModelRequesters.isOrgAdmin,\n memberGroupId: organizationReadModelState.memberGroupId,\n organizationKeyEpoch: organizationReadModelState.organizationKeyEpoch,\n organizationKeyFingerprint:\n organizationReadModelState.organizationKeyFingerprint,\n organizationMemberCount:\n organizationReadModelState.organizationMemberCount,\n organizationStateHash: organizationReadModelState.organizationStateHash,\n organizationStateVersion:\n organizationReadModelState.organizationStateVersion,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n updatedAt: organizationReadModelState.updatedAt,\n })\n .from(organizationReadModelState)\n .leftJoin(\n organizationReadModelRequesters,\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n organizationReadModelState.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.currentUserId),\n ),\n )\n .where(eq(organizationReadModelState.organizationId, input.organizationId))\n .limit(1);\n if (!state) {\n return null;\n }\n const directoryRows = await loadDirectoryRows(input.tx, input.organizationId);\n const groupRows = await loadGroupRows(input.tx, input.organizationId);\n const grants = await loadOrganizationReadModelGrantsInTransaction(input);\n const membershipEdges = await loadMembershipEdges(\n input.tx,\n input.organizationId,\n );\n const groups = groupRows.map((row) => ({\n groupId: row.groupId,\n organizationId: input.organizationId,\n name: row.name,\n createdAt: row.createdAt,\n isBuiltin: row.isBuiltin,\n currentState: toGroupCurrentState(row),\n }));\n const policyHeads = toProjectionPolicyHeads({\n groups,\n organizationHead: {\n keyEpoch: state.organizationKeyEpoch,\n keyFingerprint: state.organizationKeyFingerprint,\n memberCount: state.organizationMemberCount,\n stateHash: state.organizationStateHash,\n version: state.organizationStateVersion,\n },\n organizationId: input.organizationId,\n });\n\n return {\n cursor: state.cursor,\n directory: {\n organizationId: input.organizationId,\n profileDocumentId: state.profileDocumentId,\n users: directoryRows.map((row) =>\n toDirectoryUser(row, input.currentUserId),\n ),\n },\n grants,\n groups: {\n organizationId: input.organizationId,\n memberGroupId: state.memberGroupId,\n groups,\n },\n membershipEdges,\n organizationId: input.organizationId,\n policyHeads,\n protocolVersion: ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n requester:\n state.requesterIsOrgAdmin === null\n ? null\n : { isOrgAdmin: state.requesterIsOrgAdmin },\n updatedAt: state.updatedAt,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationReadModelProjection.js","sourceRoot":"","sources":["organizationReadModelProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAS5D,OAAO,EACL,0BAA0B,GAE3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,mCAAmC,EACnC,iCAAiC,EACjC,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EAAE,4CAA4C,EAAE,MAAM,yCAAyC,CAAC;AACvG,OA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AAwB;SACxC;QACD,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IAEH,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,SAAS,EAAE;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC/B,eAAe,CAAC,GAAG,EAAE,KAAK,CAAC,aAAa,CAAC,CAC1C;SACF;QACD,MAAM;QACN,MAAM,EAAE;YACN,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,MAAM;SACP;QACD,eAAe;QACf,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW;QACX,eAAe,EAAE,wCAAwC;QACzD,SAAS,EACP,KAAK,CAAC,mBAAmB,KAAK,IAAI;YAChC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,mBAAmB,EAAE;QAC/C,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport type {\n ListOrganizationGroupsResponse,\n OrganizationContainerGrantsResponse,\n OrganizationDirectoryResponse,\n OrganizationDirectoryUserResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationRosterStatus,\n} from \"@tearleads/validators/response\";\nimport {\n isOrganizationLeaveRequest,\n type OrganizationLeaveRequest,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadOrganizationReadModelGrantsInTransaction } from \"./organizationReadModelGrantPersistence\";\nimport {\n ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n OrganizationReadModelIntegrityError,\n} from \"./organizationReadModelProtocol\";\n\nexport type OrganizationDirectoryProjection = Omit<\n OrganizationDirectoryResponse,\n \"currentUser\"\n>;\n\nexport interface OrganizationReadModelProjection {\n readonly cursor: string;\n readonly directory: OrganizationDirectoryProjection;\n readonly grants: OrganizationContainerGrantsResponse;\n readonly groups: Omit<ListOrganizationGroupsResponse, \"groups\"> & {\n groups: Array<\n ListOrganizationGroupsResponse[\"groups\"][number] & { name: string }\n >;\n };\n readonly membershipEdges: OrganizationReadModelMembershipEdge[];\n readonly organizationId: string;\n readonly policyHeads: readonly OrganizationReadModelPolicyHead[];\n readonly protocolVersion: typeof ORGANIZATION_READ_MODEL_PROTOCOL_VERSION;\n readonly requester: OrganizationDirectoryResponse[\"currentUser\"] | null;\n readonly updatedAt: string;\n}\n\nexport interface OrganizationReadModelPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly organizationId: string;\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n readonly stateHash: string;\n readonly version: number;\n}\n\nexport interface OrganizationReadModelMembershipEdge {\n readonly groupId: string;\n readonly userId: string;\n}\n\ninterface SelectedDirectoryUser {\n readonly createdAt: string;\n readonly disabledAt: string | null;\n readonly disabledByUserId: string | null;\n readonly encapsulationKeyFingerprint: string;\n readonly isPersonalOrganizationOwner: boolean;\n readonly joinedAt: string;\n readonly leaveRequest: string | null;\n readonly profileDocumentId: string | null;\n readonly signingKeyFingerprint: string;\n readonly status: string;\n readonly updatedAt: string;\n readonly userId: string;\n}\n\ninterface SelectedGroup {\n readonly createdAt: string;\n readonly groupId: string;\n readonly isBuiltin: boolean;\n readonly keyEpoch: number | null;\n readonly keyFingerprint: string | null;\n readonly memberCount: number | null;\n readonly name: string;\n readonly stateHash: string | null;\n readonly stateVersion: number | null;\n}\n\n/** A stored policy head before validation; `version` is the state version. */\ninterface StoredPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isOrganizationRosterStatus(\n value: string,\n): value is OrganizationRosterStatus {\n return value === \"active\" || value === \"disabled\";\n}\n\nfunction toDirectoryUser(\n row: SelectedDirectoryUser,\n currentUserId: string,\n): OrganizationDirectoryUserResponse {\n if (!isOrganizationRosterStatus(row.status)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization directory status is invalid\",\n );\n }\n\n return {\n userId: row.userId,\n signingKeyFingerprint: row.signingKeyFingerprint,\n encapsulationKeyFingerprint: row.encapsulationKeyFingerprint,\n createdAt: row.createdAt,\n isPersonalOrganizationOwner: row.isPersonalOrganizationOwner,\n isSelf: row.userId === currentUserId,\n status: row.status,\n profileDocumentId: row.profileDocumentId,\n joinedAt: row.joinedAt,\n leaveRequest: readStoredLeaveRequest(row.leaveRequest),\n updatedAt: row.updatedAt,\n disabledAt: row.disabledAt,\n disabledByUserId: row.disabledByUserId,\n };\n}\n\nfunction readStoredLeaveRequest(\n stored: string | null,\n): OrganizationLeaveRequest | null {\n if (stored === null) return null;\n const parsed: unknown = JSON.parse(stored);\n if (!isOrganizationLeaveRequest(parsed)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization leave request is invalid\",\n );\n }\n return parsed;\n}\n\nfunction isValidPolicyHead(head: StoredPolicyHead): boolean {\n return (\n head.stateHash.length > 0 &&\n Number.isInteger(head.version) &&\n head.version > 0 &&\n Number.isSafeInteger(head.keyEpoch) &&\n head.keyEpoch > 0 &&\n head.keyFingerprint.length > 0 &&\n Number.isInteger(head.memberCount) &&\n head.memberCount >= 0\n );\n}\n\n/** A group's state columns are all null (stateless) or one valid head. */\nfunction toGroupCurrentState(\n row: SelectedGroup,\n): OrganizationGroupCurrentStateResponse | null {\n const values = [\n row.stateHash,\n row.stateVersion,\n row.keyEpoch,\n row.keyFingerprint,\n row.memberCount,\n ];\n if (values.every((value) => value === null)) {\n return null;\n }\n const head =\n row.stateHash === null ||\n row.stateVersion === null ||\n row.keyEpoch === null ||\n row.keyFingerprint === null ||\n row.memberCount === null\n ? null\n : {\n stateHash: row.stateHash,\n version: row.stateVersion,\n keyEpoch: row.keyEpoch,\n keyFingerprint: row.keyFingerprint,\n memberCount: row.memberCount,\n };\n if (!head || !isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization group state is invalid\",\n );\n }\n return head;\n}\n\nfunction toOrganizationPolicyHead(\n organizationId: string,\n head: StoredPolicyHead,\n): OrganizationReadModelPolicyHead {\n if (!isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization policy head is invalid\",\n );\n }\n return {\n ...head,\n organizationId,\n principalId: organizationId,\n principalType: \"organization\",\n };\n}\n\n/** The organization head from the state row plus every stateful group head. */\nfunction toProjectionPolicyHeads(input: {\n readonly groups: ReadonlyArray<{\n readonly currentState: OrganizationGroupCurrentStateResponse | null;\n readonly groupId: string;\n }>;\n readonly organizationHead: StoredPolicyHead;\n readonly organizationId: string;\n}): OrganizationReadModelPolicyHead[] {\n const groupHeads = input.groups\n .flatMap((group): OrganizationReadModelPolicyHead[] =>\n group.currentState\n ? [\n {\n ...group.currentState,\n organizationId: input.organizationId,\n principalId: group.groupId,\n principalType: \"group\",\n },\n ]\n : [],\n )\n .sort((left, right) =>\n compareCanonicalStrings(left.principalId, right.principalId),\n );\n // Group heads precede the organization head, ordered by principal ID.\n return [\n ...groupHeads,\n toOrganizationPolicyHead(input.organizationId, input.organizationHead),\n ];\n}\n\nasync function loadDirectoryRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedDirectoryUser[]> {\n return tx\n .select({\n createdAt: organizationReadModelDirectoryUsers.createdAt,\n disabledAt: organizationReadModelDirectoryUsers.disabledAt,\n disabledByUserId: organizationReadModelDirectoryUsers.disabledByUserId,\n encapsulationKeyFingerprint:\n organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,\n joinedAt: organizationReadModelDirectoryUsers.joinedAt,\n leaveRequest: organizationReadModelDirectoryUsers.leaveRequest,\n isPersonalOrganizationOwner:\n organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,\n profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,\n signingKeyFingerprint:\n organizationReadModelDirectoryUsers.signingKeyFingerprint,\n status: organizationReadModelDirectoryUsers.status,\n updatedAt: organizationReadModelDirectoryUsers.updatedAt,\n userId: organizationReadModelDirectoryUsers.userId,\n })\n .from(organizationReadModelDirectoryUsers)\n .where(\n eq(organizationReadModelDirectoryUsers.organizationId, organizationId),\n )\n .orderBy(\n asc(organizationReadModelDirectoryUsers.sortOrder),\n asc(organizationReadModelDirectoryUsers.userId),\n );\n}\n\nasync function loadGroupRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedGroup[]> {\n return tx\n .select({\n createdAt: organizationReadModelGroups.createdAt,\n groupId: organizationReadModelGroups.groupId,\n isBuiltin: organizationReadModelGroups.isBuiltin,\n keyEpoch: organizationReadModelGroups.keyEpoch,\n keyFingerprint: organizationReadModelGroups.keyFingerprint,\n memberCount: organizationReadModelGroups.memberCount,\n name: organizationReadModelGroups.name,\n stateHash: organizationReadModelGroups.stateHash,\n stateVersion: organizationReadModelGroups.stateVersion,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroups.sortOrder),\n asc(organizationReadModelGroups.groupId),\n );\n}\n\nasync function loadMembershipEdges(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<OrganizationReadModelMembershipEdge[]> {\n return tx\n .select({\n groupId: organizationReadModelGroupMembers.groupId,\n userId: organizationReadModelGroupMembers.userId,\n })\n .from(organizationReadModelGroupMembers)\n .where(eq(organizationReadModelGroupMembers.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroupMembers.groupId),\n asc(organizationReadModelGroupMembers.sortOrder),\n asc(organizationReadModelGroupMembers.userId),\n );\n}\n\nexport async function loadOrganizationReadModelProjectionInTransaction(input: {\n readonly currentUserId: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<OrganizationReadModelProjection | null> {\n const [state] = await input.tx\n .select({\n cursor: organizationReadModelState.cursor,\n requesterIsOrgAdmin: organizationReadModelRequesters.isOrgAdmin,\n memberGroupId: organizationReadModelState.memberGroupId,\n organizationKeyEpoch: organizationReadModelState.organizationKeyEpoch,\n organizationKeyFingerprint:\n organizationReadModelState.organizationKeyFingerprint,\n organizationMemberCount:\n organizationReadModelState.organizationMemberCount,\n organizationStateHash: organizationReadModelState.organizationStateHash,\n organizationStateVersion:\n organizationReadModelState.organizationStateVersion,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n updatedAt: organizationReadModelState.updatedAt,\n })\n .from(organizationReadModelState)\n .leftJoin(\n organizationReadModelRequesters,\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n organizationReadModelState.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.currentUserId),\n ),\n )\n .where(eq(organizationReadModelState.organizationId, input.organizationId))\n .limit(1);\n if (!state) {\n return null;\n }\n const directoryRows = await loadDirectoryRows(input.tx, input.organizationId);\n const groupRows = await loadGroupRows(input.tx, input.organizationId);\n const grants = await loadOrganizationReadModelGrantsInTransaction(input);\n const membershipEdges = await loadMembershipEdges(\n input.tx,\n input.organizationId,\n );\n const groups = groupRows.map((row) => ({\n groupId: row.groupId,\n organizationId: input.organizationId,\n name: row.name,\n createdAt: row.createdAt,\n isBuiltin: row.isBuiltin,\n currentState: toGroupCurrentState(row),\n }));\n const policyHeads = toProjectionPolicyHeads({\n groups,\n organizationHead: {\n keyEpoch: state.organizationKeyEpoch,\n keyFingerprint: state.organizationKeyFingerprint,\n memberCount: state.organizationMemberCount,\n stateHash: state.organizationStateHash,\n version: state.organizationStateVersion,\n },\n organizationId: input.organizationId,\n });\n\n return {\n cursor: state.cursor,\n directory: {\n organizationId: input.organizationId,\n profileDocumentId: state.profileDocumentId,\n users: directoryRows.map((row) =>\n toDirectoryUser(row, input.currentUserId),\n ),\n },\n grants,\n groups: {\n organizationId: input.organizationId,\n memberGroupId: state.memberGroupId,\n groups,\n },\n membershipEdges,\n organizationId: input.organizationId,\n policyHeads,\n protocolVersion: ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n requester:\n state.requesterIsOrgAdmin === null\n ? null\n : { isOrgAdmin: state.requesterIsOrgAdmin },\n updatedAt: state.updatedAt,\n };\n}\n"]}
|
|
@@ -8,11 +8,40 @@ export const LOCAL_SCHEMA_BASELINE = {
|
|
|
8
8
|
name: "baseline",
|
|
9
9
|
version: 1,
|
|
10
10
|
};
|
|
11
|
+
const DIRECTORY_USERS_TABLE = "organization_read_model_directory_users";
|
|
11
12
|
/**
|
|
12
13
|
* Ordered and append-only: version 2 first, each one after the last. Never
|
|
13
14
|
* edit or remove a shipped step; a correction is a new step.
|
|
14
15
|
*/
|
|
15
|
-
export const localSchemaMigrations = [
|
|
16
|
+
export const localSchemaMigrations = [
|
|
17
|
+
{
|
|
18
|
+
// Directory rows carry key fingerprints only; public keys come from the
|
|
19
|
+
// trusted identity store. Neither column is indexed or constrained.
|
|
20
|
+
name: "drop_directory_user_public_keys",
|
|
21
|
+
up: async (execSql, context) => {
|
|
22
|
+
if (!(await context.hasTable(DIRECTORY_USERS_TABLE)))
|
|
23
|
+
return;
|
|
24
|
+
for (const column of ["signing_public_key", "encapsulation_public_key"]) {
|
|
25
|
+
await execSql(`ALTER TABLE "${DIRECTORY_USERS_TABLE}" DROP COLUMN "${column}"`);
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
version: 2,
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
// No reader ever used a recorded failure's HTTP status; the message and
|
|
32
|
+
// attempt time explain a blocked document. The column is unindexed. A
|
|
33
|
+
// documents table without it (never created, or not this SDK's table in a
|
|
34
|
+
// restored backup) has nothing to drop.
|
|
35
|
+
name: "drop_document_sync_failure_status",
|
|
36
|
+
up: async (execSql) => {
|
|
37
|
+
const column = await execSql("SELECT name FROM pragma_table_info('documents') WHERE name = 'sync_failure_status'");
|
|
38
|
+
if (column.length === 0)
|
|
39
|
+
return;
|
|
40
|
+
await execSql('ALTER TABLE "documents" DROP COLUMN "sync_failure_status"');
|
|
41
|
+
},
|
|
42
|
+
version: 3,
|
|
43
|
+
},
|
|
44
|
+
];
|
|
16
45
|
const STEP_NAME_PATTERN = /^[a-z0-9_]+$/;
|
|
17
46
|
/** Rejects a registry whose versions are not consecutive from 2. */
|
|
18
47
|
export function assertLocalSchemaMigrations(migrations) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localSchemaMigrations.js","sourceRoot":"","sources":["localSchemaMigrations.ts"],"names":[],"mappings":"AA0BA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAoB;IACpD,IAAI,EAAE,UAAU;IAChB,OAAO,EAAE,CAAC;CACX,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAwC,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"localSchemaMigrations.js","sourceRoot":"","sources":["localSchemaMigrations.ts"],"names":[],"mappings":"AA0BA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAoB;IACpD,IAAI,EAAE,UAAU;IAChB,OAAO,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,qBAAqB,GAAG,yCAAyC,CAAC;AAExE;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAwC;IACxE;QACE,wEAAwE;QACxE,oEAAoE;QACpE,IAAI,EAAE,iCAAiC;QACvC,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE;YAC7B,IAAI,CAAC,CAAC,MAAM,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;gBAAE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CAC9B,UAA+C;IAE/C,OAAO;QACL,qBAAqB;QACrB,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;KAC9D,CAAC;AACJ,CAAC","sourcesContent":["import type { ExecSql } from \"../sqlExec\";\n\nexport interface LocalSchemaMigrationContext {\n /**\n * Whether a table exists. Features create their tables lazily, so a\n * migration must skip a table this database never created: the table's\n * ensure creates it later in the current shape.\n */\n hasTable(name: string): Promise<boolean>;\n}\n\nexport interface LocalSchemaStep {\n readonly version: number;\n readonly name: string;\n}\n\nexport interface LocalSchemaMigration extends LocalSchemaStep {\n /**\n * Upgrades the local database from `version - 1` to `version`. It runs on\n * the locked executor inside the migration savepoint, so it must not BEGIN,\n * COMMIT, or change `PRAGMA foreign_keys`. Write it against the shape at\n * `version - 1`, never by importing current table definitions.\n */\n up(execSql: ExecSql, context: LocalSchemaMigrationContext): Promise<void>;\n}\n\n/**\n * Version 1 is the shape the SDK's table definitions created when local\n * migrations began. It has no steps: a database from before the ledger is\n * recorded at this version, and an older shape still fails its tables'\n * required-column check.\n */\nexport const LOCAL_SCHEMA_BASELINE: LocalSchemaStep = {\n name: \"baseline\",\n version: 1,\n};\n\nconst DIRECTORY_USERS_TABLE = \"organization_read_model_directory_users\";\n\n/**\n * Ordered and append-only: version 2 first, each one after the last. Never\n * edit or remove a shipped step; a correction is a new step.\n */\nexport const localSchemaMigrations: ReadonlyArray<LocalSchemaMigration> = [\n {\n // Directory rows carry key fingerprints only; public keys come from the\n // trusted identity store. Neither column is indexed or constrained.\n name: \"drop_directory_user_public_keys\",\n up: async (execSql, context) => {\n if (!(await context.hasTable(DIRECTORY_USERS_TABLE))) return;\n for (const column of [\"signing_public_key\", \"encapsulation_public_key\"]) {\n await execSql(\n `ALTER TABLE \"${DIRECTORY_USERS_TABLE}\" DROP COLUMN \"${column}\"`,\n );\n }\n },\n version: 2,\n },\n {\n // No reader ever used a recorded failure's HTTP status; the message and\n // attempt time explain a blocked document. The column is unindexed. A\n // documents table without it (never created, or not this SDK's table in a\n // restored backup) has nothing to drop.\n name: \"drop_document_sync_failure_status\",\n up: async (execSql) => {\n const column = await execSql(\n \"SELECT name FROM pragma_table_info('documents') WHERE name = 'sync_failure_status'\",\n );\n if (column.length === 0) return;\n await execSql(\n 'ALTER TABLE \"documents\" DROP COLUMN \"sync_failure_status\"',\n );\n },\n version: 3,\n },\n];\n\nconst STEP_NAME_PATTERN = /^[a-z0-9_]+$/;\n\n/** Rejects a registry whose versions are not consecutive from 2. */\nexport function assertLocalSchemaMigrations(\n migrations: ReadonlyArray<LocalSchemaMigration>,\n): void {\n for (const [index, migration] of migrations.entries()) {\n const expected = LOCAL_SCHEMA_BASELINE.version + index + 1;\n if (migration.version !== expected) {\n throw new Error(\n `Local schema migration ${migration.name} has version ${migration.version}; expected ${expected}`,\n );\n }\n if (!STEP_NAME_PATTERN.test(migration.name)) {\n throw new Error(\n `Local schema migration ${migration.version} needs a snake_case name`,\n );\n }\n }\n}\n\n/** The steps a database at the newest version has recorded, in order. */\nexport function localSchemaSteps(\n migrations: ReadonlyArray<LocalSchemaMigration>,\n): ReadonlyArray<LocalSchemaStep> {\n return [\n LOCAL_SCHEMA_BASELINE,\n ...migrations.map(({ name, version }) => ({ name, version })),\n ];\n}\n"]}
|
|
@@ -39,14 +39,14 @@ const accessLevelColumn = "effective_access_level";
|
|
|
39
39
|
* - `recoveryGeneration`: Atomic raw-history recovery writer fence.
|
|
40
40
|
* - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.
|
|
41
41
|
* - `pullContinuation`: Durable progress for the next bounded remote pull.
|
|
42
|
-
* - `
|
|
43
|
-
*
|
|
42
|
+
* - `syncFailureMessage`, `syncFailureAttemptedAt`: The last terminal sync
|
|
43
|
+
* failure or quarantined incoming update for this scope.
|
|
44
44
|
* The durable write queue (queued rows of `documentHistoryUpdates`) has no
|
|
45
45
|
* status columns, so these let the write-queue view and footer explain why
|
|
46
46
|
* the document is blocked. `syncFailureMessage` is non-null exactly when a
|
|
47
47
|
* failure is recorded; a newer failure replaces the old, and a later fully
|
|
48
|
-
* validated sync pass, a remote reset, or the scope's teardown clears
|
|
49
|
-
*
|
|
48
|
+
* validated sync pass, a remote reset, or the scope's teardown clears
|
|
49
|
+
* both.
|
|
50
50
|
* - `updatedAt`: Local timestamp for the last persisted runtime-state update.
|
|
51
51
|
*
|
|
52
52
|
* Indexes:
|
|
@@ -74,7 +74,6 @@ export const documents = sqliteTable("documents", {
|
|
|
74
74
|
recoveryGeneration: integer("recovery_generation").notNull().default(0),
|
|
75
75
|
recoveryDocumentId: text("recovery_document_id"),
|
|
76
76
|
snapshotEndVersion: text("snapshot_end_version").notNull().default(""),
|
|
77
|
-
syncFailureStatus: integer("sync_failure_status"),
|
|
78
77
|
syncFailureMessage: text("sync_failure_message"),
|
|
79
78
|
syncFailureAttemptedAt: text("sync_failure_attempted_at"),
|
|
80
79
|
updatedAt: text("updated_at").notNull(),
|
|
@@ -174,7 +173,6 @@ export const documentTables = [
|
|
|
174
173
|
"pull_continuation",
|
|
175
174
|
"recovery_generation",
|
|
176
175
|
"recovery_document_id",
|
|
177
|
-
"sync_failure_status",
|
|
178
176
|
"sync_failure_message",
|
|
179
177
|
"sync_failure_attempted_at",
|
|
180
178
|
],
|