@tearleads/client-sdk 0.1.253 → 0.1.255
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/containerContents/documentDiscovery.js +0 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +7 -10
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +5 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +11 -4
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRemovalMetadata.js +47 -0
- package/data/persistence/container-contents/containerRemovalMetadata.js.map +1 -0
- package/data/persistence/container-contents/containerRemovalPlacements.js +22 -0
- package/data/persistence/container-contents/containerRemovalPlacements.js.map +1 -0
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +2 -1
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +10 -2
- package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryCandidate.d.ts +1 -0
- package/data/persistence/documents/documentDiscoveryCandidate.js +3 -1
- package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +16 -4
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/sqlite/migrations/localSchemaMigrations.js +11 -0
- package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
- package/data/sqlite/schema/containerSyncWatermarkSchema.js +6 -3
- package/data/sqlite/schema/containerSyncWatermarkSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +17 -0
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +1 -0
- package/internal/api-client/client/apiClientContext.d.ts +1 -0
- package/internal/api-client/client/containerReads.d.ts +1 -0
- package/internal/api-client/requestInternals.js +14 -6
- package/internal/api-client/requestInternals.js.map +1 -1
- package/internal/validators/containerSystemSlot.d.ts +6 -0
- package/internal/validators/containerSystemSlot.js +14 -6
- package/internal/validators/containerSystemSlot.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +29 -2
- package/internal/validators/operation/containerReads.js +2 -1
- package/internal/validators/operation/containerReads.js.map +1 -1
- package/internal/validators/request/containerDocumentLanes.d.ts +7 -0
- package/internal/validators/request/containerDocumentLanes.js +6 -0
- package/internal/validators/request/containerDocumentLanes.js.map +1 -1
- package/internal/validators/response/container.d.ts +8 -0
- package/internal/validators/response/container.js +1 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerParentLanes.d.ts +2 -0
- package/package.json +1 -1
- package/stores/container-contents/operations/index.js +4 -0
- package/stores/container-contents/operations/index.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.d.ts +30 -0
- package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -0
- package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +1 -1
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.d.ts +141 -0
- package/workflows/container-contents/documentDiscovery/containerDocumentListing.js +52 -4
- package/workflows/container-contents/documentDiscovery/containerDocumentListing.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +4 -2
- package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js +17 -12
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/publicationWatermark.js +15 -0
- package/workflows/container-contents/documentDiscovery/publicationWatermark.js.map +1 -0
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js +16 -0
- package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js.map +1 -0
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +8 -9
- package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +4 -4
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js +25 -0
- package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js.map +1 -0
- package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js +107 -0
- package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js.map +1 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +29 -27
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +17 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/tombstoneApplication.js +67 -24
- package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +3 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.js +3 -3
- package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -1
- package/workflows/container-contents/syncPause/discoveryGuard.js +6 -2
- package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneGate.js +6 -3
- package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -1
- package/workflows/registration/bootstrapRootContainer.d.ts +1 -0
- package/workflows/registration/bootstrapRootContainer.js +9 -0
- package/workflows/registration/bootstrapRootContainer.js.map +1 -1
- package/workflows/registration/index.d.ts +1 -1
- package/workflows/registration/index.js +1 -1
- package/workflows/registration/index.js.map +1 -1
- package/workflows/registration/organizationProvisioning.d.ts +3 -2
- package/workflows/registration/organizationProvisioning.js +1 -2
- package/workflows/registration/organizationProvisioning.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -5
- package/workflows/registration/provisioningBootstrapBuilders.js +11 -5
- package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { isCanonicalSignedAt } from "../../../internal/validators/util/index.js";
|
|
2
2
|
import { removeIndexedContainerChild } from "./lanes/childIndex.js";
|
|
3
|
+
import { pendingFolderRestorations, recordFolderRestoration, } from "./lanes/restorationReceipt.js";
|
|
4
|
+
import { resolveTombstoneCascade } from "./lanes/tombstoneAccess.js";
|
|
3
5
|
import { containerStateMatchesFingerprint } from "./remoteContainers/containerStateFingerprint.js";
|
|
4
|
-
import { collectRemovedContainers } from "./tombstoneReasons.js";
|
|
5
6
|
function latestContainerItemsById(items) {
|
|
6
7
|
const latestItems = new Map();
|
|
7
8
|
for (const item of items) {
|
|
@@ -48,13 +49,15 @@ export function getApplicableRemoteContainerItems(response) {
|
|
|
48
49
|
});
|
|
49
50
|
}
|
|
50
51
|
async function applyContainerTombstoneCascade(input) {
|
|
51
|
-
const { childIdsByParentId, expectedContainerStates,
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
52
|
+
const { childIdsByParentId, expectedContainerStates, state } = input;
|
|
53
|
+
const resolved = await resolveTombstoneCascade(input);
|
|
54
|
+
if (!resolved || input.isCurrent?.() === false)
|
|
55
|
+
return {
|
|
56
|
+
current: input.isCurrent?.() !== false,
|
|
57
|
+
removedCount: 0,
|
|
58
|
+
settled: false,
|
|
59
|
+
};
|
|
60
|
+
const { fenceOnlyContainerIds, absentDeletedContainerIds, removalByContainerId, removedContainerIds, } = resolved.cascade;
|
|
58
61
|
const affectedContainerIds = new Set([
|
|
59
62
|
...removedContainerIds,
|
|
60
63
|
...absentDeletedContainerIds,
|
|
@@ -77,10 +80,21 @@ async function applyContainerTombstoneCascade(input) {
|
|
|
77
80
|
return removal ? [{ containerId, ...removal }] : [];
|
|
78
81
|
}), {
|
|
79
82
|
discoveryOnly: true,
|
|
80
|
-
expectedContainers: Array.from(affectedContainerIds, (containerId) =>
|
|
81
|
-
containerId
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
expectedContainers: Array.from(affectedContainerIds, (containerId) => {
|
|
84
|
+
const metadata = state.containersById.get(containerId)?.record;
|
|
85
|
+
return {
|
|
86
|
+
containerId,
|
|
87
|
+
...(resolved.denied?.has(containerId)
|
|
88
|
+
? {
|
|
89
|
+
confirmedAccessLoss: {
|
|
90
|
+
placementHash: resolved.denied.get(containerId) ?? null,
|
|
91
|
+
expectedMetadata: metadata ? { ...metadata } : null,
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
: {}),
|
|
95
|
+
expectedContainer: expectedContainerStates.get(containerId)?.container ?? null,
|
|
96
|
+
};
|
|
97
|
+
}),
|
|
84
98
|
stillCurrent: input.isCurrent,
|
|
85
99
|
});
|
|
86
100
|
if (deletedContainerIds.length !== affectedContainerIds.size) {
|
|
@@ -101,8 +115,36 @@ async function applyContainerTombstoneCascade(input) {
|
|
|
101
115
|
settled: true,
|
|
102
116
|
};
|
|
103
117
|
}
|
|
118
|
+
function preserveOtherRoots(state, liveContainerIds, tombstoneRootIds, rootId) {
|
|
119
|
+
const preservedContainerIds = new Set([
|
|
120
|
+
...liveContainerIds,
|
|
121
|
+
...tombstoneRootIds,
|
|
122
|
+
...Array.from(state.containersById, ([id, state]) => state.container.metadataDocumentId === null ? id : null).filter((id) => id !== null),
|
|
123
|
+
]);
|
|
124
|
+
if (state.containersById.get(rootId)?.container.metadataDocumentId !== null) {
|
|
125
|
+
preservedContainerIds.delete(rootId);
|
|
126
|
+
}
|
|
127
|
+
return preservedContainerIds;
|
|
128
|
+
}
|
|
104
129
|
export async function applyContainerTombstones(input) {
|
|
105
|
-
|
|
130
|
+
// A folder can regain access after one of its cached children moved away.
|
|
131
|
+
// Its live listing keeps the folder and reconciles the previously held tree.
|
|
132
|
+
const restored = await pendingFolderRestorations({
|
|
133
|
+
...input,
|
|
134
|
+
items: input.remoteContainerItems,
|
|
135
|
+
execSql: input.state.runtime.infra.execSql,
|
|
136
|
+
});
|
|
137
|
+
const restoredById = new Map(restored.map((item) => [item.id, item]));
|
|
138
|
+
const tombstones = [
|
|
139
|
+
...getApplicableContainerTombstones(input.response),
|
|
140
|
+
...restored.map((item) => ({
|
|
141
|
+
containerId: item.id,
|
|
142
|
+
parentId: item.parentId,
|
|
143
|
+
depth: item.depth,
|
|
144
|
+
updatedAt: item.updatedAt,
|
|
145
|
+
reason: "access_revoked",
|
|
146
|
+
})),
|
|
147
|
+
];
|
|
106
148
|
if (tombstones.length === 0 || input.isCurrent?.() === false) {
|
|
107
149
|
return {
|
|
108
150
|
changedCount: 0,
|
|
@@ -121,25 +163,26 @@ export async function applyContainerTombstones(input) {
|
|
|
121
163
|
// Apply each root as its own CAS-protected cascade. Other explicit roots
|
|
122
164
|
// stay out of this cascade so their own reason wins and one stale root
|
|
123
165
|
// cannot block independent tombstones or live items on the page.
|
|
124
|
-
const preservedContainerIds =
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
...Array.from(input.state.containersById, ([id, state]) => state.container.metadataDocumentId === null ? id : null).filter((id) => id !== null),
|
|
128
|
-
]);
|
|
129
|
-
if (input.state.containersById.get(tombstone.containerId)?.container
|
|
130
|
-
.metadataDocumentId !== null) {
|
|
131
|
-
preservedContainerIds.delete(tombstone.containerId);
|
|
132
|
-
}
|
|
166
|
+
const preservedContainerIds = preserveOtherRoots(input.state, liveContainerIds, tombstoneRootIds, tombstone.containerId);
|
|
167
|
+
const live = restoredById.get(tombstone.containerId);
|
|
168
|
+
const stillCurrent = () => input.isCurrent?.() !== false && !(live && input.isPaused?.(live));
|
|
133
169
|
const result = await applyContainerTombstoneCascade({
|
|
170
|
+
reconcileDescendants: live !== undefined,
|
|
171
|
+
afterParentPage: input.response.nextWatermark
|
|
172
|
+
? { parentId: input.parentId, watermark: input.response.nextWatermark }
|
|
173
|
+
: undefined,
|
|
134
174
|
childIdsByParentId: input.childIdsByParentId,
|
|
135
175
|
expectedContainerStates: input.expectedContainerStates,
|
|
136
|
-
isCurrent:
|
|
176
|
+
isCurrent: stillCurrent,
|
|
137
177
|
preservedContainerIds,
|
|
138
178
|
state: input.state,
|
|
139
179
|
tombstone,
|
|
140
180
|
});
|
|
141
181
|
changedCount += result.removedCount;
|
|
142
|
-
|
|
182
|
+
if (live && input.isPaused?.(live) && input.isCurrent?.() !== false)
|
|
183
|
+
continue;
|
|
184
|
+
const recorded = await recordFolderRestoration(input.state.runtime.infra.execSql, live, result.settled, stillCurrent);
|
|
185
|
+
completed = completed && recorded;
|
|
143
186
|
if (!result.current) {
|
|
144
187
|
return { changedCount, completed: false, current: false };
|
|
145
188
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tombstoneApplication.js","sourceRoot":"","sources":["tombstoneApplication.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,gCAAgC,EAAE,MAAM,8CAA8C,CAAC;AAChG,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAQ9D,SAAS,wBAAwB,CAC/B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AAE,KAAK,CAAC,uBAAuB;YACtD,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,qBAAqB;YACrB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,SAAS;SACV,CAAC,CAAC;QACH,YAAY,IAAI,MAAM,CAAC,YAAY,CAAC;QACpC,SAAS,GAAG,SAAS,IAAI,MAAM,CAAC,OAAO,CAAC;QACxC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type {\n ContainerSyncTombstone,\n ListContainersResponse,\n} from \"@tearleads/validators/response\";\nimport { isCanonicalSignedAt } from \"@tearleads/validators/util\";\nimport { removeIndexedContainerChild } from \"./lanes/childIndex\";\nimport { containerStateMatchesFingerprint } from \"./remoteContainers/containerStateFingerprint\";\nimport { collectRemovedContainers } from \"./tombstoneReasons\";\nimport type {\n ContainerChildIndex,\n ExpectedContainerState,\n ListedRemoteContainerPageItem,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nfunction latestContainerItemsById(\n items: ReadonlyArray<ListedRemoteContainerPageItem>,\n): Map<string, ListedRemoteContainerPageItem> {\n const latestItems = new Map<string, ListedRemoteContainerPageItem>();\n for (const item of items) {\n const current = latestItems.get(item.id);\n if (!current || current.updatedAt < item.updatedAt) {\n latestItems.set(item.id, item);\n }\n }\n\n return latestItems;\n}\n\nfunction latestContainerTombstonesById(\n tombstones: ReadonlyArray<ContainerSyncTombstone>,\n): Map<string, ContainerSyncTombstone> {\n const latestTombstones = new Map<string, ContainerSyncTombstone>();\n for (const tombstone of tombstones) {\n if (!isCanonicalSignedAt(tombstone.updatedAt))\n throw new Error(\"Container tombstone timestamp is not canonical\");\n const current = latestTombstones.get(tombstone.containerId);\n if (\n !current ||\n current.updatedAt < tombstone.updatedAt ||\n (current.updatedAt === tombstone.updatedAt &&\n current.reason === \"access_revoked\" &&\n tombstone.reason === \"deleted\")\n ) {\n latestTombstones.set(tombstone.containerId, tombstone);\n }\n }\n\n return latestTombstones;\n}\n\nfunction getApplicableContainerTombstones(\n response: ListContainersResponse,\n): ContainerSyncTombstone[] {\n const latestItems = latestContainerItemsById(response.items);\n return Array.from(\n latestContainerTombstonesById(response.tombstones).values(),\n ).filter((tombstone) => {\n const item = latestItems.get(tombstone.containerId);\n return (\n !item ||\n item.updatedAt < tombstone.updatedAt ||\n (item.updatedAt === tombstone.updatedAt && tombstone.reason === \"deleted\")\n );\n });\n}\n\nexport function getApplicableRemoteContainerItems(\n response: ListContainersResponse,\n): ListedRemoteContainerPageItem[] {\n const latestTombstones = latestContainerTombstonesById(response.tombstones);\n return response.items.filter((item) => {\n const tombstone = latestTombstones.get(item.id);\n return (\n !tombstone ||\n tombstone.updatedAt < item.updatedAt ||\n (tombstone.updatedAt === item.updatedAt &&\n tombstone.reason === \"access_revoked\")\n );\n });\n}\n\nasync function applyContainerTombstoneCascade(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n preservedContainerIds: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n tombstone: ContainerSyncTombstone;\n}): Promise<{ current: boolean; removedCount: number; settled: boolean }> {\n const {\n childIdsByParentId,\n expectedContainerStates,\n preservedContainerIds,\n state,\n tombstone,\n } = input;\n const {\n fenceOnlyContainerIds,\n absentDeletedContainerIds,\n removalByContainerId,\n removedContainerIds,\n } = collectRemovedContainers({\n childIdsByParentId,\n containersById: state.containersById,\n preservedContainerIds,\n tombstones: [tombstone],\n });\n const affectedContainerIds = new Set([\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ]);\n for (const containerId of affectedContainerIds) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(containerId),\n expectedFingerprint:\n expectedContainerStates.get(containerId)?.fingerprint,\n })\n ) {\n return { current: true, removedCount: 0, settled: false };\n }\n }\n\n const deletedContainerIds = await state.persistence.deleteContainers(\n state.runtime.infra.execSql,\n [\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ].flatMap((containerId) => {\n const removal = removalByContainerId.get(containerId);\n return removal ? [{ containerId, ...removal }] : [];\n }),\n {\n discoveryOnly: true,\n expectedContainers: Array.from(affectedContainerIds, (containerId) => ({\n containerId,\n expectedContainer:\n expectedContainerStates.get(containerId)?.container ?? null,\n })),\n stillCurrent: input.isCurrent,\n },\n );\n if (deletedContainerIds.length !== affectedContainerIds.size) {\n return { current: true, removedCount: 0, settled: false };\n }\n if (input.isCurrent?.() === false) {\n return { current: false, removedCount: 0, settled: false };\n }\n for (const containerId of removedContainerIds) {\n const parentId =\n state.containersById.get(containerId)?.container.parentId ?? null;\n removeIndexedContainerChild(childIdsByParentId, containerId, parentId);\n childIdsByParentId.delete(containerId);\n state.containersById.delete(containerId);\n }\n\n return {\n current: true,\n removedCount: removedContainerIds.length,\n settled: true,\n };\n}\n\nexport async function applyContainerTombstones(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n remoteContainerItems: ReadonlyArray<ListedRemoteContainerPageItem>;\n response: ListContainersResponse;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean; current: boolean }> {\n const tombstones = getApplicableContainerTombstones(input.response);\n if (tombstones.length === 0 || input.isCurrent?.() === false) {\n return {\n changedCount: 0,\n completed: true,\n current: input.isCurrent?.() !== false,\n };\n }\n\n const tombstoneRootIds = new Set(\n tombstones.map((tombstone) => tombstone.containerId),\n );\n const liveContainerIds = input.remoteContainerItems.map((item) => item.id);\n let changedCount = 0;\n let completed = true;\n for (const tombstone of tombstones) {\n if (input.isCurrent?.() === false) {\n return { changedCount, completed: false, current: false };\n }\n // Apply each root as its own CAS-protected cascade. Other explicit roots\n // stay out of this cascade so their own reason wins and one stale root\n // cannot block independent tombstones or live items on the page.\n const preservedContainerIds = new Set([\n ...liveContainerIds,\n ...tombstoneRootIds,\n ...Array.from(input.state.containersById, ([id, state]) =>\n state.container.metadataDocumentId === null ? id : null,\n ).filter((id): id is string => id !== null),\n ]);\n if (\n input.state.containersById.get(tombstone.containerId)?.container\n .metadataDocumentId !== null\n ) {\n preservedContainerIds.delete(tombstone.containerId);\n }\n const result = await applyContainerTombstoneCascade({\n childIdsByParentId: input.childIdsByParentId,\n expectedContainerStates: input.expectedContainerStates,\n isCurrent: input.isCurrent,\n preservedContainerIds,\n state: input.state,\n tombstone,\n });\n changedCount += result.removedCount;\n completed = completed && result.settled;\n if (!result.current) {\n return { changedCount, completed: false, current: false };\n }\n }\n\n return { changedCount, completed, current: true };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tombstoneApplication.js","sourceRoot":"","sources":["tombstoneApplication.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EACL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,gCAAgC,EAAE,MAAM,8CAA8C,CAAC;AAQhG,SAAS,wBAAwB,CAC/B,KAAmD;IAEnD,MAAM,WAAW,GAAG,IAAI,GAAG,EAAyC,CAAC;IACrE,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACzC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,SAAS,GAAG,IAAI,CAA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IAAI,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,MAAM,8BAA8B,CAAC;YAClD,oBAAoB,EAAE,IAAI,KAAK,SAAS;YACxC,eAAe,EAAE,KAAK,CAAC,QAAQ,CAAC,aAAa;gBAC3C,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,aAAa,EAAE;gBACvE,CAAC,CAAC,SAAS;YACb,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;YACtD,SAAS,EAAE,YAAY;YACvB,qBAAqB;YACrB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,SAAS;SACV,CAAC,CAAC;QACH,YAAY,IAAI,MAAM,CAAC,YAAY,CAAC;QACpC,IAAI,IAAI,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YACjE,SAAS;QACX,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,IAAI,EACJ,MAAM,CAAC,OAAO,EACd,YAAY,CACb,CAAC;QACF,SAAS,GAAG,SAAS,IAAI,QAAQ,CAAC;QAClC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { ListContainerDocumentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSyncTombstone,\n ListContainersResponse,\n} from \"@tearleads/validators/response\";\nimport { isCanonicalSignedAt } from \"@tearleads/validators/util\";\nimport { removeIndexedContainerChild } from \"./lanes/childIndex\";\nimport {\n pendingFolderRestorations,\n recordFolderRestoration,\n} from \"./lanes/restorationReceipt\";\nimport { resolveTombstoneCascade } from \"./lanes/tombstoneAccess\";\nimport { containerStateMatchesFingerprint } from \"./remoteContainers/containerStateFingerprint\";\nimport type {\n ContainerChildIndex,\n ExpectedContainerState,\n ListedRemoteContainerPageItem,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nfunction latestContainerItemsById(\n items: ReadonlyArray<ListedRemoteContainerPageItem>,\n): Map<string, ListedRemoteContainerPageItem> {\n const latestItems = new Map<string, ListedRemoteContainerPageItem>();\n for (const item of items) {\n const current = latestItems.get(item.id);\n if (!current || current.updatedAt < item.updatedAt) {\n latestItems.set(item.id, item);\n }\n }\n\n return latestItems;\n}\n\nfunction latestContainerTombstonesById(\n tombstones: ReadonlyArray<ContainerSyncTombstone>,\n): Map<string, ContainerSyncTombstone> {\n const latestTombstones = new Map<string, ContainerSyncTombstone>();\n for (const tombstone of tombstones) {\n if (!isCanonicalSignedAt(tombstone.updatedAt))\n throw new Error(\"Container tombstone timestamp is not canonical\");\n const current = latestTombstones.get(tombstone.containerId);\n if (\n !current ||\n current.updatedAt < tombstone.updatedAt ||\n (current.updatedAt === tombstone.updatedAt &&\n current.reason === \"access_revoked\" &&\n tombstone.reason === \"deleted\")\n ) {\n latestTombstones.set(tombstone.containerId, tombstone);\n }\n }\n\n return latestTombstones;\n}\n\nfunction getApplicableContainerTombstones(\n response: ListContainersResponse,\n): ContainerSyncTombstone[] {\n const latestItems = latestContainerItemsById(response.items);\n return Array.from(\n latestContainerTombstonesById(response.tombstones).values(),\n ).filter((tombstone) => {\n const item = latestItems.get(tombstone.containerId);\n return (\n !item ||\n item.updatedAt < tombstone.updatedAt ||\n (item.updatedAt === tombstone.updatedAt && tombstone.reason === \"deleted\")\n );\n });\n}\n\nexport function getApplicableRemoteContainerItems(\n response: ListContainersResponse,\n): ListedRemoteContainerPageItem[] {\n const latestTombstones = latestContainerTombstonesById(response.tombstones);\n return response.items.filter((item) => {\n const tombstone = latestTombstones.get(item.id);\n return (\n !tombstone ||\n tombstone.updatedAt < item.updatedAt ||\n (tombstone.updatedAt === item.updatedAt &&\n tombstone.reason === \"access_revoked\")\n );\n });\n}\n\nasync function applyContainerTombstoneCascade(input: {\n reconcileDescendants: boolean;\n afterParentPage: ListContainerDocumentLanesRequest[\"afterParentPage\"];\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n preservedContainerIds: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n tombstone: ContainerSyncTombstone;\n}): Promise<{ current: boolean; removedCount: number; settled: boolean }> {\n const { childIdsByParentId, expectedContainerStates, state } = input;\n const resolved = await resolveTombstoneCascade(input);\n if (!resolved || input.isCurrent?.() === false)\n return {\n current: input.isCurrent?.() !== false,\n removedCount: 0,\n settled: false,\n };\n const {\n fenceOnlyContainerIds,\n absentDeletedContainerIds,\n removalByContainerId,\n removedContainerIds,\n } = resolved.cascade;\n const affectedContainerIds = new Set([\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ]);\n for (const containerId of affectedContainerIds) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(containerId),\n expectedFingerprint:\n expectedContainerStates.get(containerId)?.fingerprint,\n })\n ) {\n return { current: true, removedCount: 0, settled: false };\n }\n }\n\n const deletedContainerIds = await state.persistence.deleteContainers(\n state.runtime.infra.execSql,\n [\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ].flatMap((containerId) => {\n const removal = removalByContainerId.get(containerId);\n return removal ? [{ containerId, ...removal }] : [];\n }),\n {\n discoveryOnly: true,\n expectedContainers: Array.from(affectedContainerIds, (containerId) => {\n const metadata = state.containersById.get(containerId)?.record;\n return {\n containerId,\n ...(resolved.denied?.has(containerId)\n ? {\n confirmedAccessLoss: {\n placementHash: resolved.denied.get(containerId) ?? null,\n expectedMetadata: metadata ? { ...metadata } : null,\n },\n }\n : {}),\n expectedContainer:\n expectedContainerStates.get(containerId)?.container ?? null,\n };\n }),\n stillCurrent: input.isCurrent,\n },\n );\n if (deletedContainerIds.length !== affectedContainerIds.size) {\n return { current: true, removedCount: 0, settled: false };\n }\n if (input.isCurrent?.() === false) {\n return { current: false, removedCount: 0, settled: false };\n }\n for (const containerId of removedContainerIds) {\n const parentId =\n state.containersById.get(containerId)?.container.parentId ?? null;\n removeIndexedContainerChild(childIdsByParentId, containerId, parentId);\n childIdsByParentId.delete(containerId);\n state.containersById.delete(containerId);\n }\n\n return {\n current: true,\n removedCount: removedContainerIds.length,\n settled: true,\n };\n}\n\nfunction preserveOtherRoots(\n state: RemoteContainerHydrationState,\n liveContainerIds: ReadonlyArray<string>,\n tombstoneRootIds: ReadonlySet<string>,\n rootId: string,\n) {\n const preservedContainerIds = new Set([\n ...liveContainerIds,\n ...tombstoneRootIds,\n ...Array.from(state.containersById, ([id, state]) =>\n state.container.metadataDocumentId === null ? id : null,\n ).filter((id): id is string => id !== null),\n ]);\n if (state.containersById.get(rootId)?.container.metadataDocumentId !== null) {\n preservedContainerIds.delete(rootId);\n }\n return preservedContainerIds;\n}\n\nexport async function applyContainerTombstones(input: {\n parentId: string | null;\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n isPaused?: (item: ListedRemoteContainerPageItem) => boolean;\n remoteContainerItems: ReadonlyArray<ListedRemoteContainerPageItem>;\n response: ListContainersResponse;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean; current: boolean }> {\n // A folder can regain access after one of its cached children moved away.\n // Its live listing keeps the folder and reconciles the previously held tree.\n const restored = await pendingFolderRestorations({\n ...input,\n items: input.remoteContainerItems,\n execSql: input.state.runtime.infra.execSql,\n });\n const restoredById = new Map(restored.map((item) => [item.id, item]));\n const tombstones = [\n ...getApplicableContainerTombstones(input.response),\n ...restored.map((item) => ({\n containerId: item.id,\n parentId: item.parentId,\n depth: item.depth,\n updatedAt: item.updatedAt,\n reason: \"access_revoked\" as const,\n })),\n ];\n if (tombstones.length === 0 || input.isCurrent?.() === false) {\n return {\n changedCount: 0,\n completed: true,\n current: input.isCurrent?.() !== false,\n };\n }\n\n const tombstoneRootIds = new Set(\n tombstones.map((tombstone) => tombstone.containerId),\n );\n const liveContainerIds = input.remoteContainerItems.map((item) => item.id);\n let changedCount = 0;\n let completed = true;\n for (const tombstone of tombstones) {\n if (input.isCurrent?.() === false) {\n return { changedCount, completed: false, current: false };\n }\n // Apply each root as its own CAS-protected cascade. Other explicit roots\n // stay out of this cascade so their own reason wins and one stale root\n // cannot block independent tombstones or live items on the page.\n const preservedContainerIds = preserveOtherRoots(\n input.state,\n liveContainerIds,\n tombstoneRootIds,\n tombstone.containerId,\n );\n const live = restoredById.get(tombstone.containerId);\n const stillCurrent = () =>\n input.isCurrent?.() !== false && !(live && input.isPaused?.(live));\n const result = await applyContainerTombstoneCascade({\n reconcileDescendants: live !== undefined,\n afterParentPage: input.response.nextWatermark\n ? { parentId: input.parentId, watermark: input.response.nextWatermark }\n : undefined,\n childIdsByParentId: input.childIdsByParentId,\n expectedContainerStates: input.expectedContainerStates,\n isCurrent: stillCurrent,\n preservedContainerIds,\n state: input.state,\n tombstone,\n });\n changedCount += result.removedCount;\n if (live && input.isPaused?.(live) && input.isCurrent?.() !== false)\n continue;\n const recorded = await recordFolderRestoration(\n input.state.runtime.infra.execSql,\n live,\n result.settled,\n stillCurrent,\n );\n completed = completed && recorded;\n if (!result.current) {\n return { changedCount, completed: false, current: false };\n }\n }\n\n return { changedCount, completed, current: true };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RequestResult, WriterProjectionListing } from "../../../internal/api-client/index.js";
|
|
1
|
+
import type { ApiClient, RequestResult, WriterProjectionListing } from "../../../internal/api-client/index.js";
|
|
2
2
|
import type { ContainerReplacementAuthorizationsResponse } from "../../../internal/validators/operation/index.js";
|
|
3
3
|
import type { ListContainerParentLanesRequest } from "../../../internal/validators/request/index.js";
|
|
4
4
|
import type { ContainerSummary, ContainerWriterProjectionResponse, DocumentWriterProjectionResponse, ListContainerParentLanesResponse, ListContainersResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
|
|
@@ -34,6 +34,7 @@ export interface ContainerState {
|
|
|
34
34
|
}
|
|
35
35
|
interface RemoteContainerHydrationApi extends Partial<PrincipalPolicyHistoryReader>, CurrentPrincipalPolicyReader {
|
|
36
36
|
getContainerReplacementAuthorizationsResult(containerId: string, replacesOrganizationId: string): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;
|
|
37
|
+
listContainerDocumentLanes: ApiClient["listContainerDocumentLanes"];
|
|
37
38
|
evictContainerWriterProjection(containerId: string): void;
|
|
38
39
|
evictWriterProjectionsCiting(containerIds: readonly string[]): void;
|
|
39
40
|
getContainerWriterProjection(containerId: string, listing?: WriterProjectionListing): Promise<ContainerWriterProjectionResponse | null>;
|
|
@@ -59,6 +60,7 @@ export interface RemoteContainerHydrationState {
|
|
|
59
60
|
* fell short while it ran.
|
|
60
61
|
*/
|
|
61
62
|
containerListingFailures?: number | undefined;
|
|
63
|
+
containerParentIdsNeedingHydration?: Set<string | null>;
|
|
62
64
|
containersById: Map<string, ContainerState>;
|
|
63
65
|
lifecycleGeneration?: number | undefined;
|
|
64
66
|
persistence: ContainerContentsPersistence;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"metadataVersionVector\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport type HydrationOutcome = \"complete\" | \"refused\" | \"retry\";\nexport interface ReconnectPages {\n laneIdPrefix: string;\n recordManualError(error: Error): void;\n}\n\nexport interface ReconnectCrawl {\n isCurrent(): boolean;\n record(outcome: HydrationOutcome, manualRejection?: Error): void;\n}\n\nexport interface RemoteContainerHydrationState {\n readonly parentLaneRequestPrefix?: string;\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n /**\n * Owe a metadata document one remote read, durably, before hydration\n * advances the timestamps and lane watermark that revealed it.\n */\n requestMetadataRevalidation?:\n | ((request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n }) => Promise<void>)\n | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n /** An earlier page is incomplete. Continue discovery without persisting a cursor past it. */\n skipWatermarkWrite?: boolean;\n continuationCursors?: Set<string>;\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"metadataVersionVector\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n listContainerDocumentLanes: ApiClient[\"listContainerDocumentLanes\"];\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport type HydrationOutcome = \"complete\" | \"refused\" | \"retry\";\nexport interface ReconnectPages {\n laneIdPrefix: string;\n recordManualError(error: Error): void;\n}\n\nexport interface ReconnectCrawl {\n isCurrent(): boolean;\n record(outcome: HydrationOutcome, manualRejection?: Error): void;\n}\n\nexport interface RemoteContainerHydrationState {\n readonly parentLaneRequestPrefix?: string;\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containerParentIdsNeedingHydration?: Set<string | null>;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n /**\n * Owe a metadata document one remote read, durably, before hydration\n * advances the timestamps and lane watermark that revealed it.\n */\n requestMetadataRevalidation?:\n | ((request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n }) => Promise<void>)\n | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n /** An earlier page is incomplete. Continue discovery without persisting a cursor past it. */\n skipWatermarkWrite?: boolean;\n continuationCursors?: Set<string>;\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { and, eq, inArray, or } from "drizzle-orm";
|
|
2
2
|
import { containerSyncWatermarks } from "../../../data/sqlite/schema/containerSyncWatermarkSchema.js";
|
|
3
3
|
import { remoteResetBatches } from "../../../data/sqlite/sqliteBindBudget.js";
|
|
4
|
-
const
|
|
4
|
+
const CONTAINER_ID_LANES = ["container_documents", "container_restoration"];
|
|
5
5
|
const CONTAINER_PARENT_LANE = "container_parent";
|
|
6
6
|
// The API root feed lists every accessible organization. Its one cursor must
|
|
7
7
|
// reset on any organization's purge; child feeds use globally unique IDs.
|
|
8
8
|
const ROOT_LANE_ID = "root";
|
|
9
9
|
const PARENT_LANE_PREFIX = "parent:";
|
|
10
10
|
export function isRemoteResetSyncCursor(input) {
|
|
11
|
-
if (input.row.laneKind
|
|
11
|
+
if (CONTAINER_ID_LANES.includes(input.row.laneKind)) {
|
|
12
12
|
return input.containerIds.has(input.row.laneId);
|
|
13
13
|
}
|
|
14
14
|
if (input.row.laneKind !== CONTAINER_PARENT_LANE)
|
|
@@ -29,7 +29,7 @@ export async function clearRemoteResetSyncCursors(input) {
|
|
|
29
29
|
const parentLaneIds = containerBatch.map((containerId) => `${PARENT_LANE_PREFIX}${containerId}`);
|
|
30
30
|
await input.tx
|
|
31
31
|
.delete(table)
|
|
32
|
-
.where(or(and(eq(table.laneKind, CONTAINER_PARENT_LANE), inArray(table.laneId, parentLaneIds)), and(
|
|
32
|
+
.where(or(and(eq(table.laneKind, CONTAINER_PARENT_LANE), inArray(table.laneId, parentLaneIds)), and(inArray(table.laneKind, CONTAINER_ID_LANES), inArray(table.laneId, containerBatch))))
|
|
33
33
|
.run();
|
|
34
34
|
}
|
|
35
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remoteResetCursorScope.js","sourceRoot":"","sources":["remoteResetCursorScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAG3E,MAAM,
|
|
1
|
+
{"version":3,"file":"remoteResetCursorScope.js","sourceRoot":"","sources":["remoteResetCursorScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAG3E,MAAM,kBAAkB,GAAG,CAAC,qBAAqB,EAAE,uBAAuB,CAAC,CAAC;AAC5E,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,6EAA6E;AAC7E,0EAA0E;AAC1E,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAOrC,MAAM,UAAU,uBAAuB,CAAC,KAGvC;IACC,IAAI,kBAAkB,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACpD,OAAO,KAAK,CAAC,YAAY,CAAC,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C,QAAQ,EAAE,kBAAkB,CAAC,EAC3C,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,cAAc,CAAC,CACtC,CACF,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { containerSyncWatermarks } from \"../../../data/sqlite/schema/containerSyncWatermarkSchema\";\nimport { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\n\nconst CONTAINER_ID_LANES = [\"container_documents\", \"container_restoration\"];\nconst CONTAINER_PARENT_LANE = \"container_parent\";\n// The API root feed lists every accessible organization. Its one cursor must\n// reset on any organization's purge; child feeds use globally unique IDs.\nconst ROOT_LANE_ID = \"root\";\nconst PARENT_LANE_PREFIX = \"parent:\";\n\ninterface SyncCursorRow {\n readonly laneId: string;\n readonly laneKind: string;\n}\n\nexport function isRemoteResetSyncCursor(input: {\n containerIds: ReadonlySet<string>;\n row: SyncCursorRow;\n}): boolean {\n if (CONTAINER_ID_LANES.includes(input.row.laneKind)) {\n return input.containerIds.has(input.row.laneId);\n }\n if (input.row.laneKind !== CONTAINER_PARENT_LANE) return false;\n if (input.row.laneId === ROOT_LANE_ID) return true;\n return (\n input.row.laneId.startsWith(PARENT_LANE_PREFIX) &&\n input.containerIds.has(input.row.laneId.slice(PARENT_LANE_PREFIX.length))\n );\n}\n\nexport async function clearRemoteResetSyncCursors(input: {\n containerIds: readonly string[];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // One row per lane holds both the cursor and its freshness marker.\n const table = containerSyncWatermarks;\n await input.tx\n .delete(table)\n .where(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n eq(table.laneId, ROOT_LANE_ID),\n ),\n )\n .run();\n for (const containerBatch of remoteResetBatches(input.containerIds)) {\n const parentLaneIds = containerBatch.map(\n (containerId) => `${PARENT_LANE_PREFIX}${containerId}`,\n );\n await input.tx\n .delete(table)\n .where(\n or(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n inArray(table.laneId, parentLaneIds),\n ),\n and(\n inArray(table.laneKind, CONTAINER_ID_LANES),\n inArray(table.laneId, containerBatch),\n ),\n ),\n )\n .run();\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ContainerSyncWatermarkRepository, containerContentsSyncLane, } from "../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
|
|
2
|
-
import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
3
|
-
import {
|
|
2
|
+
import { DocumentContainerProjectionRepository, deleteContainerDocumentTombstonePlacementRows, } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
|
|
3
|
+
import { ContainerDocumentTombstoneHoldRepository } from "../../../data/persistence/documents/containerDocumentTombstoneHoldRepository.js";
|
|
4
|
+
import { applyContainerDocumentTombstones, upsertDiscoveredDocuments, } from "../../../data/persistence/documents/documentsPersistence.js";
|
|
4
5
|
import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
|
|
5
6
|
/**
|
|
6
7
|
* Binds a discovery lane's writes to its generation and its organization
|
|
@@ -16,6 +17,9 @@ export function guardDocumentDiscoveryWrites(input) {
|
|
|
16
17
|
? skipped
|
|
17
18
|
: write(lockedExecSql));
|
|
18
19
|
return {
|
|
20
|
+
applyContainerDocumentTombstones: (rows, stillCurrent) => whileCurrent([], (locked) => applyContainerDocumentTombstones(locked, rows, deleteContainerDocumentTombstonePlacementRows), stillCurrent),
|
|
21
|
+
holdContainerDocumentTombstones: (rows, stillCurrent) => whileCurrent(undefined, (locked) => new ContainerDocumentTombstoneHoldRepository(locked).holdContainerDocumentTombstones(rows), stillCurrent),
|
|
22
|
+
refuteContainerDocumentTombstoneHolds: (rows, stillCurrent) => whileCurrent(undefined, (locked) => new ContainerDocumentTombstoneHoldRepository(locked).refuteContainerDocumentTombstoneHolds(rows), stillCurrent),
|
|
19
23
|
replaceDocumentLinksBatch: (inputs, stillCurrent) => whileCurrent(undefined, (lockedExecSql) => new DocumentContainerProjectionRepository(lockedExecSql).replaceDocumentLinksBatch(inputs), stillCurrent),
|
|
20
24
|
saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) => whileCurrent(undefined, async (lockedExecSql) => {
|
|
21
25
|
await new ContainerSyncWatermarkRepository(lockedExecSql).saveWatermark(containerContentsSyncLane(containerId), watermark);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discoveryGuard.js","sourceRoot":"","sources":["discoveryGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,
|
|
1
|
+
{"version":3,"file":"discoveryGuard.js","sourceRoot":"","sources":["discoveryGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EACL,qCAAqC,EACrC,6CAA6C,GAC9C,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,wCAAwC,EAAE,MAAM,8EAA8E,CAAC;AACxI,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAexE;;;;;;;;GAQG;AACH,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,MAAM,YAAY,GAAG,CACnB,OAAU,EACV,KAA6C,EAC7C,YAAoC,EACxB,EAAE,CACd,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC9D,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,MAAM,YAAY,EAAE,CAAC;QACzC,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CACzB,CAA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AAyB,CAAC,GAAG,IAAI;YACrC,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAAC,CAAC;YACpE,OAAO;gBACL,GAAG,YAAY;gBACf,SAAS,EAAE,KAAK,IAAI,EAAE,CACpB,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,YAAY,CAAC,SAAS,EAAE,CAAC;aACxD,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport {\n DocumentContainerProjectionRepository,\n deleteContainerDocumentTombstonePlacementRows,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport {\n applyContainerDocumentTombstones,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DiscoverContainerDocumentsOptions } from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype PauseGuardedDiscovery = Pick<\n DiscoverContainerDocumentsOptions,\n | \"applyContainerDocumentTombstones\"\n | \"holdContainerDocumentTombstones\"\n | \"refuteContainerDocumentTombstoneHolds\"\n | \"replaceDocumentLinksBatch\"\n | \"saveContainerDocumentWatermark\"\n | \"upsertDiscoveredDocuments\"\n | \"verifyDiscoveredDocuments\"\n>;\n\n/**\n * Binds a discovery lane's writes to its generation and its organization\n * staying unpaused. Access changes and pauses invalidate in-flight listings,\n * so the apply stops at its next check, and each write already started\n * rechecks under the SQLite mutation lock. A listing that verified before\n * its organization paused therefore saves no watermark: a watermark saved\n * past documents it did not apply would let the listing after a resume skip\n * them.\n */\nexport function guardDocumentDiscoveryWrites(input: {\n readonly execSql: ExecSql;\n readonly isPaused: () => boolean;\n readonly verifyDiscoveredDocuments: DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"];\n}): PauseGuardedDiscovery {\n const whileCurrent = <T>(\n skipped: T,\n write: (lockedExecSql: ExecSql) => Promise<T>,\n stillCurrent: () => Promise<boolean>,\n ): Promise<T> =>\n runSerializedSqlMutation(input.execSql, async (lockedExecSql) =>\n input.isPaused() || !(await stillCurrent())\n ? skipped\n : write(lockedExecSql),\n );\n return {\n applyContainerDocumentTombstones: (rows, stillCurrent) =>\n whileCurrent(\n [],\n (locked) =>\n applyContainerDocumentTombstones(\n locked,\n rows,\n deleteContainerDocumentTombstonePlacementRows,\n ),\n stillCurrent,\n ),\n holdContainerDocumentTombstones: (rows, stillCurrent) =>\n whileCurrent(\n undefined,\n (locked) =>\n new ContainerDocumentTombstoneHoldRepository(\n locked,\n ).holdContainerDocumentTombstones(rows),\n stillCurrent,\n ),\n refuteContainerDocumentTombstoneHolds: (rows, stillCurrent) =>\n whileCurrent(\n undefined,\n (locked) =>\n new ContainerDocumentTombstoneHoldRepository(\n locked,\n ).refuteContainerDocumentTombstoneHolds(rows),\n stillCurrent,\n ),\n replaceDocumentLinksBatch: (inputs, stillCurrent) =>\n whileCurrent(\n undefined,\n (lockedExecSql) =>\n new DocumentContainerProjectionRepository(\n lockedExecSql,\n ).replaceDocumentLinksBatch(inputs),\n stillCurrent,\n ),\n saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) =>\n whileCurrent(\n undefined,\n async (lockedExecSql) => {\n await new ContainerSyncWatermarkRepository(\n lockedExecSql,\n ).saveWatermark(containerContentsSyncLane(containerId), watermark);\n },\n stillCurrent,\n ),\n upsertDiscoveredDocuments: (inputs, stillCurrent) =>\n whileCurrent(\n [],\n (lockedExecSql) => upsertDiscoveredDocuments(lockedExecSql, inputs),\n stillCurrent,\n ),\n async verifyDiscoveredDocuments(...args) {\n const verification = await input.verifyDiscoveredDocuments(...args);\n return {\n ...verification,\n isCurrent: async () =>\n !input.isPaused() && (await verification.isCurrent()),\n };\n },\n };\n}\n"]}
|
|
@@ -47,12 +47,15 @@ function assertVerdictsCoverCandidates(candidates, verdicts) {
|
|
|
47
47
|
*/
|
|
48
48
|
export async function settleContainerDocumentTombstones(input) {
|
|
49
49
|
const { store } = input;
|
|
50
|
+
const isCurrent = input.isCurrent ?? (async () => true);
|
|
50
51
|
const held = await store.listHeldContainerDocumentTombstones(input.containerIds);
|
|
51
52
|
const candidates = await mergeTombstoneCandidates(store, input.tombstones, held);
|
|
52
53
|
if (candidates.length === 0) {
|
|
53
54
|
return [];
|
|
54
55
|
}
|
|
55
56
|
const verdicts = await store.verifyContainerDocumentTombstones(candidates);
|
|
57
|
+
if (!(await isCurrent()))
|
|
58
|
+
return [];
|
|
56
59
|
assertVerdictsCoverCandidates(candidates, verdicts);
|
|
57
60
|
const verified = verdicts.flatMap((verdict) => verdict.kind === "verified" ? [verdict.tombstone] : []);
|
|
58
61
|
const refuted = verdicts.flatMap((verdict) => verdict.kind === "refuted" ? [verdict.tombstone] : []);
|
|
@@ -75,12 +78,12 @@ export async function settleContainerDocumentTombstones(input) {
|
|
|
75
78
|
}));
|
|
76
79
|
});
|
|
77
80
|
const summaries = verified.length > 0
|
|
78
|
-
? await store.applyContainerDocumentTombstones(verified)
|
|
81
|
+
? await store.applyContainerDocumentTombstones(verified, isCurrent)
|
|
79
82
|
: [];
|
|
80
83
|
const retryKeys = new Set(refuted.map(placementKey));
|
|
81
84
|
const visibleRetries = dedupePlacements(headLinkedPlacements).filter((placement) => !retryKeys.has(placementKey(placement)));
|
|
82
85
|
if (visibleRetries.length > 0) {
|
|
83
|
-
await store.refuteContainerDocumentTombstoneHolds(visibleRetries);
|
|
86
|
+
await store.refuteContainerDocumentTombstoneHolds(visibleRetries, isCurrent);
|
|
84
87
|
}
|
|
85
88
|
const retries = [
|
|
86
89
|
...unverified,
|
|
@@ -88,7 +91,7 @@ export async function settleContainerDocumentTombstones(input) {
|
|
|
88
91
|
...refuted.map((tombstone) => ({ ...tombstone, refuted: true })),
|
|
89
92
|
];
|
|
90
93
|
if (retries.length > 0)
|
|
91
|
-
await store.holdContainerDocumentTombstones(retries);
|
|
94
|
+
await store.holdContainerDocumentTombstones(retries, isCurrent);
|
|
92
95
|
return summaries;
|
|
93
96
|
}
|
|
94
97
|
//# sourceMappingURL=documentTombstoneGate.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentTombstoneGate.js","sourceRoot":"","sources":["documentTombstoneGate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,IAAI,YAAY,EAAE,MAAM,gFAAgF,CAAC;AAkB/I,SAAS,gBAAgB,CACvB,UAA4B;IAE5B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE;QACrC,MAAM,GAAG,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QAChC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,wBAAwB,CACrC,KAAyB,EACzB,MAAiD,EACjD,IAA+C;IAE/C,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,CAAC,MAAM,KAAK,CAAC,oCAAoC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAC5D,YAAY,CACb,CACF,CAAC;IACF,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsC,CAAC;IAClE,KAAK,MAAM,SAAS,IAAI;QACtB,GAAG,IAAI;QACP,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CA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AAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { containerDocumentPlacementKey as placementKey } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport type {\n ContainerDocumentPlacement,\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n DiscoverContainerDocumentsOptions,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype TombstoneGateStore = Pick<\n DiscoverContainerDocumentsOptions,\n | \"applyContainerDocumentTombstones\"\n | \"holdContainerDocumentTombstones\"\n | \"listHeldContainerDocumentTombstones\"\n | \"listKnownContainerDocumentPlacements\"\n | \"refuteContainerDocumentTombstoneHolds\"\n | \"verifyContainerDocumentTombstones\"\n>;\n\nfunction dedupePlacements<T extends ContainerDocumentPlacement>(\n placements: ReadonlyArray<T>,\n): T[] {\n const seen = new Set<string>();\n return placements.filter((placement) => {\n const key = placementKey(placement);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/**\n * One candidate per placement the device actually holds; the newest server\n * timestamp wins. A tombstone for a placement this device never had has\n * nothing to remove or hide, so its head is not fetched.\n */\nasync function mergeTombstoneCandidates(\n store: TombstoneGateStore,\n listed: ReadonlyArray<ContainerDocumentTombstone>,\n held: ReadonlyArray<ContainerDocumentTombstone>,\n): Promise<ContainerDocumentTombstone[]> {\n const known = new Set(\n (await store.listKnownContainerDocumentPlacements(listed)).map(\n placementKey,\n ),\n );\n const byPlacement = new Map<string, ContainerDocumentTombstone>();\n for (const tombstone of [\n ...held,\n ...listed.filter((tombstone) => known.has(placementKey(tombstone))),\n ]) {\n const key = placementKey(tombstone);\n const current = byPlacement.get(key);\n if (\n !current ||\n Date.parse(current.updatedAt) < Date.parse(tombstone.updatedAt)\n ) {\n byPlacement.set(key, tombstone);\n }\n }\n return [...byPlacement.values()];\n}\n\nfunction assertVerdictsCoverCandidates(\n candidates: ReadonlyArray<ContainerDocumentTombstone>,\n verdicts: ReadonlyArray<ContainerDocumentTombstoneVerdict>,\n): void {\n const verdictKeys = new Set(\n verdicts.map((verdict) => placementKey(verdict.tombstone)),\n );\n if (\n verdictKeys.size !== verdicts.length ||\n verdictKeys.size !== candidates.length ||\n candidates.some((candidate) => !verdictKeys.has(placementKey(candidate)))\n ) {\n throw new Error(\n \"Container document tombstone verification must return one verdict per tombstone\",\n );\n }\n}\n\n/**\n * Apply a tombstone only when the signed head omits its container. Unavailable\n * heads leave hidden placements. A head that still links a container keeps its\n * placement visible, but retains a backed-off retry: even an uncached signed\n * head can lag the listing, so its refutation must not discard an honest move.\n * Listing items pass their own signed-head gate before reaching persistence.\n */\nexport async function settleContainerDocumentTombstones(input: {\n containerIds: ReadonlyArray<string>;\n store: TombstoneGateStore;\n tombstones: ReadonlyArray<ContainerDocumentTombstone>;\n}): Promise<ReadonlyArray<DocumentSummary>> {\n const { store } = input;\n const held = await store.listHeldContainerDocumentTombstones(\n input.containerIds,\n );\n const candidates = await mergeTombstoneCandidates(\n store,\n input.tombstones,\n held,\n );\n if (candidates.length === 0) {\n return [];\n }\n\n const verdicts = await store.verifyContainerDocumentTombstones(candidates);\n assertVerdictsCoverCandidates(candidates, verdicts);\n const verified = verdicts.flatMap((verdict) =>\n verdict.kind === \"verified\" ? [verdict.tombstone] : [],\n );\n const refuted = verdicts.flatMap((verdict) =>\n verdict.kind === \"refuted\" ? [verdict.tombstone] : [],\n );\n const unverified = verdicts.flatMap((verdict) =>\n verdict.kind === \"unverified\" ? [verdict.tombstone] : [],\n );\n const deferred = verdicts.flatMap((verdict) =>\n verdict.kind === \"deferred\"\n ? [{ ...verdict.tombstone, deferred: true }]\n : [],\n );\n // A loaded head is evidence for every placement it links, including holds\n // on this document that were not due this run: make them visible while\n // retaining each retry, since the head may lag any of those tombstones.\n const headLinkedPlacements = verdicts.flatMap((verdict) => {\n if (verdict.kind !== \"verified\" && verdict.kind !== \"refuted\") return [];\n const linked =\n verdict.kind === \"verified\"\n ? verdict.tombstone.linkedContainerIds\n : verdict.linkedContainerIds;\n return linked.map((containerId) => ({\n containerId,\n documentId: verdict.tombstone.documentId,\n }));\n });\n\n const summaries =\n verified.length > 0\n ? await store.applyContainerDocumentTombstones(verified)\n : [];\n const retryKeys = new Set(refuted.map(placementKey));\n const visibleRetries = dedupePlacements(headLinkedPlacements).filter(\n (placement) => !retryKeys.has(placementKey(placement)),\n );\n if (visibleRetries.length > 0) {\n await store.refuteContainerDocumentTombstoneHolds(visibleRetries);\n }\n const retries = [\n ...unverified,\n ...deferred,\n ...refuted.map((tombstone) => ({ ...tombstone, refuted: true })),\n ];\n if (retries.length > 0) await store.holdContainerDocumentTombstones(retries);\n return summaries;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"documentTombstoneGate.js","sourceRoot":"","sources":["documentTombstoneGate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,IAAI,YAAY,EAAE,MAAM,gFAAgF,CAAC;AAkB/I,SAAS,gBAAgB,CACvB,UAA4B;IAE5B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE;QACrC,MAAM,GAAG,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QAChC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,wBAAwB,CACrC,KAAyB,EACzB,MAAiD,EACjD,IAA+C;IAE/C,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,CAAC,MAAM,KAAK,CAAC,oCAAoC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAC5D,YAAY,CACb,CACF,CAAC;IACF,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsC,CAAC;IAClE,KAAK,MAAM,SAAS,IAAI;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IACD,MAAM,OAAO,GAAG;QACd,GAAG,UAAU;QACb,GAAG,QAAQ;QACX,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;KACjE,CAAC;IACF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QACpB,MAAM,KAAK,CAAC,+BAA+B,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAClE,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { containerDocumentPlacementKey as placementKey } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport type {\n ContainerDocumentPlacement,\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n DiscoverContainerDocumentsOptions,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype TombstoneGateStore = Pick<\n DiscoverContainerDocumentsOptions,\n | \"applyContainerDocumentTombstones\"\n | \"holdContainerDocumentTombstones\"\n | \"listHeldContainerDocumentTombstones\"\n | \"listKnownContainerDocumentPlacements\"\n | \"refuteContainerDocumentTombstoneHolds\"\n | \"verifyContainerDocumentTombstones\"\n>;\n\nfunction dedupePlacements<T extends ContainerDocumentPlacement>(\n placements: ReadonlyArray<T>,\n): T[] {\n const seen = new Set<string>();\n return placements.filter((placement) => {\n const key = placementKey(placement);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/**\n * One candidate per placement the device actually holds; the newest server\n * timestamp wins. A tombstone for a placement this device never had has\n * nothing to remove or hide, so its head is not fetched.\n */\nasync function mergeTombstoneCandidates(\n store: TombstoneGateStore,\n listed: ReadonlyArray<ContainerDocumentTombstone>,\n held: ReadonlyArray<ContainerDocumentTombstone>,\n): Promise<ContainerDocumentTombstone[]> {\n const known = new Set(\n (await store.listKnownContainerDocumentPlacements(listed)).map(\n placementKey,\n ),\n );\n const byPlacement = new Map<string, ContainerDocumentTombstone>();\n for (const tombstone of [\n ...held,\n ...listed.filter((tombstone) => known.has(placementKey(tombstone))),\n ]) {\n const key = placementKey(tombstone);\n const current = byPlacement.get(key);\n if (\n !current ||\n Date.parse(current.updatedAt) < Date.parse(tombstone.updatedAt)\n ) {\n byPlacement.set(key, tombstone);\n }\n }\n return [...byPlacement.values()];\n}\n\nfunction assertVerdictsCoverCandidates(\n candidates: ReadonlyArray<ContainerDocumentTombstone>,\n verdicts: ReadonlyArray<ContainerDocumentTombstoneVerdict>,\n): void {\n const verdictKeys = new Set(\n verdicts.map((verdict) => placementKey(verdict.tombstone)),\n );\n if (\n verdictKeys.size !== verdicts.length ||\n verdictKeys.size !== candidates.length ||\n candidates.some((candidate) => !verdictKeys.has(placementKey(candidate)))\n ) {\n throw new Error(\n \"Container document tombstone verification must return one verdict per tombstone\",\n );\n }\n}\n\n/**\n * Apply a tombstone only when the signed head omits its container. Unavailable\n * heads leave hidden placements. A head that still links a container keeps its\n * placement visible, but retains a backed-off retry: even an uncached signed\n * head can lag the listing, so its refutation must not discard an honest move.\n * Listing items pass their own signed-head gate before reaching persistence.\n */\nexport async function settleContainerDocumentTombstones(input: {\n containerIds: ReadonlyArray<string>;\n isCurrent?: () => Promise<boolean>;\n store: TombstoneGateStore;\n tombstones: ReadonlyArray<ContainerDocumentTombstone>;\n}): Promise<ReadonlyArray<DocumentSummary>> {\n const { store } = input;\n const isCurrent = input.isCurrent ?? (async () => true);\n const held = await store.listHeldContainerDocumentTombstones(\n input.containerIds,\n );\n const candidates = await mergeTombstoneCandidates(\n store,\n input.tombstones,\n held,\n );\n if (candidates.length === 0) {\n return [];\n }\n\n const verdicts = await store.verifyContainerDocumentTombstones(candidates);\n if (!(await isCurrent())) return [];\n assertVerdictsCoverCandidates(candidates, verdicts);\n const verified = verdicts.flatMap((verdict) =>\n verdict.kind === \"verified\" ? [verdict.tombstone] : [],\n );\n const refuted = verdicts.flatMap((verdict) =>\n verdict.kind === \"refuted\" ? [verdict.tombstone] : [],\n );\n const unverified = verdicts.flatMap((verdict) =>\n verdict.kind === \"unverified\" ? [verdict.tombstone] : [],\n );\n const deferred = verdicts.flatMap((verdict) =>\n verdict.kind === \"deferred\"\n ? [{ ...verdict.tombstone, deferred: true }]\n : [],\n );\n // A loaded head is evidence for every placement it links, including holds\n // on this document that were not due this run: make them visible while\n // retaining each retry, since the head may lag any of those tombstones.\n const headLinkedPlacements = verdicts.flatMap((verdict) => {\n if (verdict.kind !== \"verified\" && verdict.kind !== \"refuted\") return [];\n const linked =\n verdict.kind === \"verified\"\n ? verdict.tombstone.linkedContainerIds\n : verdict.linkedContainerIds;\n return linked.map((containerId) => ({\n containerId,\n documentId: verdict.tombstone.documentId,\n }));\n });\n\n const summaries =\n verified.length > 0\n ? await store.applyContainerDocumentTombstones(verified, isCurrent)\n : [];\n const retryKeys = new Set(refuted.map(placementKey));\n const visibleRetries = dedupePlacements(headLinkedPlacements).filter(\n (placement) => !retryKeys.has(placementKey(placement)),\n );\n if (visibleRetries.length > 0) {\n await store.refuteContainerDocumentTombstoneHolds(\n visibleRetries,\n isCurrent,\n );\n }\n const retries = [\n ...unverified,\n ...deferred,\n ...refuted.map((tombstone) => ({ ...tombstone, refuted: true })),\n ];\n if (retries.length > 0)\n await store.holdContainerDocumentTombstones(retries, isCurrent);\n return summaries;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ExecSql, type ExecSqlClientLike } from "../../data/sqlite/sqlSchema.js";
|
|
2
|
+
export declare function deriveRegistrationOrganizationId(rootContainerId: string): Promise<string>;
|
|
2
3
|
interface RootContainerBootstrapResult {
|
|
3
4
|
containerId: string;
|
|
4
5
|
created: boolean;
|
|
@@ -1,5 +1,14 @@
|
|
|
1
|
+
import { deriveStableUuidV4Shaped } from "../../data/keying/stableUuid.js";
|
|
1
2
|
import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/container-contents/containerPersistence.js";
|
|
2
3
|
import { createExecSql, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
|
|
4
|
+
// A device-first root can receive deleted items before its organization is registered.
|
|
5
|
+
const ORGANIZATION_ID_NAMESPACE = new Uint8Array([
|
|
6
|
+
0x62, 0xb5, 0x73, 0xbf, 0x47, 0x2a, 0x4f, 0x93, 0x87, 0xcf, 0x07, 0x8e, 0x25,
|
|
7
|
+
0xa1, 0xd2, 0x68,
|
|
8
|
+
]);
|
|
9
|
+
export function deriveRegistrationOrganizationId(rootContainerId) {
|
|
10
|
+
return deriveStableUuidV4Shaped(ORGANIZATION_ID_NAMESPACE, rootContainerId);
|
|
11
|
+
}
|
|
3
12
|
async function bootstrapRootContainerFromExecSql(execSql) {
|
|
4
13
|
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
5
14
|
await ensureContainerTables(lockedExecSql);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,uFAAuF;AACvF,MAAM,yBAAyB,GAAG,IAAI,UAAU,CAAC;IAC/C,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE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C,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import { deriveStableUuidV4Shaped } from \"../../data/keying/stableUuid\";\nimport {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/container-contents/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\n// A device-first root can receive deleted items before its organization is registered.\nconst ORGANIZATION_ID_NAMESPACE = new Uint8Array([\n 0x62, 0xb5, 0x73, 0xbf, 0x47, 0x2a, 0x4f, 0x93, 0x87, 0xcf, 0x07, 0x8e, 0x25,\n 0xa1, 0xd2, 0x68,\n]);\n\nexport function deriveRegistrationOrganizationId(\n rootContainerId: string,\n): Promise<string> {\n return deriveStableUuidV4Shaped(ORGANIZATION_ID_NAMESPACE, rootContainerId);\n}\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
|
|
2
|
-
export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
|
|
2
|
+
export { bootstrapRootContainer, deriveRegistrationOrganizationId, } from "./bootstrapRootContainer.js";
|
|
3
3
|
export { type CreateOrganizationApi, type CreateOrganizationInput, createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
|
|
4
4
|
export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
|
|
5
5
|
export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
|
|
2
|
-
export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
|
|
2
|
+
export { bootstrapRootContainer, deriveRegistrationOrganizationId, } from "./bootstrapRootContainer.js";
|
|
3
3
|
export { createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
|
|
4
4
|
export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
|
|
5
5
|
export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EACL,sBAAsB,EACtB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AAEnH,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nexport {\n bootstrapRootContainer,\n deriveRegistrationOrganizationId,\n} from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport type { ProvisionedSystemContainerSpec } from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
|
|
@@ -8,10 +8,11 @@ export type { ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuil
|
|
|
8
8
|
* The freshly built provisioning artifacts, shared by registration and
|
|
9
9
|
* additional-organization creation. `registerIdentity` generates a new
|
|
10
10
|
* `userId`; creating an additional organization reuses the caller's existing
|
|
11
|
-
* one.
|
|
12
|
-
*
|
|
11
|
+
* one. Registration supplies the personal organization ID planned for the local
|
|
12
|
+
* root. An additional organization receives a fresh ID.
|
|
13
13
|
*/
|
|
14
14
|
export interface OrganizationProvisioningArtifactsInput {
|
|
15
|
+
organizationId?: string;
|
|
15
16
|
identityTrustDomain: string;
|
|
16
17
|
encapsulationKeyPair: EncapsulationKeyPair;
|
|
17
18
|
organizationProfileName?: string | undefined;
|
|
@@ -10,7 +10,7 @@ import { buildInitialOrganizationMetadataBootstrap, buildInitialRootProvisioning
|
|
|
10
10
|
import { createInitialRootMetadataBootstrap } from "./rootMetadataBootstrap.js";
|
|
11
11
|
export { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
|
|
12
12
|
async function createOrganizationPrincipalPolicies(input) {
|
|
13
|
-
const organizationId = crypto.randomUUID();
|
|
13
|
+
const organizationId = input.organizationId ?? crypto.randomUUID();
|
|
14
14
|
const signingFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
|
|
15
15
|
const initialAdminGroup = await buildInitialGroupPolicyRequest({
|
|
16
16
|
identityTrustDomain: input.identityTrustDomain,
|
|
@@ -123,7 +123,6 @@ export async function buildOrganizationProvisioningArtifacts(input) {
|
|
|
123
123
|
initialAdminGroup,
|
|
124
124
|
rootContainer,
|
|
125
125
|
rootContainerProjection,
|
|
126
|
-
signingPrivateKey: input.signingKeyPair.signingPrivateKey,
|
|
127
126
|
spec,
|
|
128
127
|
targetSecretKey: input.encapsulationKeyPair.secretKey,
|
|
129
128
|
})));
|