@tearleads/client-sdk 0.1.217 → 0.1.218

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.
Files changed (139) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/index.d.ts +1 -1
  25. package/index.js.map +1 -1
  26. package/package.json +1 -1
  27. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  28. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  29. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  30. package/stores/documents/documentStore/rotation/index.js +1 -2
  31. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  32. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  33. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  34. package/stores/documents/documentStore/state.js.map +1 -1
  35. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  36. package/stores/documents/documentStore/sync/index.js.map +1 -1
  37. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  38. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  39. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  40. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  41. package/stores/documents/documentStore/sync/syncRequest.js +3 -2
  42. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  43. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  45. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  46. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  47. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  48. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  49. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  50. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  51. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  52. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  53. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  54. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  55. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  56. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  57. package/workflows/container-contents/container-state/remote.js +3 -4
  58. package/workflows/container-contents/container-state/remote.js.map +1 -1
  59. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  60. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  61. package/workflows/container-contents/container-state/share/index.js +2 -3
  62. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  63. package/workflows/container-contents/container-state/types.js.map +1 -1
  64. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  65. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  66. package/workflows/container-contents/documentLinks/index.js +3 -2
  67. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  68. package/workflows/container-contents/index.d.ts +1 -1
  69. package/workflows/container-contents/index.js +1 -1
  70. package/workflows/container-contents/index.js.map +1 -1
  71. package/workflows/container-contents/metadata/index.d.ts +1 -1
  72. package/workflows/container-contents/metadata/index.js.map +1 -1
  73. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +3 -3
  74. package/workflows/container-contents/metadata/metadataRemoteSync.js +3 -2
  75. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  76. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  77. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  78. package/workflows/container-contents/remoteHydration/index.js +1 -2
  79. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  80. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  81. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  82. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  83. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  84. package/workflows/container-contents/runtime.d.ts +13 -2
  85. package/workflows/container-contents/runtime.js +33 -21
  86. package/workflows/container-contents/runtime.js.map +1 -1
  87. package/workflows/container-contents/syncLane.d.ts +1 -1
  88. package/workflows/container-contents/syncLane.js.map +1 -1
  89. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  90. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  91. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  92. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  93. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  94. package/workflows/documents/index.d.ts +1 -1
  95. package/workflows/documents/index.js +1 -1
  96. package/workflows/documents/index.js.map +1 -1
  97. package/workflows/documents/runtime.d.ts +12 -1
  98. package/workflows/documents/runtime.js +24 -16
  99. package/workflows/documents/runtime.js.map +1 -1
  100. package/workflows/documents/sync/syncLane.d.ts +1 -1
  101. package/workflows/documents/sync/syncLane.js.map +1 -1
  102. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  103. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  104. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  105. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  106. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  107. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  108. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  109. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  110. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  111. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  112. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  113. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  114. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  115. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  116. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  117. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  118. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  119. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  120. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  121. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  122. package/workflows/principals/index.d.ts +1 -0
  123. package/workflows/principals/index.js.map +1 -1
  124. package/workflows/principals/principalPolicyService.d.ts +64 -0
  125. package/workflows/principals/principalPolicyService.js +117 -0
  126. package/workflows/principals/principalPolicyService.js.map +1 -0
  127. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  128. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  129. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  130. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  131. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  132. package/data/principals/principalHistoryRuntime.js +0 -12
  133. package/data/principals/principalHistoryRuntime.js.map +0 -1
  134. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  135. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  136. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  137. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  138. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  139. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AACjH,OAAO,EACL,kCAAkC,GAEnC,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAGL,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC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,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,yEAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
1
+ {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAElB,wBAAwB,EAExB,mCAAmC,EACnC,iCAAiC,EAEjC,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AAEjH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAGL,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAChD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,mCAAmC;QACpD,UAAU;QACV,KAAK;QACL,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oCAAoC,CAClD,K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EAAyE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
@@ -2,7 +2,6 @@ import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
2
2
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, } from "../../../../data/keyingProjectionVerification/index.js";
3
3
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, } from "../../../../data/keyingProjectionVerification/error.js";
4
4
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
5
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
6
5
  import { settleContainerCreateIntent } from "./createIntentSettlement.js";
7
6
  const LABEL = "Container create conflict";
8
7
  /** The recorded error that parks an intent whose listed create is foreign. */
@@ -29,7 +28,7 @@ async function verifyAdoptableProjection(input) {
29
28
  execSql: input.state.runtime.infra.execSql,
30
29
  projection,
31
30
  resolveUserKey: input.state.resolveProjectionUserKey,
32
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.state.runtime),
31
+ warmReferencedPrincipalPolicies: input.state.runtime.principalPolicies.createWarmer(),
33
32
  });
34
33
  const head = path.at(-1);
35
34
  // One read naming another container says nothing signed about this id.
@@ -1 +1 @@
1
- {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,yBAAyB,EACzB,yCAAyC,GAC1C,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AACpE,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAO7F,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAEvE,MAAM,KAAK,GAAG,2BAA2B,CAAC;AAE1C,8EAA8E;AAC9E,MAAM,CAAC,MAAM,iCAAiC,GAC5C,uCAAuC,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,2BAA4B,SAAQ,uBAAu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M,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC;IAC/C,IAAI,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;QACpE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,SAAoC,CAAC;IACzC,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,2BAA2B,CAAC;YAC5C,MAAM;YACN,WAAW;YACX,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,qBAAqB,CAAC;YAC3B,KAAK;YACL,cAAc,EAAE,WAAW,CAAC,SAAS,CAAC,cAAc;YACpD,SAAS;SACV,CAAC,CAAC;IACL,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC;QACpD,cAAc;QACd,SAAS;QACT,SAAS;KACV,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAC1D,2EAA2E;IAC3E,yCAAyC;IACzC,IAAI,SAAS,CAAC,eAAe,KAAK,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC3D,SAAS,CAAC,2BAA2B,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.state.runtime,\n ),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
1
+ {"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,yBAAyB,EACzB,yCAAyC,GAC1C,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAQpE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAEvE,MAAM,KAAK,GAAG,2BAA2B,CAAC;AAE1C,8EAA8E;AAC9E,MAAM,CAAC,MAAM,iCAAiC,GAC5C,uCAAuC,CAAC;AAE1C;;;;;GAKG;AACH,MAAM,2BAA4B,SAAQ,uB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K,CAAC;IACzD,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC;IAC/C,IAAI,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;QACpE,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,SAAoC,CAAC;IACzC,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,2BAA2B,CAAC;YAC5C,MAAM;YACN,WAAW;YACX,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,qBAAqB,CAAC;YAC3B,KAAK;YACL,cAAc,EAAE,WAAW,CAAC,SAAS,CAAC,cAAc;YACpD,SAAS;SACV,CAAC,CAAC;IACL,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC;QACpD,cAAc;QACd,SAAS;QACT,SAAS;KACV,CAAC,CAAC;IACH,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC;IAC1D,2EAA2E;IAC3E,yCAAyC;IACzC,IAAI,SAAS,CAAC,eAAe,KAAK,MAAM,CAAC,iBAAiB,EAAE,CAAC;QAC3D,SAAS,CAAC,2BAA2B,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n} from \"../../../../data/keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport type {\n AdoptedContainerPlacement,\n ContainerCreateIntentSyncInput,\n ContainerCreateIntentSyncState,\n} from \"../types\";\nimport { settleContainerCreateIntent } from \"./createIntentSettlement\";\n\nconst LABEL = \"Container create conflict\";\n\n/** The recorded error that parks an intent whose listed create is foreign. */\nexport const CONTAINER_CREATE_ADOPTION_REFUSED =\n \"Container create adoption was refused\";\n\n/**\n * The listed create's signed identity is not this device's pending create: its\n * signed create names another signer, another organization, or a root. An honest server never lists that under the\n * id this device minted, and no later read can change those signed facts, so\n * the intent parks instead of re-verifying.\n */\nclass ForeignContainerCreateError extends KeyingVerificationError {}\n\nfunction foreignCreate(\n code: KeyingVerificationCode,\n message: string,\n): ForeignContainerCreateError {\n return new ForeignContainerCreateError(code, `${LABEL} ${message}`);\n}\n\nasync function verifyAdoptableProjection(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly projection: ContainerWriterProjectionResponse;\n readonly sessionUserId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { projection } = input;\n if (\n projection.containerId !== input.containerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n // The envelope is unsigned: a corrupt read is retried, not parked.\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection has the wrong identity`,\n );\n }\n const { path, verifiedByHash } = await verifyContainerDestinationProjection({\n execSql: input.state.runtime.infra.execSql,\n projection,\n resolveUserKey: input.state.resolveProjectionUserKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n });\n const head = path.at(-1);\n // One read naming another container says nothing signed about this id.\n if (!head || head.state.containerId !== input.containerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${LABEL} projection names another container`,\n );\n }\n const create = verifiedContainerCreateManifest({\n head,\n label: LABEL,\n verifiedByHash,\n });\n if (create.event.event.signerUserId !== input.sessionUserId) {\n throw foreignCreate(\"signer_mismatch\", \"was signed by another user\");\n }\n if (create.state.organizationId !== input.expectedOrganizationId) {\n throw foreignCreate(\"object_mismatch\", \"belongs to another organization\");\n }\n const createdParentId = create.state.parentContainerId;\n const currentParentId = head.state.parentContainerId;\n if (createdParentId === null || currentParentId === null) {\n throw foreignCreate(\"object_mismatch\", \"is an organization root\");\n }\n return { createdParentId, currentParentId };\n}\n\n/**\n * A pending create whose container the listing already carries is adopted\n * only when the container's signed epoch-1 `container.create` is this user's,\n * in the intended organization (#2365 finding 26). Listing metadata is\n * unsigned: a create by another writer that collides on the pending id, or one\n * a dishonest server invents, must not become this device's container.\n * Documents apply the same rule (`workflows/documents/createAdoption.ts`).\n *\n * Returns where the create committed and where the verified head sits now.\n * The user may have moved the pending container since, which rewrites its\n * intent's parent; that is a move still owed, not a mismatch.\n */\nasync function assertContainerCreateAdoptable(input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const { runtime } = input.state;\n const sessionUserId = runtime.auth.userId;\n // Without a session user there is no signer to compare: not tampering.\n if (!sessionUserId) {\n throw new Error(`${LABEL} needs a signed-in session user`);\n }\n const projection = await runtime.apiClient.getContainerWriterProjection(\n input.containerId,\n );\n if (!projection) {\n throw new Error(`${LABEL} is unavailable to verify`);\n }\n try {\n return await verifyAdoptableProjection({\n ...input,\n projection,\n sessionUserId,\n });\n } catch (error) {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error)) {\n runtime.apiClient.evictContainerWriterProjection(input.containerId);\n }\n throw error;\n }\n}\n\nfunction verifyListedContainerCreate(input: {\n readonly intent: ContainerCreateIntentSyncInput[\"intent\"];\n readonly parentState: ContainerState;\n readonly state: ContainerCreateIntentSyncState;\n}): Promise<AdoptedContainerPlacement> {\n const adoption = {\n containerId: input.intent.containerId,\n expectedOrganizationId: input.parentState.container.organizationId,\n };\n return input.state.verifyCreateAdoption\n ? input.state.verifyCreateAdoption(adoption)\n : assertContainerCreateAdoptable({ ...adoption, state: input.state });\n}\n\n/** Settles a verified adoption against the row hydration installed. */\nasync function markContainerCreateIntentAdopted(input: {\n containerState: ContainerState;\n placement: AdoptedContainerPlacement;\n syncInput: ContainerCreateIntentSyncInput;\n}): Promise<boolean> {\n const { containerState, placement, syncInput } = input;\n const remoteMetadataDocumentId = containerState.record.documentId;\n const remoteMetadataAccessStateHash = containerState.record.accessStateHash;\n\n if (!remoteMetadataDocumentId || !remoteMetadataAccessStateHash) {\n return false;\n }\n return settleContainerCreateIntent({\n createdParentContainerId: placement.createdParentId,\n desiredParentContainerId: syncInput.intent.parentContainerId,\n intent: syncInput.intent,\n isCurrent: syncInput.isCurrent,\n remoteContainerId: containerState.container.id,\n remoteMetadataAccessStateHash,\n remoteMetadataDocumentId,\n state: syncInput.state,\n supersededMovePreviousParentId: placement.currentParentId,\n });\n}\n\n/**\n * Records a failed adoption and leaves the lane's other intents to proceed. A\n * foreign create parks the intent: its signed facts never change, so later\n * passes neither re-read it nor report it again. Any other failure retries.\n */\nasync function recordAdoptionFailure(input: {\n readonly error: unknown;\n readonly organizationId: string;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"failed\"> {\n const { intent, isCurrent, state } = input.syncInput;\n if (!isCurrent()) return \"abandoned\";\n await reportKeyingVerificationErrorInCauseChain(\n input.error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.create.replay\",\n organizationId: input.organizationId,\n },\n );\n if (!isCurrent()) return \"abandoned\";\n const action =\n input.error instanceof ForeignContainerCreateError\n ? CONTAINER_CREATE_ADOPTION_REFUSED\n : \"Container create adoption verification failed\";\n await state.persistence.recordCreateIntentRevisionError(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n message: `${action}: ${errorMessage(input.error)}`,\n stillCurrent: isCurrent,\n },\n );\n return isCurrent() ? \"failed\" : \"abandoned\";\n}\n\n/**\n * Adopts a pending create the listing already carries, once its signed create\n * proves it is this device's. A parked refusal stays blocked without a read.\n */\nexport async function syncListedContainerCreate(input: {\n readonly containerState: ContainerState;\n readonly parentState: ContainerState;\n readonly syncInput: ContainerCreateIntentSyncInput;\n}): Promise<\"abandoned\" | \"blocked\" | \"created\" | \"failed\"> {\n const { containerState, parentState, syncInput } = input;\n const { intent, isCurrent, state } = syncInput;\n if (intent.lastError?.startsWith(CONTAINER_CREATE_ADOPTION_REFUSED)) {\n return \"blocked\";\n }\n let placement: AdoptedContainerPlacement;\n try {\n placement = await verifyListedContainerCreate({\n intent,\n parentState,\n state,\n });\n } catch (error) {\n return recordAdoptionFailure({\n error,\n organizationId: parentState.container.organizationId,\n syncInput,\n });\n }\n const marked = await markContainerCreateIntentAdopted({\n containerState,\n placement,\n syncInput,\n });\n if (!marked) return isCurrent() ? \"blocked\" : \"abandoned\";\n // The folder now sits elsewhere; list it there rather than waiting for the\n // next poll to correct the local parent.\n if (placement.currentParentId !== intent.parentContainerId) {\n syncInput.requestRemoteReconciliation(placement.currentParentId);\n }\n return \"created\";\n}\n"]}
@@ -10,7 +10,6 @@ import { repairContainerCreateFailure } from "../../../containers/child/create/c
10
10
  import { documentWriterProjectionFromCreateResponse, resolveDocumentCreateAuthor, } from "../../../documents/index.js";
11
11
  import { buildDocumentCreateSeedRequest, documentCreateSeedFits, } from "../../../documents/sync/initialSync.js";
12
12
  import { PrincipalPolicyRepairBudget } from "../../../principals/policyRepairBudget.js";
13
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
14
13
  import { settleTerminalCreateFailure } from "./createTerminalFailure.js";
15
14
  import { buildContainerWithMetadataPlans, } from "./createWithMetadataPlan.js";
16
15
  /**
@@ -252,7 +251,7 @@ async function createContainerWithMetadataWithRepairs(input) {
252
251
  parentContainerId: input.parentContainerId,
253
252
  parentProjection,
254
253
  state: repairState,
255
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
254
+ warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer(),
256
255
  stillCurrent: input.stillCurrent,
257
256
  });
258
257
  if (repair.kind === "retry") {
@@ -1 +1 @@
1
- {"version":3,"file":"createWithMetadata.js","sourceRoot":"","sources":["createWithMetadata.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AAMnD,OAAO,EAAE,wCAAwC,EAAE,MAAM,4DAA4D,CAAC;AACtH,OAAO,EAAE,wCAAwC,EAAE,MAAM,qDAAqD,CAAC;AAE/G,OAAO,EAAE,wCAAwC,EAAE,MAAM,8CAA8C,CAAC;AACxG,OAAO,EAEL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,6CAA6C,CAAC;AAErD,OAAO,EAAE,0BAA0B,EAAE,MAAM,2EAA2E,CAAC;AACvH,OAAO,EAAE,iCAAiC,EAAE,MAAM,yFAAyF,CAAC;AAE5I,OAAO,EAEL,iCAAiC,GAClC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AACjG,OAAO,EAEL,0CAA0C,EAC1C,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,8BAA8B,EAC9B,sBAAsB,GACvB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAK7F,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACL,+BAA+B,GAEhC,MAAM,0BAA0B,CAAC;AAElC;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAG/E,KAAK,UAAU,mCAAmC,CAAC,KAKlD;IAQC,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD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C,gBAAgB;QACtB,CAAC,MAAM,SAAS,CAAC,4BAA4B,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC1E,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,gBAAgB,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC7C,MAAM,YAAY,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IAChE,MAAM,iBAAiB,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACnD,MAAM,kBAAkB,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACtE,MAAM,eAAe,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC5C,MAAM,gBAAgB,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAClD,OAAO,sCAAsC,CAAC;QAC5C,MAAM;QACN,gBAAgB;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY;QACZ,iBAAiB;QACjB,kBAAkB;QAClB,eAAe;QACf,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,gBAAgB;QAChB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,gBAAgB;QAChB,eAAe;QACf,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,UAAU,EAAE,KAAK,CAAC,UAAU;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport {\n type ContainerSystemSlot,\n isContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerCreateWithMetadataDocumentRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { locallyAcknowledgedContainerMutationHead } from \"../../../../data/containers/shared/mutationAcknowledgement\";\nimport { isContainerManifestAlreadyExistsConflict } from \"../../../../data/containers/shared/mutationFailures\";\nimport type { ContainerMutationSubmitFailure } from \"../../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../../data/documents/shared/projection\";\nimport {\n type AcknowledgedDocumentMutation,\n acknowledgedDocumentCreate,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\nimport {\n type buildMaterializedContainerCreatePlan,\n signedContainerMetadataDocumentId,\n} from \"../../../containers\";\nimport { repairContainerCreateFailure } from \"../../../containers/child/create/createSubmission\";\nimport {\n type buildMaterializedDocumentCreatePlan,\n documentWriterProjectionFromCreateResponse,\n resolveDocumentCreateAuthor,\n} from \"../../../documents\";\nimport {\n buildDocumentCreateSeedRequest,\n documentCreateSeedFits,\n} from \"../../../documents/sync/initialSync\";\nimport { PrincipalPolicyRepairBudget } from \"../../../principals/policyRepairBudget\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type {\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n} from \"../types\";\nimport { settleTerminalCreateFailure } from \"./createTerminalFailure\";\nimport {\n buildContainerWithMetadataPlans,\n type ContainerWithMetadataPlanInput,\n} from \"./createWithMetadataPlan\";\n\n/**\n * Sentinel for a lost-response retry whose manifest already exists remotely.\n * Callers avoid a duplicate; the next parent hydration settles local state.\n */\nexport const CONTAINER_ALREADY_COMMITTED = Symbol(\"containerAlreadyCommitted\");\nexport type ContainerAlreadyCommitted = typeof CONTAINER_ALREADY_COMMITTED;\n\nasync function submitContainerWithMetadataDocument(input: {\n readonly organizationId: string;\n readonly request: ContainerCreateWithMetadataDocumentRequest;\n readonly runtime: ContainerWorkflowRuntime;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly ok: true;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n }\n | ContainerMutationSubmitFailure\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const result = await apiClient.createContainerWithMetadataDocumentResult(\n input.request,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n },\n );\n return result.ok ? { ok: true, response: result.data } : result;\n}\n\n/**\n * Seed the metadata document's writer projection from the create response so the\n * first read after the container is created (its own metadata sync, contents\n * hydration) resolves locally instead of a cold `GET writer-projection`. The\n * authorizing path is the child container projection the create was authored\n * against — locally built rather than server-fetched, so unlike the plain\n * document-create path this is gated on the projection's internal consistency;\n * on any mismatch the seed is skipped and the next read falls back to a fetch.\n */\nasync function seedMetadataDocumentWriterProjection(input: {\n readonly runtime: ContainerWorkflowRuntime;\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly metadataDocument: AcknowledgedDocumentMutation;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const projection = documentWriterProjectionFromCreateResponse({\n containerProjection: input.childProjection,\n response: input.metadataDocument,\n });\n try {\n await assertDocumentWriterProjectionConsistent(projection, {\n execSql: input.execSql,\n stillCurrent: input.stillCurrent,\n trustedLocalProjection: true,\n });\n } catch {\n return;\n }\n if (input.stillCurrent?.() === false) return;\n input.runtime.apiClient.primeDocumentWriterProjection(\n input.metadataDocument.id,\n projection,\n );\n}\n\nasync function acknowledgeContainerWithMetadata(input: {\n containerPlan: Parameters<\n typeof locallyAcknowledgedContainerMutationHead\n >[0][\"plan\"];\n execSql: ExecSql;\n metadataDocumentPlan: Parameters<typeof acknowledgedDocumentCreate>[0];\n response: ContainerCreateWithMetadataDocumentResponse;\n stillCurrent?: (() => boolean) | undefined;\n}) {\n const metadataDocument = acknowledgedDocumentCreate(\n input.metadataDocumentPlan,\n input.response.metadataDocument,\n );\n const containerHead = await locallyAcknowledgedContainerMutationHead({\n plan: input.containerPlan,\n response: input.response.container,\n });\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n containerHead,\n locallyAuthoredAccessManifestHead(input.metadataDocumentPlan),\n ],\n stillCurrent: input.stillCurrent,\n });\n return metadataDocument;\n}\n\n/**\n * Prime the new container's writer projection from the create plan the client\n * just authored, so the first write under it (a child folder, a document)\n * resolves locally instead of a cold `GET writer-projection`. Only primed when\n * the locally-built projection matches what the server created — the create\n * response echoes the container id and manifest head — so a mismatch skips the\n * seed and the next write falls back to a fetch (same fail-closed contract as\n * the metadata-document seed). Priming is safe for writes: the server still\n * validates every mutation, so a projection that later goes stale (rekey/share/\n * move evict it) just yields a rejected write that retries with a fresh fetch.\n */\nfunction seedChildContainerWriterProjection(input: {\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n readonly runtime: ContainerWorkflowRuntime;\n}): void {\n const createdManifestHash =\n input.response.container.manifestHead.manifestHash;\n const projectedManifestHash = input.childProjection.path.at(-1)?.manifestHash;\n // Both hashes must be present and equal, or two undefined hashes would compare\n // equal and prime an empty/invalid projection.\n if (\n !createdManifestHash ||\n !projectedManifestHash ||\n input.childProjection.containerId !==\n input.response.container.containerId ||\n projectedManifestHash !== createdManifestHash\n ) {\n return;\n }\n\n input.runtime.apiClient.primeContainerWriterProjection(\n input.response.container.containerId,\n input.childProjection,\n );\n}\n\n/**\n * The persisted slot is the one this client signed into the manifest state.\n * The acknowledgement already refused a response that echoed anything else,\n * so the server's column never chooses which local record becomes Trash.\n */\nfunction signedCreateSystemSlot(\n state: ContainerAccessManifestState,\n): ContainerSystemSlot | null {\n if (state.systemSlot === null) return null;\n if (!isContainerSystemSlot(state.systemSlot)) {\n throw new Error(\"Container create plan signed an invalid system slot\");\n }\n return state.systemSlot;\n}\n\n/** The seed the create committed, if the response accepted it. */\nfunction committedMetadataSeed(\n response: ContainerCreateWithMetadataDocumentResponse,\n seedUpdateId: string | undefined,\n): CreatedRemoteContainerState[\"metadataSeed\"] {\n const seed = response.metadataDocument.initialSync;\n return seedUpdateId && seed?.acceptedOutgoingUpdateIds.includes(seedUpdateId)\n ? { commitLsn: seed.commitLsn, updateId: seedUpdateId }\n : undefined;\n}\n\nasync function settleContainerWithMetadataCreate(input: {\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly containerPlan: Awaited<\n ReturnType<typeof buildMaterializedContainerCreatePlan>\n >;\n readonly execSql: ExecSql;\n readonly metadataDocumentPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n readonly runtime: ContainerWorkflowRuntime;\n readonly seedUpdateId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly ok: true;\n readonly state: CreatedRemoteContainerState;\n} | null> {\n if (\n input.response.container.containerId !==\n input.containerPlan.plan.containerId\n ) {\n throw new Error(\"Container metadata create response container mismatch\");\n }\n // The acknowledgement echoed the signed parent, which a child always names.\n const parentId = input.containerPlan.plan.state.parentContainerId;\n if (parentId === null) {\n throw new Error(\"A container create must commit under a parent\");\n }\n // The acknowledgement carries no state: the metadata document is the one\n // this client signed into the container, matched by the manifest hash.\n const metadataDocumentId = signedContainerMetadataDocumentId(\n input.containerPlan.plan,\n );\n if (\n metadataDocumentId !== input.containerPlan.plan.metadataDocumentId ||\n input.response.metadataDocument.id !==\n input.metadataDocumentPlan.plan.documentId\n ) {\n throw new Error(\"Container metadata create response document mismatch\");\n }\n const metadataDocument = await acknowledgeContainerWithMetadata({\n containerPlan: input.containerPlan.plan,\n execSql: input.execSql,\n metadataDocumentPlan: input.metadataDocumentPlan.plan,\n response: input.response,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n await seedMetadataDocumentWriterProjection({\n childProjection: input.childProjection,\n execSql: input.execSql,\n metadataDocument,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n seedChildContainerWriterProjection({\n childProjection: input.childProjection,\n response: input.response,\n runtime: input.runtime,\n });\n const metadataSeed = committedMetadataSeed(\n input.response,\n input.seedUpdateId,\n );\n return {\n ok: true,\n state: {\n accessManifestHash: input.response.container.manifestHead.manifestHash,\n ...(metadataSeed ? { metadataSeed } : {}),\n systemSlot: signedCreateSystemSlot(input.containerPlan.plan.state),\n containerId: input.response.container.containerId,\n createdAt: input.response.container.createdAt,\n metadataDocumentId,\n organizationId: input.response.container.organizationId,\n parentId,\n persistedMetadataState:\n persistedDocumentStateFromAcknowledgement(metadataDocument),\n updatedAt: input.response.container.updatedAt,\n },\n };\n}\n\nasync function createRemoteContainerWithMetadataDocumentAttempt(\n input: ContainerWithMetadataPlanInput,\n): Promise<\n | {\n readonly ok: true;\n readonly state: CreatedRemoteContainerState;\n }\n | ContainerMutationSubmitFailure\n | null\n> {\n const execSql = input.runtime.infra.execSql;\n const plans = await buildContainerWithMetadataPlans(input);\n if (!plans) return null;\n const { containerPlan, childProjection, metadataDocumentPlan } = plans;\n const request = {\n systemSlot: input.systemSlot ?? null,\n container: containerPlan.plan.request,\n metadataDocument: metadataDocumentPlan.plan.request,\n };\n const submitRequest = (body: ContainerCreateWithMetadataDocumentRequest) =>\n submitContainerWithMetadataDocument({\n organizationId: containerPlan.plan.state.organizationId,\n request: body,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n const seed = input.metadataSeedUpdate\n ? await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: childProjection,\n materializedDocument: metadataDocumentPlan,\n pendingUpdate: input.metadataSeedUpdate,\n })\n : null;\n let submitted: Awaited<ReturnType<typeof submitRequest>> = null;\n if (seed && documentCreateSeedFits(seed)) {\n submitted = await submitRequest({ ...request, initialMetadataSync: seed });\n if (!submitted) return null;\n }\n // A seed only saves the first metadata sync: a refused seeded create falls\n // back to the plain create once, so the row syncs as before, and its failures\n // take the ordinary repair path. A lost response is adopted directly, as a\n // plain create's would be.\n const seeded = submitted?.ok === true;\n if (\n !submitted ||\n (!submitted.ok && !isContainerManifestAlreadyExistsConflict(submitted))\n ) {\n submitted = await submitRequest(request);\n }\n if (!submitted?.ok) {\n return submitted;\n }\n return settleContainerWithMetadataCreate({\n childProjection,\n containerPlan,\n execSql,\n metadataDocumentPlan,\n response: submitted.response,\n runtime: input.runtime,\n seedUpdateId: seeded ? input.metadataSeedUpdate?.id : undefined,\n stillCurrent: input.stillCurrent,\n });\n}\n\nasync function createContainerWithMetadataWithRepairs(\n input: Parameters<\n typeof createRemoteContainerWithMetadataDocumentAttempt\n >[0] & {\n readonly parentContainerId: string;\n },\n): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n const { apiClient } = input.runtime;\n let parentProjection = input.parentProjection;\n const repairState = {\n didRepairStaleParent: false,\n policyRepairs: new PrincipalPolicyRepairBudget(),\n };\n for (;;) {\n const submitted = await createRemoteContainerWithMetadataDocumentAttempt({\n ...input,\n parentProjection,\n });\n if (!submitted) {\n return null;\n }\n if (submitted.ok) {\n return submitted.state;\n }\n const repair = await repairContainerCreateFailure({\n apiClient,\n failure: submitted,\n parentContainerId: input.parentContainerId,\n parentProjection,\n state: repairState,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n stillCurrent: input.stillCurrent,\n });\n if (repair.kind === \"retry\") {\n parentProjection = repair.parentProjection;\n continue;\n }\n if (repair.kind === \"unavailable\") return null;\n return settleTerminalCreateFailure(submitted, input.stillCurrent) ===\n \"committed\"\n ? CONTAINER_ALREADY_COMMITTED\n : null;\n }\n}\n\nexport async function createRemoteContainerWithMetadataDocument(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: ContainerWithMetadataPlanInput[\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n const author = resolveDocumentCreateAuthor(input.runtime);\n const { apiClient } = input.runtime;\n const parentSecretKey = input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !parentSecretKey) {\n input.runtime.util.log(\n \"Container contents: skipped container create because the writer context is unavailable.\",\n );\n return null;\n }\n\n const parentProjection =\n input.parentProjection ??\n (await apiClient.getContainerWriterProjection(input.parentContainerId));\n if (!parentProjection) {\n return null;\n }\n\n const containerEventId = crypto.randomUUID();\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerSignedAt = new Date().toISOString();\n const metadataContentKey = crypto.getRandomValues(new Uint8Array(32));\n const metadataEventId = crypto.randomUUID();\n const metadataSignedAt = new Date().toISOString();\n return createContainerWithMetadataWithRepairs({\n author,\n containerEventId,\n containerId: input.containerId,\n containerKey,\n containerSignedAt,\n metadataContentKey,\n metadataEventId,\n metadataSeedUpdate: input.metadataSeedUpdate,\n metadataSignedAt,\n parentContainerId: input.parentContainerId,\n parentProjection,\n parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n systemSlot: input.systemSlot,\n });\n}\n"]}
1
+ {"version":3,"file":"createWithMetadata.js","sourceRoot":"","sources":["createWithMetadata.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,qBAAqB,GACtB,MAAM,2CAA2C,CAAC;AAMnD,OAAO,EAAE,wCAAwC,EAAE,MAAM,4DAA4D,CAAC;AACtH,O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M,iBAAiB,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACnD,MAAM,kBAAkB,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACtE,MAAM,eAAe,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IAC5C,MAAM,gBAAgB,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAClD,OAAO,sCAAsC,CAAC;QAC5C,MAAM;QACN,gBAAgB;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY;QACZ,iBAAiB;QACjB,kBAAkB;QAClB,eAAe;QACf,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,gBAAgB;QAChB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,gBAAgB;QAChB,eAAe;QACf,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,UAAU,EAAE,KAAK,CAAC,UAAU;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport {\n type ContainerSystemSlot,\n isContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerCreateWithMetadataDocumentRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { locallyAcknowledgedContainerMutationHead } from \"../../../../data/containers/shared/mutationAcknowledgement\";\nimport { isContainerManifestAlreadyExistsConflict } from \"../../../../data/containers/shared/mutationFailures\";\nimport type { ContainerMutationSubmitFailure } from \"../../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../../data/documents/shared/projection\";\nimport {\n type AcknowledgedDocumentMutation,\n acknowledgedDocumentCreate,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { locallyAuthoredAccessManifestHead } from \"../../../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\nimport {\n type buildMaterializedContainerCreatePlan,\n signedContainerMetadataDocumentId,\n} from \"../../../containers\";\nimport { repairContainerCreateFailure } from \"../../../containers/child/create/createSubmission\";\nimport {\n type buildMaterializedDocumentCreatePlan,\n documentWriterProjectionFromCreateResponse,\n resolveDocumentCreateAuthor,\n} from \"../../../documents\";\nimport {\n buildDocumentCreateSeedRequest,\n documentCreateSeedFits,\n} from \"../../../documents/sync/initialSync\";\nimport { PrincipalPolicyRepairBudget } from \"../../../principals/policyRepairBudget\";\n\nimport type {\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n} from \"../types\";\nimport { settleTerminalCreateFailure } from \"./createTerminalFailure\";\nimport {\n buildContainerWithMetadataPlans,\n type ContainerWithMetadataPlanInput,\n} from \"./createWithMetadataPlan\";\n\n/**\n * Sentinel for a lost-response retry whose manifest already exists remotely.\n * Callers avoid a duplicate; the next parent hydration settles local state.\n */\nexport const CONTAINER_ALREADY_COMMITTED = Symbol(\"containerAlreadyCommitted\");\nexport type ContainerAlreadyCommitted = typeof CONTAINER_ALREADY_COMMITTED;\n\nasync function submitContainerWithMetadataDocument(input: {\n readonly organizationId: string;\n readonly request: ContainerCreateWithMetadataDocumentRequest;\n readonly runtime: ContainerWorkflowRuntime;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly ok: true;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n }\n | ContainerMutationSubmitFailure\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const result = await apiClient.createContainerWithMetadataDocumentResult(\n input.request,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n },\n );\n return result.ok ? { ok: true, response: result.data } : result;\n}\n\n/**\n * Seed the metadata document's writer projection from the create response so the\n * first read after the container is created (its own metadata sync, contents\n * hydration) resolves locally instead of a cold `GET writer-projection`. The\n * authorizing path is the child container projection the create was authored\n * against — locally built rather than server-fetched, so unlike the plain\n * document-create path this is gated on the projection's internal consistency;\n * on any mismatch the seed is skipped and the next read falls back to a fetch.\n */\nasync function seedMetadataDocumentWriterProjection(input: {\n readonly runtime: ContainerWorkflowRuntime;\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly metadataDocument: AcknowledgedDocumentMutation;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const projection = documentWriterProjectionFromCreateResponse({\n containerProjection: input.childProjection,\n response: input.metadataDocument,\n });\n try {\n await assertDocumentWriterProjectionConsistent(projection, {\n execSql: input.execSql,\n stillCurrent: input.stillCurrent,\n trustedLocalProjection: true,\n });\n } catch {\n return;\n }\n if (input.stillCurrent?.() === false) return;\n input.runtime.apiClient.primeDocumentWriterProjection(\n input.metadataDocument.id,\n projection,\n );\n}\n\nasync function acknowledgeContainerWithMetadata(input: {\n containerPlan: Parameters<\n typeof locallyAcknowledgedContainerMutationHead\n >[0][\"plan\"];\n execSql: ExecSql;\n metadataDocumentPlan: Parameters<typeof acknowledgedDocumentCreate>[0];\n response: ContainerCreateWithMetadataDocumentResponse;\n stillCurrent?: (() => boolean) | undefined;\n}) {\n const metadataDocument = acknowledgedDocumentCreate(\n input.metadataDocumentPlan,\n input.response.metadataDocument,\n );\n const containerHead = await locallyAcknowledgedContainerMutationHead({\n plan: input.containerPlan,\n response: input.response.container,\n });\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n heads: [\n containerHead,\n locallyAuthoredAccessManifestHead(input.metadataDocumentPlan),\n ],\n stillCurrent: input.stillCurrent,\n });\n return metadataDocument;\n}\n\n/**\n * Prime the new container's writer projection from the create plan the client\n * just authored, so the first write under it (a child folder, a document)\n * resolves locally instead of a cold `GET writer-projection`. Only primed when\n * the locally-built projection matches what the server created — the create\n * response echoes the container id and manifest head — so a mismatch skips the\n * seed and the next write falls back to a fetch (same fail-closed contract as\n * the metadata-document seed). Priming is safe for writes: the server still\n * validates every mutation, so a projection that later goes stale (rekey/share/\n * move evict it) just yields a rejected write that retries with a fresh fetch.\n */\nfunction seedChildContainerWriterProjection(input: {\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n readonly runtime: ContainerWorkflowRuntime;\n}): void {\n const createdManifestHash =\n input.response.container.manifestHead.manifestHash;\n const projectedManifestHash = input.childProjection.path.at(-1)?.manifestHash;\n // Both hashes must be present and equal, or two undefined hashes would compare\n // equal and prime an empty/invalid projection.\n if (\n !createdManifestHash ||\n !projectedManifestHash ||\n input.childProjection.containerId !==\n input.response.container.containerId ||\n projectedManifestHash !== createdManifestHash\n ) {\n return;\n }\n\n input.runtime.apiClient.primeContainerWriterProjection(\n input.response.container.containerId,\n input.childProjection,\n );\n}\n\n/**\n * The persisted slot is the one this client signed into the manifest state.\n * The acknowledgement already refused a response that echoed anything else,\n * so the server's column never chooses which local record becomes Trash.\n */\nfunction signedCreateSystemSlot(\n state: ContainerAccessManifestState,\n): ContainerSystemSlot | null {\n if (state.systemSlot === null) return null;\n if (!isContainerSystemSlot(state.systemSlot)) {\n throw new Error(\"Container create plan signed an invalid system slot\");\n }\n return state.systemSlot;\n}\n\n/** The seed the create committed, if the response accepted it. */\nfunction committedMetadataSeed(\n response: ContainerCreateWithMetadataDocumentResponse,\n seedUpdateId: string | undefined,\n): CreatedRemoteContainerState[\"metadataSeed\"] {\n const seed = response.metadataDocument.initialSync;\n return seedUpdateId && seed?.acceptedOutgoingUpdateIds.includes(seedUpdateId)\n ? { commitLsn: seed.commitLsn, updateId: seedUpdateId }\n : undefined;\n}\n\nasync function settleContainerWithMetadataCreate(input: {\n readonly childProjection: ContainerWriterProjectionResponse;\n readonly containerPlan: Awaited<\n ReturnType<typeof buildMaterializedContainerCreatePlan>\n >;\n readonly execSql: ExecSql;\n readonly metadataDocumentPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n readonly response: ContainerCreateWithMetadataDocumentResponse;\n readonly runtime: ContainerWorkflowRuntime;\n readonly seedUpdateId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<{\n readonly ok: true;\n readonly state: CreatedRemoteContainerState;\n} | null> {\n if (\n input.response.container.containerId !==\n input.containerPlan.plan.containerId\n ) {\n throw new Error(\"Container metadata create response container mismatch\");\n }\n // The acknowledgement echoed the signed parent, which a child always names.\n const parentId = input.containerPlan.plan.state.parentContainerId;\n if (parentId === null) {\n throw new Error(\"A container create must commit under a parent\");\n }\n // The acknowledgement carries no state: the metadata document is the one\n // this client signed into the container, matched by the manifest hash.\n const metadataDocumentId = signedContainerMetadataDocumentId(\n input.containerPlan.plan,\n );\n if (\n metadataDocumentId !== input.containerPlan.plan.metadataDocumentId ||\n input.response.metadataDocument.id !==\n input.metadataDocumentPlan.plan.documentId\n ) {\n throw new Error(\"Container metadata create response document mismatch\");\n }\n const metadataDocument = await acknowledgeContainerWithMetadata({\n containerPlan: input.containerPlan.plan,\n execSql: input.execSql,\n metadataDocumentPlan: input.metadataDocumentPlan.plan,\n response: input.response,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n await seedMetadataDocumentWriterProjection({\n childProjection: input.childProjection,\n execSql: input.execSql,\n metadataDocument,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n seedChildContainerWriterProjection({\n childProjection: input.childProjection,\n response: input.response,\n runtime: input.runtime,\n });\n const metadataSeed = committedMetadataSeed(\n input.response,\n input.seedUpdateId,\n );\n return {\n ok: true,\n state: {\n accessManifestHash: input.response.container.manifestHead.manifestHash,\n ...(metadataSeed ? { metadataSeed } : {}),\n systemSlot: signedCreateSystemSlot(input.containerPlan.plan.state),\n containerId: input.response.container.containerId,\n createdAt: input.response.container.createdAt,\n metadataDocumentId,\n organizationId: input.response.container.organizationId,\n parentId,\n persistedMetadataState:\n persistedDocumentStateFromAcknowledgement(metadataDocument),\n updatedAt: input.response.container.updatedAt,\n },\n };\n}\n\nasync function createRemoteContainerWithMetadataDocumentAttempt(\n input: ContainerWithMetadataPlanInput,\n): Promise<\n | {\n readonly ok: true;\n readonly state: CreatedRemoteContainerState;\n }\n | ContainerMutationSubmitFailure\n | null\n> {\n const execSql = input.runtime.infra.execSql;\n const plans = await buildContainerWithMetadataPlans(input);\n if (!plans) return null;\n const { containerPlan, childProjection, metadataDocumentPlan } = plans;\n const request = {\n systemSlot: input.systemSlot ?? null,\n container: containerPlan.plan.request,\n metadataDocument: metadataDocumentPlan.plan.request,\n };\n const submitRequest = (body: ContainerCreateWithMetadataDocumentRequest) =>\n submitContainerWithMetadataDocument({\n organizationId: containerPlan.plan.state.organizationId,\n request: body,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n const seed = input.metadataSeedUpdate\n ? await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: childProjection,\n materializedDocument: metadataDocumentPlan,\n pendingUpdate: input.metadataSeedUpdate,\n })\n : null;\n let submitted: Awaited<ReturnType<typeof submitRequest>> = null;\n if (seed && documentCreateSeedFits(seed)) {\n submitted = await submitRequest({ ...request, initialMetadataSync: seed });\n if (!submitted) return null;\n }\n // A seed only saves the first metadata sync: a refused seeded create falls\n // back to the plain create once, so the row syncs as before, and its failures\n // take the ordinary repair path. A lost response is adopted directly, as a\n // plain create's would be.\n const seeded = submitted?.ok === true;\n if (\n !submitted ||\n (!submitted.ok && !isContainerManifestAlreadyExistsConflict(submitted))\n ) {\n submitted = await submitRequest(request);\n }\n if (!submitted?.ok) {\n return submitted;\n }\n return settleContainerWithMetadataCreate({\n childProjection,\n containerPlan,\n execSql,\n metadataDocumentPlan,\n response: submitted.response,\n runtime: input.runtime,\n seedUpdateId: seeded ? input.metadataSeedUpdate?.id : undefined,\n stillCurrent: input.stillCurrent,\n });\n}\n\nasync function createContainerWithMetadataWithRepairs(\n input: Parameters<\n typeof createRemoteContainerWithMetadataDocumentAttempt\n >[0] & {\n readonly parentContainerId: string;\n },\n): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n const { apiClient } = input.runtime;\n let parentProjection = input.parentProjection;\n const repairState = {\n didRepairStaleParent: false,\n policyRepairs: new PrincipalPolicyRepairBudget(),\n };\n for (;;) {\n const submitted = await createRemoteContainerWithMetadataDocumentAttempt({\n ...input,\n parentProjection,\n });\n if (!submitted) {\n return null;\n }\n if (submitted.ok) {\n return submitted.state;\n }\n const repair = await repairContainerCreateFailure({\n apiClient,\n failure: submitted,\n parentContainerId: input.parentContainerId,\n parentProjection,\n state: repairState,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n stillCurrent: input.stillCurrent,\n });\n if (repair.kind === \"retry\") {\n parentProjection = repair.parentProjection;\n continue;\n }\n if (repair.kind === \"unavailable\") return null;\n return settleTerminalCreateFailure(submitted, input.stillCurrent) ===\n \"committed\"\n ? CONTAINER_ALREADY_COMMITTED\n : null;\n }\n}\n\nexport async function createRemoteContainerWithMetadataDocument(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: ContainerWithMetadataPlanInput[\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n const author = resolveDocumentCreateAuthor(input.runtime);\n const { apiClient } = input.runtime;\n const parentSecretKey = input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !parentSecretKey) {\n input.runtime.util.log(\n \"Container contents: skipped container create because the writer context is unavailable.\",\n );\n return null;\n }\n\n const parentProjection =\n input.parentProjection ??\n (await apiClient.getContainerWriterProjection(input.parentContainerId));\n if (!parentProjection) {\n return null;\n }\n\n const containerEventId = crypto.randomUUID();\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerSignedAt = new Date().toISOString();\n const metadataContentKey = crypto.getRandomValues(new Uint8Array(32));\n const metadataEventId = crypto.randomUUID();\n const metadataSignedAt = new Date().toISOString();\n return createContainerWithMetadataWithRepairs({\n author,\n containerEventId,\n containerId: input.containerId,\n containerKey,\n containerSignedAt,\n metadataContentKey,\n metadataEventId,\n metadataSeedUpdate: input.metadataSeedUpdate,\n metadataSignedAt,\n parentContainerId: input.parentContainerId,\n parentProjection,\n parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n systemSlot: input.systemSlot,\n });\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
2
  import { buildMaterializedContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, } from "../../../containers/index.js";
3
3
  import { buildMaterializedDocumentCreatePlan, } from "../../../documents/index.js";
4
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
5
4
  /** A folder's metadata document takes the folder's id, known before the create. */
6
5
  export function plannedContainerMetadataDocumentId(containerId) {
7
6
  return containerId;
@@ -23,7 +22,7 @@ async function buildPlans(input) {
23
22
  resolveProjectionUserKey: input.resolveProjectionUserKey,
24
23
  signedAt: input.containerSignedAt,
25
24
  stillCurrent: input.stillCurrent,
26
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
25
+ warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer(),
27
26
  });
28
27
  const childProjection = childContainerWriterProjectionFromCreatePlan({
29
28
  materializedPlan: containerPlan,
@@ -1 +1 @@
1
- {"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAE3H,OAAO,EACL,oCAAoC,EACpC,4CAA4C,GAC7C,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,mCAAmC,GAEpC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAsB7F,mFAAmF;AACnF,MAAM,UAAU,kCAAkC,CAChD,WAAmB;IAEnB,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,KAAqC;IAC7D,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C,8EAA8E;IAC9E,4EAA4E;IAC5E,MAAM,aAAa,GAAG,MAAM,oCAAoC,CAAC;QAC/D,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,OAAO;QACP,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,kBAAkB,EAAE,kCAAkC,CAAC,KAAK,CAAC,WAAW,CAAC;QACzE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,iBAAiB;QACjC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;KACF,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,4CAA4C,CAAC;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SAAS,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,CAAC,gBAAgB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACvE,IACE,gBAAgB,CAAC,WAAW,KAAK,QAAQ;QACzC,gBAAgB,CAAC,cAAc,KAAK,KAAK,CAAC,gBAAgB,CAAC,cAAc,EACzE,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0EAA0E,CAC3E,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PendingUpdateRecord } from \"../../../../data/persistence/documents/records\";\nimport {\n buildMaterializedContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../../../containers\";\nimport {\n buildMaterializedDocumentCreatePlan,\n type resolveDocumentCreateAuthor,\n} from \"../../../documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\nexport interface ContainerWithMetadataPlanInput {\n readonly author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n readonly containerEventId: string;\n readonly containerId: string;\n readonly containerKey: Uint8Array;\n readonly containerSignedAt: string;\n readonly metadataContentKey: Uint8Array;\n readonly metadataEventId: string;\n /** The queued update holding the metadata document's whole content. */\n readonly metadataSeedUpdate?: PendingUpdateRecord | undefined;\n readonly metadataSignedAt: string;\n readonly parentProjection: ContainerWriterProjectionResponse;\n readonly parentSecretKey: Uint8Array;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: ContainerWorkflowRuntime;\n readonly systemSlot?: ContainerSystemSlot | null | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/** A folder's metadata document takes the folder's id, known before the create. */\nexport function plannedContainerMetadataDocumentId(\n containerId: string,\n): string {\n return containerId;\n}\n\nasync function buildPlans(input: ContainerWithMetadataPlanInput) {\n const execSql = input.runtime.infra.execSql;\n // Rebuild parent- and policy-dependent hashes, signatures, and wraps on every\n // attempt while retaining the logical mutation identities and key material.\n const containerPlan = await buildMaterializedContainerCreatePlan({\n author: input.author,\n containerId: input.containerId,\n containerKey: input.containerKey,\n execSql,\n eventId: input.containerEventId,\n metadataDocumentId: plannedContainerMetadataDocumentId(input.containerId),\n systemSlot: input.systemSlot,\n parentProjection: input.parentProjection,\n parentSecretKey: input.parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.containerSignedAt,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n const childProjection = childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.parentProjection,\n });\n const metadataDocumentPlan = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: childProjection,\n contentKey: input.metadataContentKey,\n documentId: containerPlan.plan.metadataDocumentId,\n eventId: input.metadataEventId,\n execSql,\n knownContainerKeks: new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]),\n signedAt: input.metadataSignedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.parentSecretKey,\n trustedLocalProjection: true,\n });\n return { containerPlan, childProjection, metadataDocumentPlan };\n}\n\n/** Refresh stale history evidence once, strictly before submitting the write. */\nexport async function buildContainerWithMetadataPlans(\n input: ContainerWithMetadataPlanInput,\n) {\n try {\n return await buildPlans(input);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const parentId = input.parentProjection.containerId;\n apiClient.evictContainerWriterProjection(parentId);\n const parentProjection =\n await apiClient.getContainerWriterProjection(parentId);\n if (!parentProjection || input.stillCurrent?.() === false) return null;\n if (\n parentProjection.containerId !== parentId ||\n parentProjection.organizationId !== input.parentProjection.organizationId\n ) {\n throw new Error(\n \"Refreshed parent projection belongs to another container or organization\",\n );\n }\n return buildPlans({ ...input, parentProjection });\n}\n"]}
1
+ {"version":3,"file":"createWithMetadataPlan.js","sourceRoot":"","sources":["createWithMetadataPlan.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAE3H,OAAO,EACL,oCAAoC,EACpC,4CAA4C,GAC7C,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,mCAAmC,GAEpC,MAAM,oBAAoB,CAAC;AAuB5B,mFAAmF;AACnF,MAAM,UAAU,kCAAkC,CAChD,WAAmB;IAEnB,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,KAAqC;IAC7D,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;IAC5C,8EAA8E;IAC9E,4EAA4E;IAC5E,MAAM,aAAa,GAAG,MAAM,oCAAoC,CAAC;QAC/D,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,OAAO;QACP,OAAO,EAAE,KAAK,CAAC,gBAAgB;QAC/B,kBAAkB,EAAE,kCAAkC,CAAC,KAAK,CAAC,WAAW,CAAC;QACzE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,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SAAS,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IACpC,MAAM,QAAQ,GAAG,KAAK,CAAC,gBAAgB,CAAC,WAAW,CAAC;IACpD,SAAS,CAAC,8BAA8B,CAAC,QAAQ,CAAC,CAAC;IACnD,MAAM,gBAAgB,GACpB,MAAM,SAAS,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,CAAC,gBAAgB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACvE,IACE,gBAAgB,CAAC,WAAW,KAAK,QAAQ;QACzC,gBAAgB,CAAC,cAAc,KAAK,KAAK,CAAC,gBAAgB,CAAC,cAAc,EACzE,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0EAA0E,CAC3E,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,gBAAgB,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PendingUpdateRecord } from \"../../../../data/persistence/documents/records\";\nimport {\n buildMaterializedContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n} from \"../../../containers\";\nimport {\n buildMaterializedDocumentCreatePlan,\n type resolveDocumentCreateAuthor,\n} from \"../../../documents\";\n\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\nexport interface ContainerWithMetadataPlanInput {\n readonly author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n readonly containerEventId: string;\n readonly containerId: string;\n readonly containerKey: Uint8Array;\n readonly containerSignedAt: string;\n readonly metadataContentKey: Uint8Array;\n readonly metadataEventId: string;\n /** The queued update holding the metadata document's whole content. */\n readonly metadataSeedUpdate?: PendingUpdateRecord | undefined;\n readonly metadataSignedAt: string;\n readonly parentProjection: ContainerWriterProjectionResponse;\n readonly parentSecretKey: Uint8Array;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly runtime: ContainerWorkflowRuntime;\n readonly systemSlot?: ContainerSystemSlot | null | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/** A folder's metadata document takes the folder's id, known before the create. */\nexport function plannedContainerMetadataDocumentId(\n containerId: string,\n): string {\n return containerId;\n}\n\nasync function buildPlans(input: ContainerWithMetadataPlanInput) {\n const execSql = input.runtime.infra.execSql;\n // Rebuild parent- and policy-dependent hashes, signatures, and wraps on every\n // attempt while retaining the logical mutation identities and key material.\n const containerPlan = await buildMaterializedContainerCreatePlan({\n author: input.author,\n containerId: input.containerId,\n containerKey: input.containerKey,\n execSql,\n eventId: input.containerEventId,\n metadataDocumentId: plannedContainerMetadataDocumentId(input.containerId),\n systemSlot: input.systemSlot,\n parentProjection: input.parentProjection,\n parentSecretKey: input.parentSecretKey,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.containerSignedAt,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n const childProjection = childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.parentProjection,\n });\n const metadataDocumentPlan = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: childProjection,\n contentKey: input.metadataContentKey,\n documentId: containerPlan.plan.metadataDocumentId,\n eventId: input.metadataEventId,\n execSql,\n knownContainerKeks: new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]),\n signedAt: input.metadataSignedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.parentSecretKey,\n trustedLocalProjection: true,\n });\n return { containerPlan, childProjection, metadataDocumentPlan };\n}\n\n/** Refresh stale history evidence once, strictly before submitting the write. */\nexport async function buildContainerWithMetadataPlans(\n input: ContainerWithMetadataPlanInput,\n) {\n try {\n return await buildPlans(input);\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n }\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input.runtime;\n const parentId = input.parentProjection.containerId;\n apiClient.evictContainerWriterProjection(parentId);\n const parentProjection =\n await apiClient.getContainerWriterProjection(parentId);\n if (!parentProjection || input.stillCurrent?.() === false) return null;\n if (\n parentProjection.containerId !== parentId ||\n parentProjection.organizationId !== input.parentProjection.organizationId\n ) {\n throw new Error(\n \"Refreshed parent projection belongs to another container or organization\",\n );\n }\n return buildPlans({ ...input, parentProjection });\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { ContainerPathTooDeepError } from "../../../../data/containers/shared/containerPathLimits.js";
2
2
  import { reportAndRethrowKeyingVerificationError } from "../../../../data/keyingProjectionVerification/error.js";
3
3
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
4
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
5
4
  import { createDetachedContainerMetadataState, installDetachedContainerMetadataState, } from "../../metadata/metadataStateIsolation.js";
6
5
  import { hasRemoteContainerMetadataState } from "../../remoteHydration/reconciliation.js";
7
6
  import { moveRemoteContainer } from "../remote.js";
@@ -57,7 +56,7 @@ export async function persistAcceptedMoveIntent(input) {
57
56
  if (!containerState) {
58
57
  return false;
59
58
  }
60
- await createRuntimePrincipalPolicyWarmer(state.runtime)({
59
+ await state.runtime.principalPolicies.createWarmer()({
61
60
  organizationId: moved.organizationId,
62
61
  references: moved.metadataReferencedPrincipals,
63
62
  stillCurrent: input.isCurrent,
@@ -1 +1 @@
1
- {"version":3,"file":"moveIntentSync.js","sourceRoot":"","sources":["moveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;A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K,CAAC,OAAO,CAAC;IAC5C,MAAM,cAAc,GAClB,MAAM,KAAK,CAAC,WAAW,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,OAAO,CAAC,CAAC;IACX,CAAC;IACD,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,KAAK,MAAM,MAAM,IAAI,cAAc,EAAE,CAAC;QACpC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,OAAO,UAAU,CAAC;QACpB,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,iCAAiC,CAAC;YACrD,IAAI;YACJ,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM;YACN,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;YAC9D,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,KAAK;SACN,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;YAC3B,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,UAAU,IAAI,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACN,mEAAmE;YACnE,8BAA8B;YAC9B,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { ContainerPathTooDeepError } from \"../../../../data/containers/shared/containerPathLimits\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../metadata/metadataStateIsolation\";\nimport type { ContainerState, RemoteContainer } from \"../../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../../remoteHydration/reconciliation\";\nimport { moveRemoteContainer } from \"../remote\";\nimport type {\n AcceptedMoveRetry,\n ContainerMoveIntentSyncHost,\n ContainerMoveIntentSyncInput,\n ContainerMoveIntentSyncState,\n} from \"../types\";\nimport {\n appliedRemoteContainer,\n leaveAcceptedMoveQueued,\n STALE_ACCEPTED_MOVE,\n unacknowledgedAcceptedMove,\n unpersistedAcceptedMove,\n} from \"./acceptedMoveSettlement\";\n\ntype MoveIntentSyncResult = \"abandoned\" | \"blocked\" | \"failed\" | \"moved\";\n\nfunction currentMoveResult<\n Result extends Exclude<MoveIntentSyncResult, \"abandoned\">,\n>(isCurrent: () => boolean, result: Result): \"abandoned\" | Result {\n return isCurrent() ? result : \"abandoned\";\n}\n\nasync function recordPendingMoveIntentError(input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n isCurrent: () => boolean;\n message: string;\n state: ContainerMoveIntentSyncState;\n}): Promise<boolean> {\n if (!input.isCurrent()) {\n return false;\n }\n const execSql = input.state.runtime.infra.execSql;\n await input.state.persistence.recordMoveIntentError(execSql, {\n blocked: input.blocked,\n containerId: input.containerId,\n expectedIntentId: input.expectedIntentId,\n expectedUpdatedAt: input.expectedUpdatedAt,\n message: input.message,\n stillCurrent: input.isCurrent,\n });\n return input.isCurrent();\n}\n\nasync function resolveMoveIntentLocalUpdatedAt(input: {\n containerId: string;\n isCurrent: () => boolean;\n remoteUpdatedAt: string;\n state: ContainerMoveIntentSyncState;\n}): Promise<string | null> {\n if (!input.isCurrent()) {\n return null;\n }\n const previousLocalUpdatedAt =\n input.state.containersById.get(input.containerId)?.container\n .localUpdatedAt ?? null;\n if (\n !previousLocalUpdatedAt ||\n previousLocalUpdatedAt.localeCompare(input.remoteUpdatedAt) <= 0\n ) {\n return input.remoteUpdatedAt;\n }\n\n const execSql = input.state.runtime.infra.execSql;\n const containersWithPendingMetadataUpdates =\n await input.state.persistence.listContainerIdsWithPendingUpdates(execSql, [\n input.containerId,\n ]);\n if (!input.isCurrent()) {\n return null;\n }\n\n return containersWithPendingMetadataUpdates.includes(input.containerId)\n ? previousLocalUpdatedAt\n : input.remoteUpdatedAt;\n}\n\nexport async function persistAcceptedMoveIntent(input: {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n intent: ContainerMoveIntentSyncInput[\"intent\"];\n moved: RemoteContainer;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const abandon = () => {\n input.requestRemoteReconciliation(moved.parentId);\n return false;\n };\n if (!input.isCurrent()) return abandon();\n const containerState = state.containersById.get(intent.containerId);\n if (!containerState) {\n return false;\n }\n\n await createRuntimePrincipalPolicyWarmer(state.runtime)({\n organizationId: moved.organizationId,\n references: moved.metadataReferencedPrincipals,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n return abandon();\n }\n const localUpdatedAt = await resolveMoveIntentLocalUpdatedAt({\n containerId: intent.containerId,\n isCurrent: input.isCurrent,\n remoteUpdatedAt: moved.updatedAt,\n state,\n });\n if (!input.isCurrent() || localUpdatedAt === null) {\n return abandon();\n }\n const persistenceCandidate =\n await createDetachedContainerMetadataState(containerState);\n if (!input.isCurrent()) {\n return abandon();\n }\n persistenceCandidate.container = {\n ...persistenceCandidate.container,\n createdAt: moved.createdAt,\n serverCreatedAt: moved.createdAt,\n serverUpdatedAt: moved.updatedAt,\n updatedAt: moved.updatedAt,\n };\n const persistenceResult = await host.persistContainerState(\n persistenceCandidate,\n {\n accessEpoch: moved.metadataAccessEpoch,\n accessStateHash: moved.metadataAccessStateHash,\n documentId: moved.metadataDocumentId,\n metadataDocumentId: moved.metadataDocumentId,\n organizationId: moved.organizationId,\n parentId: moved.parentId,\n systemSlot: moved.systemSlot ?? null,\n },\n false,\n {\n localUpdatedAt,\n serverTimestamps: {\n createdAt: moved.createdAt,\n updatedAt: moved.updatedAt,\n },\n },\n {\n expectedStateWhenMissing: containerState,\n isCurrent: input.isCurrent,\n moveIntentSettlement: {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n },\n },\n );\n if (!input.isCurrent() || persistenceResult.status !== \"persisted\") {\n return abandon();\n }\n if (persistenceResult.moveIntentSettled !== true) {\n throw new Error(\n \"Container move persistence must settle the intent atomically\",\n );\n }\n if (!input.isCurrent()) return abandon();\n const { record: nextRecord } = persistenceResult;\n installDetachedContainerMetadataState(containerState, persistenceCandidate, {\n candidateRecord: nextRecord,\n preserveConcurrentMetadataEdit: true,\n });\n containerState.container = {\n ...containerState.container,\n metadataDocumentId: moved.metadataDocumentId,\n organizationId: moved.organizationId,\n parentId: moved.parentId,\n };\n return true;\n}\n\n/**\n * A move refused for path length never succeeds; the queue-time check saw only\n * the descendants this device holds. Drop the queued move and restore the\n * previous parent together: the server row never changed, so no listing would\n * ever put the folder back.\n */\nasync function abandonTooDeepMove(\n syncInput: ContainerMoveIntentSyncInput,\n): Promise<MoveIntentSyncResult> {\n const { host, intent, state } = syncInput;\n const previousParentId = intent.previousParentContainerId;\n if (previousParentId === null) {\n throw new Error(\"A queued container move must name its previous parent\");\n }\n const abandoned = await state.persistence.abandonMoveIntentRevision(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n previousParentContainerId: previousParentId,\n stillCurrent: syncInput.isCurrent,\n },\n );\n if (!syncInput.isCurrent()) return \"abandoned\";\n // A newer local move superseded this revision; it replays on its own.\n if (!abandoned) return \"failed\";\n const containerState = state.containersById.get(intent.containerId);\n if (containerState) {\n containerState.container = {\n ...containerState.container,\n parentId: previousParentId,\n };\n }\n host.updateSnapshot();\n state.runtime.util.log(\n `Container contents: abandoned queued move of ${intent.containerId}; its path would exceed the maximum depth`,\n );\n return \"failed\";\n}\n\n/** A replay that threw: refused for depth, tampered, or left unsettled. */\nasync function failedMoveReplay(input: {\n abandonAppliedMove: () => \"abandoned\";\n error: unknown;\n parentState: ContainerState;\n remoteMoveApplied: boolean;\n syncInput: ContainerMoveIntentSyncInput;\n}): Promise<MoveIntentSyncResult> {\n const {\n abandonAppliedMove,\n error,\n parentState,\n remoteMoveApplied,\n syncInput,\n } = input;\n const { intent, state } = syncInput;\n if (!syncInput.isCurrent()) {\n return abandonAppliedMove();\n }\n if (error instanceof ContainerPathTooDeepError)\n return abandonTooDeepMove(syncInput);\n // Even a refused acknowledgement leaves the move on the server; its replay\n // verifies the head again before settling.\n if (remoteMoveApplied && error instanceof Error)\n leaveAcceptedMoveQueued(\n syncInput,\n \"Container contents: an accepted container move failed to settle\",\n error,\n );\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.move.replay\",\n organizationId: parentState.container.organizationId,\n },\n );\n if (!syncInput.isCurrent()) {\n return abandonAppliedMove();\n }\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: syncInput.isCurrent,\n message: `Failed to sync container move: ${errorMessage(error)}`,\n state,\n });\n return currentMoveResult(syncInput.isCurrent, \"failed\");\n}\n\nasync function movePendingRemoteContainer(input: {\n containerState: ContainerState;\n parentState: ContainerState;\n syncInput: ContainerMoveIntentSyncInput;\n}): Promise<MoveIntentSyncResult> {\n const { containerState, parentState, syncInput } = input;\n const { host, intent, state } = syncInput;\n let remoteMoveApplied = false;\n let remoteParentId: string | null = intent.parentContainerId;\n const abandonAppliedMove = () => {\n if (remoteMoveApplied) {\n leaveAcceptedMoveQueued(\n syncInput,\n STALE_ACCEPTED_MOVE,\n new Error(\"Stale pass dropped an accepted container move\"),\n );\n syncInput.requestRemoteReconciliation(remoteParentId);\n }\n return \"abandoned\" as const;\n };\n try {\n const replayed = await moveRemoteContainer({\n containerId: intent.containerId,\n onAccepted: () => {\n remoteMoveApplied = true;\n },\n parentContainerId: intent.parentContainerId,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n stillCurrent: syncInput.isCurrent,\n });\n if (!replayed) {\n if (!syncInput.isCurrent()) {\n if (!remoteMoveApplied)\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return abandonAppliedMove();\n }\n if (remoteMoveApplied) return unacknowledgedAcceptedMove(syncInput);\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: syncInput.isCurrent,\n message: \"Remote container move was rejected or unavailable\",\n state,\n });\n return currentMoveResult(syncInput.isCurrent, \"failed\");\n }\n remoteMoveApplied = true;\n const moved =\n \"applied\" in replayed\n ? appliedRemoteContainer(containerState, replayed.applied)\n : replayed.moved;\n remoteParentId = moved.parentId;\n if (!syncInput.isCurrent()) return abandonAppliedMove();\n\n const persisted = await persistAcceptedMoveIntent({\n host,\n isCurrent: syncInput.isCurrent,\n intent,\n moved,\n requestRemoteReconciliation: syncInput.requestRemoteReconciliation,\n state,\n });\n if (!persisted) return unpersistedAcceptedMove(syncInput);\n state.runtime.util.log(\n \"applied\" in replayed\n ? `Container contents: settled queued container move ${intent.containerId} the server already held`\n : `Container contents: synced queued container move ${intent.containerId}`,\n );\n return \"moved\";\n } catch (error: unknown) {\n return failedMoveReplay({\n abandonAppliedMove,\n error,\n parentState,\n remoteMoveApplied,\n syncInput,\n });\n }\n}\n\nasync function trySyncPendingContainerMoveIntent(\n input: ContainerMoveIntentSyncInput,\n): Promise<MoveIntentSyncResult> {\n const { intent, state } = input;\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n const containerState = state.containersById.get(intent.containerId);\n const parentState = state.containersById.get(intent.parentContainerId);\n\n if (!containerState) {\n await recordPendingMoveIntentError({\n blocked: true,\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move intent references a missing local container\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"failed\");\n }\n if (!parentState) {\n await recordPendingMoveIntentError({\n blocked: true,\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Container move intent references a missing destination parent container\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"failed\");\n }\n if (input.isRemoteSyncBlocked(containerState.container.organizationId)) {\n return \"blocked\";\n }\n if (\n !hasRemoteContainerMetadataState(containerState) ||\n input.isCreatePending(intent.containerId)\n ) {\n // Source not synced yet is TRANSIENT, exactly like the destination case\n // below: the source's own create intent syncs first (createIntentSync runs\n // before moveIntentSync in a pass), but if that create fails on this pass\n // the source still lacks remote metadata here. Keep the intent 'pending'\n // (not 'blocked') so the queue reports a retryable failure rather than a\n // missing-dependency block; either way listUnsyncedMoveIntents replays it\n // once the create lands.\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move source is not synced yet\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"blocked\");\n }\n if (\n !hasRemoteContainerMetadataState(parentState) ||\n input.isCreatePending(intent.parentContainerId)\n ) {\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move destination parent is not synced yet\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"blocked\");\n }\n\n return movePendingRemoteContainer({\n containerState,\n parentState,\n syncInput: input,\n });\n}\n\nexport async function syncPendingContainerMoveIntents(input: {\n host: ContainerMoveIntentSyncHost;\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) {\n return 0;\n }\n const { host } = input;\n const state = { ...input.state };\n const execSql = state.runtime.infra.execSql;\n const pendingIntents =\n await state.persistence.listUnsyncedMoveIntents(execSql);\n if (!input.isCurrent()) {\n return 0;\n }\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) {\n return movedCount;\n }\n const result = await trySyncPendingContainerMoveIntent({\n host,\n isCurrent: input.isCurrent,\n isCreatePending: input.isCreatePending,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n requestRemoteReconciliation: input.requestRemoteReconciliation,\n acceptedMoveRetry: input.acceptedMoveRetry,\n state,\n });\n if (result === \"abandoned\") {\n return movedCount;\n }\n\n if (result === \"moved\") {\n movedCount += 1;\n } else {\n // A replay that failed before reaching the server keeps an earlier\n // acceptance's retries going.\n input.acceptedMoveRetry.resume(intent.id);\n }\n }\n\n return movedCount;\n}\n"]}
1
+ {"version":3,"file":"moveIntentSync.js","sourceRoot":"","sources":["moveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,wDAAwD,CAAC;AACnG,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AAEpE,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAOhD,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,GACxB,MAAM,0BAA0B,CAAC;AAIlC,SAAS,iBAAiB,CAExB,SA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AiC,CAAC;YACrD,IAAI;YACJ,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM;YACN,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;YAC9D,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,KAAK;SACN,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;YAC3B,OAAO,UAAU,CAAC;QACpB,CAAC;QAED,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,UAAU,IAAI,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACN,mEAAmE;YACnE,8BAA8B;YAC9B,KAAK,CAAC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { ContainerPathTooDeepError } from \"../../../../data/containers/shared/containerPathLimits\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../../data/keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../../data/shared/errorMessage\";\n\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"../../metadata/metadataStateIsolation\";\nimport type { ContainerState, RemoteContainer } from \"../../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../../remoteHydration/reconciliation\";\nimport { moveRemoteContainer } from \"../remote\";\nimport type {\n AcceptedMoveRetry,\n ContainerMoveIntentSyncHost,\n ContainerMoveIntentSyncInput,\n ContainerMoveIntentSyncState,\n} from \"../types\";\nimport {\n appliedRemoteContainer,\n leaveAcceptedMoveQueued,\n STALE_ACCEPTED_MOVE,\n unacknowledgedAcceptedMove,\n unpersistedAcceptedMove,\n} from \"./acceptedMoveSettlement\";\n\ntype MoveIntentSyncResult = \"abandoned\" | \"blocked\" | \"failed\" | \"moved\";\n\nfunction currentMoveResult<\n Result extends Exclude<MoveIntentSyncResult, \"abandoned\">,\n>(isCurrent: () => boolean, result: Result): \"abandoned\" | Result {\n return isCurrent() ? result : \"abandoned\";\n}\n\nasync function recordPendingMoveIntentError(input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n isCurrent: () => boolean;\n message: string;\n state: ContainerMoveIntentSyncState;\n}): Promise<boolean> {\n if (!input.isCurrent()) {\n return false;\n }\n const execSql = input.state.runtime.infra.execSql;\n await input.state.persistence.recordMoveIntentError(execSql, {\n blocked: input.blocked,\n containerId: input.containerId,\n expectedIntentId: input.expectedIntentId,\n expectedUpdatedAt: input.expectedUpdatedAt,\n message: input.message,\n stillCurrent: input.isCurrent,\n });\n return input.isCurrent();\n}\n\nasync function resolveMoveIntentLocalUpdatedAt(input: {\n containerId: string;\n isCurrent: () => boolean;\n remoteUpdatedAt: string;\n state: ContainerMoveIntentSyncState;\n}): Promise<string | null> {\n if (!input.isCurrent()) {\n return null;\n }\n const previousLocalUpdatedAt =\n input.state.containersById.get(input.containerId)?.container\n .localUpdatedAt ?? null;\n if (\n !previousLocalUpdatedAt ||\n previousLocalUpdatedAt.localeCompare(input.remoteUpdatedAt) <= 0\n ) {\n return input.remoteUpdatedAt;\n }\n\n const execSql = input.state.runtime.infra.execSql;\n const containersWithPendingMetadataUpdates =\n await input.state.persistence.listContainerIdsWithPendingUpdates(execSql, [\n input.containerId,\n ]);\n if (!input.isCurrent()) {\n return null;\n }\n\n return containersWithPendingMetadataUpdates.includes(input.containerId)\n ? previousLocalUpdatedAt\n : input.remoteUpdatedAt;\n}\n\nexport async function persistAcceptedMoveIntent(input: {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n intent: ContainerMoveIntentSyncInput[\"intent\"];\n moved: RemoteContainer;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const abandon = () => {\n input.requestRemoteReconciliation(moved.parentId);\n return false;\n };\n if (!input.isCurrent()) return abandon();\n const containerState = state.containersById.get(intent.containerId);\n if (!containerState) {\n return false;\n }\n\n await state.runtime.principalPolicies.createWarmer()({\n organizationId: moved.organizationId,\n references: moved.metadataReferencedPrincipals,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n return abandon();\n }\n const localUpdatedAt = await resolveMoveIntentLocalUpdatedAt({\n containerId: intent.containerId,\n isCurrent: input.isCurrent,\n remoteUpdatedAt: moved.updatedAt,\n state,\n });\n if (!input.isCurrent() || localUpdatedAt === null) {\n return abandon();\n }\n const persistenceCandidate =\n await createDetachedContainerMetadataState(containerState);\n if (!input.isCurrent()) {\n return abandon();\n }\n persistenceCandidate.container = {\n ...persistenceCandidate.container,\n createdAt: moved.createdAt,\n serverCreatedAt: moved.createdAt,\n serverUpdatedAt: moved.updatedAt,\n updatedAt: moved.updatedAt,\n };\n const persistenceResult = await host.persistContainerState(\n persistenceCandidate,\n {\n accessEpoch: moved.metadataAccessEpoch,\n accessStateHash: moved.metadataAccessStateHash,\n documentId: moved.metadataDocumentId,\n metadataDocumentId: moved.metadataDocumentId,\n organizationId: moved.organizationId,\n parentId: moved.parentId,\n systemSlot: moved.systemSlot ?? null,\n },\n false,\n {\n localUpdatedAt,\n serverTimestamps: {\n createdAt: moved.createdAt,\n updatedAt: moved.updatedAt,\n },\n },\n {\n expectedStateWhenMissing: containerState,\n isCurrent: input.isCurrent,\n moveIntentSettlement: {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n },\n },\n );\n if (!input.isCurrent() || persistenceResult.status !== \"persisted\") {\n return abandon();\n }\n if (persistenceResult.moveIntentSettled !== true) {\n throw new Error(\n \"Container move persistence must settle the intent atomically\",\n );\n }\n if (!input.isCurrent()) return abandon();\n const { record: nextRecord } = persistenceResult;\n installDetachedContainerMetadataState(containerState, persistenceCandidate, {\n candidateRecord: nextRecord,\n preserveConcurrentMetadataEdit: true,\n });\n containerState.container = {\n ...containerState.container,\n metadataDocumentId: moved.metadataDocumentId,\n organizationId: moved.organizationId,\n parentId: moved.parentId,\n };\n return true;\n}\n\n/**\n * A move refused for path length never succeeds; the queue-time check saw only\n * the descendants this device holds. Drop the queued move and restore the\n * previous parent together: the server row never changed, so no listing would\n * ever put the folder back.\n */\nasync function abandonTooDeepMove(\n syncInput: ContainerMoveIntentSyncInput,\n): Promise<MoveIntentSyncResult> {\n const { host, intent, state } = syncInput;\n const previousParentId = intent.previousParentContainerId;\n if (previousParentId === null) {\n throw new Error(\"A queued container move must name its previous parent\");\n }\n const abandoned = await state.persistence.abandonMoveIntentRevision(\n state.runtime.infra.execSql,\n {\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n previousParentContainerId: previousParentId,\n stillCurrent: syncInput.isCurrent,\n },\n );\n if (!syncInput.isCurrent()) return \"abandoned\";\n // A newer local move superseded this revision; it replays on its own.\n if (!abandoned) return \"failed\";\n const containerState = state.containersById.get(intent.containerId);\n if (containerState) {\n containerState.container = {\n ...containerState.container,\n parentId: previousParentId,\n };\n }\n host.updateSnapshot();\n state.runtime.util.log(\n `Container contents: abandoned queued move of ${intent.containerId}; its path would exceed the maximum depth`,\n );\n return \"failed\";\n}\n\n/** A replay that threw: refused for depth, tampered, or left unsettled. */\nasync function failedMoveReplay(input: {\n abandonAppliedMove: () => \"abandoned\";\n error: unknown;\n parentState: ContainerState;\n remoteMoveApplied: boolean;\n syncInput: ContainerMoveIntentSyncInput;\n}): Promise<MoveIntentSyncResult> {\n const {\n abandonAppliedMove,\n error,\n parentState,\n remoteMoveApplied,\n syncInput,\n } = input;\n const { intent, state } = syncInput;\n if (!syncInput.isCurrent()) {\n return abandonAppliedMove();\n }\n if (error instanceof ContainerPathTooDeepError)\n return abandonTooDeepMove(syncInput);\n // Even a refused acknowledgement leaves the move on the server; its replay\n // verifies the head again before settling.\n if (remoteMoveApplied && error instanceof Error)\n leaveAcceptedMoveQueued(\n syncInput,\n \"Container contents: an accepted container move failed to settle\",\n error,\n );\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.containerId,\n objectKind: \"container\",\n operation: \"container.move.replay\",\n organizationId: parentState.container.organizationId,\n },\n );\n if (!syncInput.isCurrent()) {\n return abandonAppliedMove();\n }\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: syncInput.isCurrent,\n message: `Failed to sync container move: ${errorMessage(error)}`,\n state,\n });\n return currentMoveResult(syncInput.isCurrent, \"failed\");\n}\n\nasync function movePendingRemoteContainer(input: {\n containerState: ContainerState;\n parentState: ContainerState;\n syncInput: ContainerMoveIntentSyncInput;\n}): Promise<MoveIntentSyncResult> {\n const { containerState, parentState, syncInput } = input;\n const { host, intent, state } = syncInput;\n let remoteMoveApplied = false;\n let remoteParentId: string | null = intent.parentContainerId;\n const abandonAppliedMove = () => {\n if (remoteMoveApplied) {\n leaveAcceptedMoveQueued(\n syncInput,\n STALE_ACCEPTED_MOVE,\n new Error(\"Stale pass dropped an accepted container move\"),\n );\n syncInput.requestRemoteReconciliation(remoteParentId);\n }\n return \"abandoned\" as const;\n };\n try {\n const replayed = await moveRemoteContainer({\n containerId: intent.containerId,\n onAccepted: () => {\n remoteMoveApplied = true;\n },\n parentContainerId: intent.parentContainerId,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n stillCurrent: syncInput.isCurrent,\n });\n if (!replayed) {\n if (!syncInput.isCurrent()) {\n if (!remoteMoveApplied)\n syncInput.requestRemoteReconciliation(intent.parentContainerId);\n return abandonAppliedMove();\n }\n if (remoteMoveApplied) return unacknowledgedAcceptedMove(syncInput);\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: syncInput.isCurrent,\n message: \"Remote container move was rejected or unavailable\",\n state,\n });\n return currentMoveResult(syncInput.isCurrent, \"failed\");\n }\n remoteMoveApplied = true;\n const moved =\n \"applied\" in replayed\n ? appliedRemoteContainer(containerState, replayed.applied)\n : replayed.moved;\n remoteParentId = moved.parentId;\n if (!syncInput.isCurrent()) return abandonAppliedMove();\n\n const persisted = await persistAcceptedMoveIntent({\n host,\n isCurrent: syncInput.isCurrent,\n intent,\n moved,\n requestRemoteReconciliation: syncInput.requestRemoteReconciliation,\n state,\n });\n if (!persisted) return unpersistedAcceptedMove(syncInput);\n state.runtime.util.log(\n \"applied\" in replayed\n ? `Container contents: settled queued container move ${intent.containerId} the server already held`\n : `Container contents: synced queued container move ${intent.containerId}`,\n );\n return \"moved\";\n } catch (error: unknown) {\n return failedMoveReplay({\n abandonAppliedMove,\n error,\n parentState,\n remoteMoveApplied,\n syncInput,\n });\n }\n}\n\nasync function trySyncPendingContainerMoveIntent(\n input: ContainerMoveIntentSyncInput,\n): Promise<MoveIntentSyncResult> {\n const { intent, state } = input;\n if (!input.isCurrent()) {\n return \"abandoned\";\n }\n const containerState = state.containersById.get(intent.containerId);\n const parentState = state.containersById.get(intent.parentContainerId);\n\n if (!containerState) {\n await recordPendingMoveIntentError({\n blocked: true,\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move intent references a missing local container\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"failed\");\n }\n if (!parentState) {\n await recordPendingMoveIntentError({\n blocked: true,\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Container move intent references a missing destination parent container\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"failed\");\n }\n if (input.isRemoteSyncBlocked(containerState.container.organizationId)) {\n return \"blocked\";\n }\n if (\n !hasRemoteContainerMetadataState(containerState) ||\n input.isCreatePending(intent.containerId)\n ) {\n // Source not synced yet is TRANSIENT, exactly like the destination case\n // below: the source's own create intent syncs first (createIntentSync runs\n // before moveIntentSync in a pass), but if that create fails on this pass\n // the source still lacks remote metadata here. Keep the intent 'pending'\n // (not 'blocked') so the queue reports a retryable failure rather than a\n // missing-dependency block; either way listUnsyncedMoveIntents replays it\n // once the create lands.\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move source is not synced yet\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"blocked\");\n }\n if (\n !hasRemoteContainerMetadataState(parentState) ||\n input.isCreatePending(intent.parentContainerId)\n ) {\n await recordPendingMoveIntentError({\n containerId: intent.containerId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Container move destination parent is not synced yet\",\n state,\n });\n return currentMoveResult(input.isCurrent, \"blocked\");\n }\n\n return movePendingRemoteContainer({\n containerState,\n parentState,\n syncInput: input,\n });\n}\n\nexport async function syncPendingContainerMoveIntents(input: {\n host: ContainerMoveIntentSyncHost;\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) {\n return 0;\n }\n const { host } = input;\n const state = { ...input.state };\n const execSql = state.runtime.infra.execSql;\n const pendingIntents =\n await state.persistence.listUnsyncedMoveIntents(execSql);\n if (!input.isCurrent()) {\n return 0;\n }\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) {\n return movedCount;\n }\n const result = await trySyncPendingContainerMoveIntent({\n host,\n isCurrent: input.isCurrent,\n isCreatePending: input.isCreatePending,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n requestRemoteReconciliation: input.requestRemoteReconciliation,\n acceptedMoveRetry: input.acceptedMoveRetry,\n state,\n });\n if (result === \"abandoned\") {\n return movedCount;\n }\n\n if (result === \"moved\") {\n movedCount += 1;\n } else {\n // A replay that failed before reaching the server keeps an earlier\n // acceptance's retries going.\n input.acceptedMoveRetry.resume(intent.id);\n }\n }\n\n return movedCount;\n}\n"]}
@@ -5,7 +5,6 @@ import { rethrowProjectionVerificationCancelled } from "../../../../data/keyingP
5
5
  import { hasUnsettledDocumentPlacement } from "../../../../data/persistence/container-contents/documentPurgePlacement.js";
6
6
  import { sqlDocumentsPersistence } from "../../../../data/persistence/documents/documentsPersistence.js";
7
7
  import { errorMessage } from "../../../../data/shared/errorMessage.js";
8
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
9
8
  import { assertLocalPurgeScope } from "./localPurgeScope.js";
10
9
  import { snapshotContainerStates } from "./purgeTreeCollection.js";
11
10
  import { readLocalPurgeScope } from "./readLocalPurgeScope.js";
@@ -30,7 +29,7 @@ async function verifiedRemoteScope(input, current, verifiedAncestorsById) {
30
29
  projection,
31
30
  resolveUserKey: input.resolveProjectionUserKey,
32
31
  stillCurrent: input.stillCurrent,
33
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime),
32
+ warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),
34
33
  });
35
34
  const rootIndex = path.findIndex((head) => head.state.containerId === rootContainerId);
36
35
  const latest = await input.persistence.loadContainerMetadataState(runtime.infra.execSql, targetId);