feat(ql3): establish 3.0 incubation baseline

This commit is contained in:
whyour committed 2026-08-12 00:25:26 +08:00
1 parent 4bf92dcfeb
commit c699c32461
2817 files changed
+779642 -653

No files matched your search

+1
View File
@@ -0,0 +1 @@
dist/
+816
View File
@@ -0,0 +1,816 @@
{
"name": "@qinglong/runtime-core",
"version": "3.0.0-alpha.0",
"private": true,
"description": "QingLong 3.0 profile-neutral runtime contracts",
"license": "Apache-2.0",
"engines": {
"node": ">=24.18.0 <25"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"typesVersions": {
"*": {
"local-dispatch": [
"dist/local-runtime/localDispatch.d.ts"
],
"remote-dispatch": [
"dist/remote-execution/remoteDispatch.d.ts"
],
"remote-offer-delivery": [
"dist/remote-execution/remoteOfferDelivery.d.ts"
],
"remote-activation": [
"dist/remote-execution/remoteRunActivation.d.ts"
],
"remote-activation-delivery": [
"dist/remote-execution/remoteRunActivationDelivery.d.ts"
],
"remote-secret-delivery": [
"dist/remote-execution/remoteSecretDelivery.d.ts"
],
"remote-worker-completion": [
"dist/remote-execution/remoteWorkerCompletion.d.ts"
],
"remote-worker-lease-control": [
"dist/remote-execution/remoteWorkerLeaseControl.d.ts"
],
"cluster-run-cancellation": [
"dist/run/clusterRunCancellation.d.ts"
],
"run-cancellation": [
"dist/run/clusterRunCancellation.d.ts"
],
"task-start": [
"dist/task-start/taskStart.d.ts"
],
"cluster-run-cancellation-convergence": [
"dist/run/clusterRunCancellationConvergence.d.ts"
],
"run-dispatch-lease": [
"dist/run/runDispatchLease.d.ts"
],
"worker-session": [
"dist/worker/workerSession.d.ts"
],
"worker-session-transport": [
"dist/worker/workerSessionTransport.d.ts"
],
"worker-credential": [
"dist/worker/workerCredential.d.ts"
],
"worker-credential-delivery": [
"dist/worker/workerCredentialDelivery.d.ts"
],
"worker-credential-token": [
"dist/worker/workerCredentialToken.d.ts"
],
"worker-credential-management-plan": [
"dist/worker/workerCredentialManagementPlan.d.ts"
],
"plugin-package": [
"dist/plugin-package/pluginPackage.d.ts"
],
"plugin-package-install": [
"dist/plugin-package/installation/pluginPackageInstall.d.ts"
],
"plugin-package-activation": [
"dist/plugin-package/installation/pluginPackageActivation.d.ts"
],
"plugin-package-resource-generation": [
"dist/plugin-package/pluginPackageResourceGeneration.d.ts"
],
"plugin-package-resource-materialization": [
"dist/plugin-package/pluginPackageResourceMaterialization.d.ts"
],
"plugin-package-task-reconciliation": [
"dist/plugin-package/pluginPackageTaskReconciliation.d.ts"
],
"plugin-package-task-publication": [
"dist/plugin-package/pluginPackageTaskPublication.d.ts"
],
"plugin-package-automation-publication": [
"dist/plugin-package/pluginPackageAutomationPublication.d.ts"
],
"plugin-package-workflow-execution-plan": [
"dist/plugin-package/workflow/pluginPackageWorkflowExecutionPlan.d.ts"
],
"plugin-package-workflow-administration": [
"dist/plugin-package/workflow/pluginPackageWorkflowAdministration.d.ts"
],
"plugin-package-workflow-frontier": [
"dist/plugin-package/workflow/pluginPackageWorkflowFrontier.d.ts"
],
"plugin-package-workflow-cancellation-convergence": [
"dist/plugin-package/workflow/pluginPackageWorkflowCancellationConvergence.d.ts"
],
"plugin-package-workflow-task-attempt-admission": [
"dist/plugin-package/workflow/pluginPackageWorkflowTaskAttemptAdmission.d.ts"
],
"plugin-package-quarantine": [
"dist/plugin-package/lifecycle/pluginPackageQuarantine.d.ts"
],
"plugin-package-lifecycle": [
"dist/plugin-package/lifecycle/pluginPackageLifecycle.d.ts"
],
"plugin-package-lifecycle-plan": [
"dist/plugin-package/lifecycle/pluginPackageLifecyclePlan.d.ts"
],
"plugin-package-publisher-provenance": [
"dist/plugin-package/publisher/pluginPackagePublisherProvenance.d.ts"
],
"plugin-package-publisher-trust": [
"dist/plugin-package/publisher/pluginPackagePublisherTrust.d.ts"
],
"plugin-package-publisher-revocation-proposal": [
"dist/plugin-package/publisher/pluginPackagePublisherRevocationProposal.d.ts"
],
"plugin-package-publisher-trust-transition-proposal": [
"dist/plugin-package/publisher/pluginPackagePublisherTrustTransitionProposal.d.ts"
],
"project-tool-definition-snapshot": [
"dist/tool-execution/tool-registry/projectToolDefinitionSnapshot.d.ts"
],
"plugin-package-installation": [
"dist/plugin-package/installation/pluginPackageInstallation.d.ts"
],
"plugin-package-admission": [
"dist/plugin-package/installation/pluginPackageAdmission.d.ts"
],
"plugin-package-recovery": [
"dist/plugin-package/installation/pluginPackageRecovery.d.ts"
],
"plugin-package-bundle": [
"dist/plugin-package/pluginPackageBundle.d.ts"
],
"approved-action": [
"dist/approved-action/approvedAction.d.ts"
],
"approval-discovery": [
"dist/approved-action/approvalDiscovery.d.ts"
],
"approval-decision": [
"dist/approved-action/approvalDecision.d.ts"
],
"approval-inspection": [
"dist/approved-action/approvalInspection.d.ts"
],
"approved-action-execution": [
"dist/approved-action/approvedActionExecution.d.ts"
],
"approved-action-dispatcher": [
"dist/approved-action/approvedActionDispatcher.d.ts"
],
"plugin-package-approved-action": [
"dist/plugin-package/pluginPackageApprovedActionHandler.d.ts"
],
"plugin-package-proposal": [
"dist/plugin-package/pluginPackageProposal.d.ts"
],
"plugin-package-management": [
"dist/plugin-package/pluginPackageManagement.d.ts"
],
"tool-registry": [
"dist/tool-execution/tool-registry/toolRegistry.d.ts"
],
"tool-invocation-artifact": [
"dist/tool-execution/toolInvocationArtifact.d.ts"
],
"trusted-tool-invocation": [
"dist/tool-execution/trustedToolInvocation.d.ts"
],
"step-run": [
"dist/run/stepRun.d.ts"
],
"tool-execution-evidence": [
"dist/tool-execution/toolExecutionEvidence.d.ts"
],
"tool-execution-start-barrier": [
"dist/tool-execution/toolExecutionStartBarrier.d.ts"
],
"trusted-tool-execution": [
"dist/tool-execution/trustedToolExecution.d.ts"
],
"tool-execution-completion": [
"dist/tool-execution/toolExecutionCompletion.d.ts"
],
"trusted-tool-success-completion": [
"dist/tool-execution/trustedToolSuccessCompletion.d.ts"
],
"trusted-tool-completion": [
"dist/tool-execution/trustedToolCompletion.d.ts"
],
"tool-execution-failure-completion": [
"dist/tool-execution/toolExecutionFailureCompletion.d.ts"
],
"tool-result-key-catalog": [
"dist/tool-execution/toolResultKeyCatalog.d.ts"
],
"tool-result-rekey": [
"dist/tool-execution/toolResultRekey.d.ts"
],
"builtin-run-read-tool": [
"dist/tool-execution/builtin-run-read/builtInRunReadTool.d.ts"
],
"builtin-run-read-projection": [
"dist/tool-execution/builtin-run-read/builtInRunReadProjection.d.ts"
],
"run": [
"dist/run/run.d.ts"
],
"project-run-list": [
"dist/run/projectRunList.d.ts"
],
"bounded-run-read-projection": [
"dist/run/projection/boundedRunReadProjection.d.ts"
],
"bounded-run-list-projection": [
"dist/run/projection/boundedRunListProjection.d.ts"
],
"bounded-run-event-list-projection": [
"dist/run/projection/boundedRunEventListProjection.d.ts"
],
"bounded-run-step-list-projection": [
"dist/run/projection/boundedRunStepListProjection.d.ts"
]
}
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"default": "./dist/index.js"
},
"./migration-stream": {
"types": "./dist/migration/migrationStream.d.ts",
"require": "./dist/migration/migrationStream.js",
"default": "./dist/migration/migrationStream.js"
},
"./run": {
"types": "./dist/run/run.d.ts",
"require": "./dist/run/run.js",
"default": "./dist/run/run.js"
},
"./run-repository": {
"types": "./dist/run/runRepositoryContract.d.ts",
"require": "./dist/run/runRepositoryContract.js",
"default": "./dist/run/runRepositoryContract.js"
},
"./project-run-list": {
"types": "./dist/run/projectRunList.d.ts",
"require": "./dist/run/projectRunList.js",
"default": "./dist/run/projectRunList.js"
},
"./bounded-run-read-projection": {
"types": "./dist/run/projection/boundedRunReadProjection.d.ts",
"require": "./dist/run/projection/boundedRunReadProjection.js",
"default": "./dist/run/projection/boundedRunReadProjection.js"
},
"./bounded-run-list-projection": {
"types": "./dist/run/projection/boundedRunListProjection.d.ts",
"require": "./dist/run/projection/boundedRunListProjection.js",
"default": "./dist/run/projection/boundedRunListProjection.js"
},
"./bounded-run-event-list-projection": {
"types": "./dist/run/projection/boundedRunEventListProjection.d.ts",
"require": "./dist/run/projection/boundedRunEventListProjection.js",
"default": "./dist/run/projection/boundedRunEventListProjection.js"
},
"./bounded-run-step-list-projection": {
"types": "./dist/run/projection/boundedRunStepListProjection.d.ts",
"require": "./dist/run/projection/boundedRunStepListProjection.js",
"default": "./dist/run/projection/boundedRunStepListProjection.js"
},
"./task-definition": {
"types": "./dist/task-definition/taskDefinition.d.ts",
"require": "./dist/task-definition/taskDefinition.js",
"default": "./dist/task-definition/taskDefinition.js"
},
"./bounded-task-list-projection": {
"types": "./dist/task-definition/projection/boundedTaskListProjection.d.ts",
"require": "./dist/task-definition/projection/boundedTaskListProjection.js",
"default": "./dist/task-definition/projection/boundedTaskListProjection.js"
},
"./bounded-task-read-projection": {
"types": "./dist/task-definition/projection/boundedTaskReadProjection.d.ts",
"require": "./dist/task-definition/projection/boundedTaskReadProjection.js",
"default": "./dist/task-definition/projection/boundedTaskReadProjection.js"
},
"./task-definition-administration": {
"types": "./dist/task-definition/taskDefinitionAdministration.d.ts",
"require": "./dist/task-definition/taskDefinitionAdministration.js",
"default": "./dist/task-definition/taskDefinitionAdministration.js"
},
"./plugin-package": {
"types": "./dist/plugin-package/pluginPackage.d.ts",
"require": "./dist/plugin-package/pluginPackage.js",
"default": "./dist/plugin-package/pluginPackage.js"
},
"./plugin-package-install": {
"types": "./dist/plugin-package/installation/pluginPackageInstall.d.ts",
"require": "./dist/plugin-package/installation/pluginPackageInstall.js",
"default": "./dist/plugin-package/installation/pluginPackageInstall.js"
},
"./plugin-package-activation": {
"types": "./dist/plugin-package/installation/pluginPackageActivation.d.ts",
"require": "./dist/plugin-package/installation/pluginPackageActivation.js",
"default": "./dist/plugin-package/installation/pluginPackageActivation.js"
},
"./plugin-package-resource-generation": {
"types": "./dist/plugin-package/pluginPackageResourceGeneration.d.ts",
"require": "./dist/plugin-package/pluginPackageResourceGeneration.js",
"default": "./dist/plugin-package/pluginPackageResourceGeneration.js"
},
"./plugin-package-resource-materialization": {
"types": "./dist/plugin-package/pluginPackageResourceMaterialization.d.ts",
"require": "./dist/plugin-package/pluginPackageResourceMaterialization.js",
"default": "./dist/plugin-package/pluginPackageResourceMaterialization.js"
},
"./plugin-package-task-reconciliation": {
"types": "./dist/plugin-package/pluginPackageTaskReconciliation.d.ts",
"require": "./dist/plugin-package/pluginPackageTaskReconciliation.js",
"default": "./dist/plugin-package/pluginPackageTaskReconciliation.js"
},
"./plugin-package-task-publication": {
"types": "./dist/plugin-package/pluginPackageTaskPublication.d.ts",
"require": "./dist/plugin-package/pluginPackageTaskPublication.js",
"default": "./dist/plugin-package/pluginPackageTaskPublication.js"
},
"./plugin-package-automation-publication": {
"types": "./dist/plugin-package/pluginPackageAutomationPublication.d.ts",
"require": "./dist/plugin-package/pluginPackageAutomationPublication.js",
"default": "./dist/plugin-package/pluginPackageAutomationPublication.js"
},
"./plugin-package-workflow-execution-plan": {
"types": "./dist/plugin-package/workflow/pluginPackageWorkflowExecutionPlan.d.ts",
"require": "./dist/plugin-package/workflow/pluginPackageWorkflowExecutionPlan.js",
"default": "./dist/plugin-package/workflow/pluginPackageWorkflowExecutionPlan.js"
},
"./plugin-package-workflow-administration": {
"types": "./dist/plugin-package/workflow/pluginPackageWorkflowAdministration.d.ts",
"require": "./dist/plugin-package/workflow/pluginPackageWorkflowAdministration.js",
"default": "./dist/plugin-package/workflow/pluginPackageWorkflowAdministration.js"
},
"./plugin-package-workflow-frontier": {
"types": "./dist/plugin-package/workflow/pluginPackageWorkflowFrontier.d.ts",
"require": "./dist/plugin-package/workflow/pluginPackageWorkflowFrontier.js",
"default": "./dist/plugin-package/workflow/pluginPackageWorkflowFrontier.js"
},
"./plugin-package-workflow-cancellation-convergence": {
"types": "./dist/plugin-package/workflow/pluginPackageWorkflowCancellationConvergence.d.ts",
"require": "./dist/plugin-package/workflow/pluginPackageWorkflowCancellationConvergence.js",
"default": "./dist/plugin-package/workflow/pluginPackageWorkflowCancellationConvergence.js"
},
"./plugin-package-workflow-task-attempt-admission": {
"types": "./dist/plugin-package/workflow/pluginPackageWorkflowTaskAttemptAdmission.d.ts",
"require": "./dist/plugin-package/workflow/pluginPackageWorkflowTaskAttemptAdmission.js",
"default": "./dist/plugin-package/workflow/pluginPackageWorkflowTaskAttemptAdmission.js"
},
"./plugin-package-quarantine": {
"types": "./dist/plugin-package/lifecycle/pluginPackageQuarantine.d.ts",
"require": "./dist/plugin-package/lifecycle/pluginPackageQuarantine.js",
"default": "./dist/plugin-package/lifecycle/pluginPackageQuarantine.js"
},
"./plugin-package-lifecycle": {
"types": "./dist/plugin-package/lifecycle/pluginPackageLifecycle.d.ts",
"require": "./dist/plugin-package/lifecycle/pluginPackageLifecycle.js",
"default": "./dist/plugin-package/lifecycle/pluginPackageLifecycle.js"
},
"./plugin-package-lifecycle-plan": {
"types": "./dist/plugin-package/lifecycle/pluginPackageLifecyclePlan.d.ts",
"require": "./dist/plugin-package/lifecycle/pluginPackageLifecyclePlan.js",
"default": "./dist/plugin-package/lifecycle/pluginPackageLifecyclePlan.js"
},
"./plugin-package-publisher-provenance": {
"types": "./dist/plugin-package/publisher/pluginPackagePublisherProvenance.d.ts",
"require": "./dist/plugin-package/publisher/pluginPackagePublisherProvenance.js",
"default": "./dist/plugin-package/publisher/pluginPackagePublisherProvenance.js"
},
"./plugin-package-publisher-trust": {
"types": "./dist/plugin-package/publisher/pluginPackagePublisherTrust.d.ts",
"require": "./dist/plugin-package/publisher/pluginPackagePublisherTrust.js",
"default": "./dist/plugin-package/publisher/pluginPackagePublisherTrust.js"
},
"./plugin-package-publisher-revocation-proposal": {
"types": "./dist/plugin-package/publisher/pluginPackagePublisherRevocationProposal.d.ts",
"require": "./dist/plugin-package/publisher/pluginPackagePublisherRevocationProposal.js",
"default": "./dist/plugin-package/publisher/pluginPackagePublisherRevocationProposal.js"
},
"./plugin-package-publisher-trust-transition-proposal": {
"types": "./dist/plugin-package/publisher/pluginPackagePublisherTrustTransitionProposal.d.ts",
"require": "./dist/plugin-package/publisher/pluginPackagePublisherTrustTransitionProposal.js",
"default": "./dist/plugin-package/publisher/pluginPackagePublisherTrustTransitionProposal.js"
},
"./project-tool-definition-snapshot": {
"types": "./dist/tool-execution/tool-registry/projectToolDefinitionSnapshot.d.ts",
"require": "./dist/tool-execution/tool-registry/projectToolDefinitionSnapshot.js",
"default": "./dist/tool-execution/tool-registry/projectToolDefinitionSnapshot.js"
},
"./plugin-package-installation": {
"types": "./dist/plugin-package/installation/pluginPackageInstallation.d.ts",
"require": "./dist/plugin-package/installation/pluginPackageInstallation.js",
"default": "./dist/plugin-package/installation/pluginPackageInstallation.js"
},
"./plugin-package-admission": {
"types": "./dist/plugin-package/installation/pluginPackageAdmission.d.ts",
"require": "./dist/plugin-package/installation/pluginPackageAdmission.js",
"default": "./dist/plugin-package/installation/pluginPackageAdmission.js"
},
"./plugin-package-recovery": {
"types": "./dist/plugin-package/installation/pluginPackageRecovery.d.ts",
"require": "./dist/plugin-package/installation/pluginPackageRecovery.js",
"default": "./dist/plugin-package/installation/pluginPackageRecovery.js"
},
"./plugin-package-bundle": {
"types": "./dist/plugin-package/pluginPackageBundle.d.ts",
"require": "./dist/plugin-package/pluginPackageBundle.js",
"default": "./dist/plugin-package/pluginPackageBundle.js"
},
"./approved-action": {
"types": "./dist/approved-action/approvedAction.d.ts",
"require": "./dist/approved-action/approvedAction.js",
"default": "./dist/approved-action/approvedAction.js"
},
"./approval-discovery": {
"types": "./dist/approved-action/approvalDiscovery.d.ts",
"require": "./dist/approved-action/approvalDiscovery.js",
"default": "./dist/approved-action/approvalDiscovery.js"
},
"./approval-decision": {
"types": "./dist/approved-action/approvalDecision.d.ts",
"require": "./dist/approved-action/approvalDecision.js",
"default": "./dist/approved-action/approvalDecision.js"
},
"./approval-inspection": {
"types": "./dist/approved-action/approvalInspection.d.ts",
"require": "./dist/approved-action/approvalInspection.js",
"default": "./dist/approved-action/approvalInspection.js"
},
"./approved-action-execution": {
"types": "./dist/approved-action/approvedActionExecution.d.ts",
"require": "./dist/approved-action/approvedActionExecution.js",
"default": "./dist/approved-action/approvedActionExecution.js"
},
"./approved-action-dispatcher": {
"types": "./dist/approved-action/approvedActionDispatcher.d.ts",
"require": "./dist/approved-action/approvedActionDispatcher.js",
"default": "./dist/approved-action/approvedActionDispatcher.js"
},
"./plugin-package-approved-action": {
"types": "./dist/plugin-package/pluginPackageApprovedActionHandler.d.ts",
"require": "./dist/plugin-package/pluginPackageApprovedActionHandler.js",
"default": "./dist/plugin-package/pluginPackageApprovedActionHandler.js"
},
"./plugin-package-proposal": {
"types": "./dist/plugin-package/pluginPackageProposal.d.ts",
"require": "./dist/plugin-package/pluginPackageProposal.js",
"default": "./dist/plugin-package/pluginPackageProposal.js"
},
"./plugin-package-management": {
"types": "./dist/plugin-package/pluginPackageManagement.d.ts",
"require": "./dist/plugin-package/pluginPackageManagement.js",
"default": "./dist/plugin-package/pluginPackageManagement.js"
},
"./tool-registry": {
"types": "./dist/tool-execution/tool-registry/toolRegistry.d.ts",
"require": "./dist/tool-execution/tool-registry/toolRegistry.js",
"default": "./dist/tool-execution/tool-registry/toolRegistry.js"
},
"./tool-invocation-artifact": {
"types": "./dist/tool-execution/toolInvocationArtifact.d.ts",
"require": "./dist/tool-execution/toolInvocationArtifact.js",
"default": "./dist/tool-execution/toolInvocationArtifact.js"
},
"./trusted-tool-invocation": {
"types": "./dist/tool-execution/trustedToolInvocation.d.ts",
"require": "./dist/tool-execution/trustedToolInvocation.js",
"default": "./dist/tool-execution/trustedToolInvocation.js"
},
"./step-run": {
"types": "./dist/run/stepRun.d.ts",
"require": "./dist/run/stepRun.js",
"default": "./dist/run/stepRun.js"
},
"./tool-execution-evidence": {
"types": "./dist/tool-execution/toolExecutionEvidence.d.ts",
"require": "./dist/tool-execution/toolExecutionEvidence.js",
"default": "./dist/tool-execution/toolExecutionEvidence.js"
},
"./tool-execution-start-barrier": {
"types": "./dist/tool-execution/toolExecutionStartBarrier.d.ts",
"require": "./dist/tool-execution/toolExecutionStartBarrier.js",
"default": "./dist/tool-execution/toolExecutionStartBarrier.js"
},
"./trusted-tool-execution": {
"types": "./dist/tool-execution/trustedToolExecution.d.ts",
"require": "./dist/tool-execution/trustedToolExecution.js",
"default": "./dist/tool-execution/trustedToolExecution.js"
},
"./tool-execution-completion": {
"types": "./dist/tool-execution/toolExecutionCompletion.d.ts",
"require": "./dist/tool-execution/toolExecutionCompletion.js",
"default": "./dist/tool-execution/toolExecutionCompletion.js"
},
"./trusted-tool-success-completion": {
"types": "./dist/tool-execution/trustedToolSuccessCompletion.d.ts",
"require": "./dist/tool-execution/trustedToolSuccessCompletion.js",
"default": "./dist/tool-execution/trustedToolSuccessCompletion.js"
},
"./trusted-tool-completion": {
"types": "./dist/tool-execution/trustedToolCompletion.d.ts",
"require": "./dist/tool-execution/trustedToolCompletion.js",
"default": "./dist/tool-execution/trustedToolCompletion.js"
},
"./tool-execution-failure-completion": {
"types": "./dist/tool-execution/toolExecutionFailureCompletion.d.ts",
"require": "./dist/tool-execution/toolExecutionFailureCompletion.js",
"default": "./dist/tool-execution/toolExecutionFailureCompletion.js"
},
"./tool-result-key-catalog": {
"types": "./dist/tool-execution/toolResultKeyCatalog.d.ts",
"require": "./dist/tool-execution/toolResultKeyCatalog.js",
"default": "./dist/tool-execution/toolResultKeyCatalog.js"
},
"./tool-result-rekey": {
"types": "./dist/tool-execution/toolResultRekey.d.ts",
"require": "./dist/tool-execution/toolResultRekey.js",
"default": "./dist/tool-execution/toolResultRekey.js"
},
"./builtin-run-read-tool": {
"types": "./dist/tool-execution/builtin-run-read/builtInRunReadTool.d.ts",
"require": "./dist/tool-execution/builtin-run-read/builtInRunReadTool.js",
"default": "./dist/tool-execution/builtin-run-read/builtInRunReadTool.js"
},
"./builtin-run-read-projection": {
"types": "./dist/tool-execution/builtin-run-read/builtInRunReadProjection.d.ts",
"require": "./dist/tool-execution/builtin-run-read/builtInRunReadProjection.js",
"default": "./dist/tool-execution/builtin-run-read/builtInRunReadProjection.js"
},
"./secret-reference": {
"types": "./dist/secret/secretReference.d.ts",
"require": "./dist/secret/secretReference.js",
"default": "./dist/secret/secretReference.js"
},
"./cluster-execution-revision": {
"types": "./dist/task-definition/clusterExecutionRevision.d.ts",
"require": "./dist/task-definition/clusterExecutionRevision.js",
"default": "./dist/task-definition/clusterExecutionRevision.js"
},
"./cluster-scheduler": {
"types": "./dist/scheduler/clusterScheduler.d.ts",
"require": "./dist/scheduler/clusterScheduler.js",
"default": "./dist/scheduler/clusterScheduler.js"
},
"./remote-dispatch": {
"types": "./dist/remote-execution/remoteDispatch.d.ts",
"require": "./dist/remote-execution/remoteDispatch.js",
"default": "./dist/remote-execution/remoteDispatch.js"
},
"./remote-offer-delivery": {
"types": "./dist/remote-execution/remoteOfferDelivery.d.ts",
"require": "./dist/remote-execution/remoteOfferDelivery.js",
"default": "./dist/remote-execution/remoteOfferDelivery.js"
},
"./remote-activation": {
"types": "./dist/remote-execution/remoteRunActivation.d.ts",
"require": "./dist/remote-execution/remoteRunActivation.js",
"default": "./dist/remote-execution/remoteRunActivation.js"
},
"./remote-activation-delivery": {
"types": "./dist/remote-execution/remoteRunActivationDelivery.d.ts",
"require": "./dist/remote-execution/remoteRunActivationDelivery.js",
"default": "./dist/remote-execution/remoteRunActivationDelivery.js"
},
"./remote-secret-delivery": {
"types": "./dist/remote-execution/remoteSecretDelivery.d.ts",
"require": "./dist/remote-execution/remoteSecretDelivery.js",
"default": "./dist/remote-execution/remoteSecretDelivery.js"
},
"./remote-worker-completion": {
"types": "./dist/remote-execution/remoteWorkerCompletion.d.ts",
"require": "./dist/remote-execution/remoteWorkerCompletion.js",
"default": "./dist/remote-execution/remoteWorkerCompletion.js"
},
"./remote-worker-lease-control": {
"types": "./dist/remote-execution/remoteWorkerLeaseControl.d.ts",
"require": "./dist/remote-execution/remoteWorkerLeaseControl.js",
"default": "./dist/remote-execution/remoteWorkerLeaseControl.js"
},
"./cluster-run-cancellation": {
"types": "./dist/run/clusterRunCancellation.d.ts",
"require": "./dist/run/clusterRunCancellation.js",
"default": "./dist/run/clusterRunCancellation.js"
},
"./run-cancellation": {
"types": "./dist/run/clusterRunCancellation.d.ts",
"require": "./dist/run/clusterRunCancellation.js",
"default": "./dist/run/clusterRunCancellation.js"
},
"./task-start": {
"types": "./dist/task-start/taskStart.d.ts",
"require": "./dist/task-start/taskStart.js",
"default": "./dist/task-start/taskStart.js"
},
"./cluster-run-cancellation-convergence": {
"types": "./dist/run/clusterRunCancellationConvergence.d.ts",
"require": "./dist/run/clusterRunCancellationConvergence.js",
"default": "./dist/run/clusterRunCancellationConvergence.js"
},
"./run-dispatch-lease": {
"types": "./dist/run/runDispatchLease.d.ts",
"require": "./dist/run/runDispatchLease.js",
"default": "./dist/run/runDispatchLease.js"
},
"./worker-session": {
"types": "./dist/worker/workerSession.d.ts",
"require": "./dist/worker/workerSession.js",
"default": "./dist/worker/workerSession.js"
},
"./worker-session-transport": {
"types": "./dist/worker/workerSessionTransport.d.ts",
"require": "./dist/worker/workerSessionTransport.js",
"default": "./dist/worker/workerSessionTransport.js"
},
"./trigger": {
"types": "./dist/scheduler/trigger.d.ts",
"require": "./dist/scheduler/trigger.js",
"default": "./dist/scheduler/trigger.js"
},
"./trigger-administration": {
"types": "./dist/scheduler/triggerAdministration.d.ts",
"require": "./dist/scheduler/triggerAdministration.js",
"default": "./dist/scheduler/triggerAdministration.js"
},
"./task-spec-semantic": {
"types": "./dist/task-definition/taskSpecSemantic.d.ts",
"require": "./dist/task-definition/taskSpecSemantic.js",
"default": "./dist/task-definition/taskSpecSemantic.js"
},
"./task-definition-execution-compiler": {
"types": "./dist/task-definition/taskDefinitionExecutionCompiler.d.ts",
"require": "./dist/task-definition/taskDefinitionExecutionCompiler.js",
"default": "./dist/task-definition/taskDefinitionExecutionCompiler.js"
},
"./local-startup-recovery": {
"types": "./dist/local-runtime/localStartupRecovery.d.ts",
"require": "./dist/local-runtime/localStartupRecovery.js",
"default": "./dist/local-runtime/localStartupRecovery.js"
},
"./local-completion-receipt-journal": {
"types": "./dist/local-runtime/localCompletionReceiptJournal.d.ts",
"require": "./dist/local-runtime/localCompletionReceiptJournal.js",
"default": "./dist/local-runtime/localCompletionReceiptJournal.js"
},
"./local-dispatch": {
"types": "./dist/local-runtime/localDispatch.d.ts",
"require": "./dist/local-runtime/localDispatch.js",
"default": "./dist/local-runtime/localDispatch.js"
},
"./local-execution-control": {
"types": "./dist/local-runtime/localExecutionControl.d.ts",
"require": "./dist/local-runtime/localExecutionControl.js",
"default": "./dist/local-runtime/localExecutionControl.js"
},
"./local-scheduler": {
"types": "./dist/scheduler/localScheduler.d.ts",
"require": "./dist/scheduler/localScheduler.js",
"default": "./dist/scheduler/localScheduler.js"
},
"./local-secret": {
"types": "./dist/secret/localSecret.d.ts",
"require": "./dist/secret/localSecret.js",
"default": "./dist/secret/localSecret.js"
},
"./local-secret-administration": {
"types": "./dist/secret/localSecretAdministration.d.ts",
"require": "./dist/secret/localSecretAdministration.js",
"default": "./dist/secret/localSecretAdministration.js"
},
"./local-project-policy-administration": {
"types": "./dist/security/project-policy/localProjectPolicyAdministration.d.ts",
"require": "./dist/security/project-policy/localProjectPolicyAdministration.js",
"default": "./dist/security/project-policy/localProjectPolicyAdministration.js"
},
"./local-security-audit-query": {
"types": "./dist/security/audit/localSecurityAuditQuery.d.ts",
"require": "./dist/security/audit/localSecurityAuditQuery.js",
"default": "./dist/security/audit/localSecurityAuditQuery.js"
},
"./local-security-audit-retention": {
"types": "./dist/security/audit/localSecurityAuditRetention.d.ts",
"require": "./dist/security/audit/localSecurityAuditRetention.js",
"default": "./dist/security/audit/localSecurityAuditRetention.js"
},
"./local-identity-credential-administration": {
"types": "./dist/security/identity-credential/localIdentityCredentialAdministration.d.ts",
"require": "./dist/security/identity-credential/localIdentityCredentialAdministration.js",
"default": "./dist/security/identity-credential/localIdentityCredentialAdministration.js"
},
"./local-owner-bootstrap": {
"types": "./dist/local-owner/localOwnerBootstrap.d.ts",
"require": "./dist/local-owner/localOwnerBootstrap.js",
"default": "./dist/local-owner/localOwnerBootstrap.js"
},
"./local-owner-pepper": {
"types": "./dist/local-owner/localOwnerPepper.d.ts",
"require": "./dist/local-owner/localOwnerPepper.js",
"default": "./dist/local-owner/localOwnerPepper.js"
},
"./local-owner-credential-recovery": {
"types": "./dist/local-owner/localOwnerCredentialRecovery.d.ts",
"require": "./dist/local-owner/localOwnerCredentialRecovery.js",
"default": "./dist/local-owner/localOwnerCredentialRecovery.js"
},
"./local-owner-delivery-acknowledgement-gc": {
"types": "./dist/local-owner/localOwnerDeliveryAcknowledgementGc.d.ts",
"require": "./dist/local-owner/localOwnerDeliveryAcknowledgementGc.js",
"default": "./dist/local-owner/localOwnerDeliveryAcknowledgementGc.js"
},
"./local-owner-pepper-material-gc": {
"types": "./dist/local-owner/localOwnerPepperMaterialGc.d.ts",
"require": "./dist/local-owner/localOwnerPepperMaterialGc.js",
"default": "./dist/local-owner/localOwnerPepperMaterialGc.js"
},
"./security": {
"types": "./dist/security/security.d.ts",
"require": "./dist/security/security.js",
"default": "./dist/security/security.js"
},
"./api-credential": {
"types": "./dist/security/identity-credential/apiCredential.d.ts",
"require": "./dist/security/identity-credential/apiCredential.js",
"default": "./dist/security/identity-credential/apiCredential.js"
},
"./api-credential-administration": {
"types": "./dist/security/identity-credential/apiCredentialAdministration.d.ts",
"require": "./dist/security/identity-credential/apiCredentialAdministration.js",
"default": "./dist/security/identity-credential/apiCredentialAdministration.js"
},
"./api-credential-token": {
"types": "./dist/security/identity-credential/apiCredentialToken.d.ts",
"require": "./dist/security/identity-credential/apiCredentialToken.js",
"default": "./dist/security/identity-credential/apiCredentialToken.js"
},
"./identity-administration": {
"types": "./dist/security/identity-credential/identityAdministration.d.ts",
"require": "./dist/security/identity-credential/identityAdministration.js",
"default": "./dist/security/identity-credential/identityAdministration.js"
},
"./security-audit": {
"types": "./dist/security/audit/securityAudit.d.ts",
"require": "./dist/security/audit/securityAudit.js",
"default": "./dist/security/audit/securityAudit.js"
},
"./security-audit-query": {
"types": "./dist/security/audit/securityAuditQuery.d.ts",
"require": "./dist/security/audit/securityAuditQuery.js",
"default": "./dist/security/audit/securityAuditQuery.js"
},
"./project-policy": {
"types": "./dist/security/project-policy/projectPolicy.d.ts",
"require": "./dist/security/project-policy/projectPolicy.js",
"default": "./dist/security/project-policy/projectPolicy.js"
},
"./worker-credential": {
"types": "./dist/worker/workerCredential.d.ts",
"require": "./dist/worker/workerCredential.js",
"default": "./dist/worker/workerCredential.js"
},
"./worker-credential-delivery": {
"types": "./dist/worker/workerCredentialDelivery.d.ts",
"require": "./dist/worker/workerCredentialDelivery.js",
"default": "./dist/worker/workerCredentialDelivery.js"
},
"./worker-credential-token": {
"types": "./dist/worker/workerCredentialToken.d.ts",
"require": "./dist/worker/workerCredentialToken.js",
"default": "./dist/worker/workerCredentialToken.js"
},
"./worker-credential-management-plan": {
"types": "./dist/worker/workerCredentialManagementPlan.d.ts",
"require": "./dist/worker/workerCredentialManagementPlan.js",
"default": "./dist/worker/workerCredentialManagementPlan.js"
},
"./worker-attestation": {
"types": "./dist/worker/workerExecutionAttestation.d.ts",
"require": "./dist/worker/workerExecutionAttestation.js",
"default": "./dist/worker/workerExecutionAttestation.js"
}
},
"files": [
"dist/**/*.js",
"dist/**/*.d.ts"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"check": "node ../../scripts/ql3-build-package-closure.cjs && tsc -p tsconfig.json --noEmit",
"test": "node ../../scripts/ql3-build-package-closure.cjs && node --test test/*.test.cjs"
},
"dependencies": {
"semver": "7.7.4"
},
"devDependencies": {
"@types/node": "24.13.3",
"typescript": "5.9.3"
}
}
@@ -0,0 +1,347 @@
import {
ApprovalUnavailableError,
normalizeApprovedActionBinding,
normalizeApprovalRequestRecord,
type ApprovalDecision,
type ApprovalRequestRecord,
type ApprovalRequestRepository,
type ApprovedActionBinding,
type DecideApprovalRequestResult,
} from './approvedAction';
import { ProjectPolicyEngine } from '../security/project-policy/projectPolicy';
import {
normalizeSecurityPrincipal,
type SecurityPolicyFence,
type SecurityPrincipal,
} from '../security/security';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const STRONG_HUMAN_ASSURANCES = new Set([
'multi_factor',
'hardware',
'local_console',
]);
export interface ApprovalDecisionRequest {
readonly projectId: string;
readonly approvalRequestId: string;
readonly expectedVersion: number;
readonly expectedAction: Readonly<ApprovedActionBinding>;
readonly decisionId: string;
readonly decision: ApprovalDecision;
readonly reasonCode: string;
readonly auditEventId: string;
readonly requestId: string;
readonly principal: Readonly<SecurityPrincipal>;
}
export interface ApprovalDecisionService {
decide(
request: ApprovalDecisionRequest,
): Promise<Readonly<DecideApprovalRequestResult>>;
}
export interface ApprovalDecisionServiceOptions {
readonly approvals: Pick<
ApprovalRequestRepository,
'findById' | 'decide'
>;
readonly policy: Pick<ProjectPolicyEngine, 'authorize'>;
readonly confirmAuthorization?: () => void | Promise<void>;
readonly now?: () => number;
}
export class ApprovalDecisionRequestError extends TypeError {
readonly code = 'APPROVAL_DECISION_REQUEST_INVALID';
constructor(message: string) {
super(`Approval decision request is invalid: ${message}`);
this.name = 'ApprovalDecisionRequestError';
}
}
export class ApprovalDecisionAuthorizationError extends Error {
readonly code = 'APPROVAL_DECISION_AUTHORIZATION_REJECTED';
constructor() {
super('Approval decision authorization was rejected');
this.name = 'ApprovalDecisionAuthorizationError';
}
}
export class ApprovalDecisionTargetUnavailableError extends Error {
readonly code = 'APPROVAL_DECISION_TARGET_UNAVAILABLE';
constructor() {
super('Approval decision target is unavailable');
this.name = 'ApprovalDecisionTargetUnavailableError';
}
}
export class ApprovalDecisionBindingConflictError extends Error {
readonly code = 'APPROVAL_DECISION_BINDING_CONFLICT';
constructor() {
super('Approval decision does not match the reviewed action binding');
this.name = 'ApprovalDecisionBindingConflictError';
}
}
export class ApprovalDecisionUnavailableError extends Error {
readonly code = 'APPROVAL_DECISION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Approval decision authority is unavailable', options);
this.name = 'ApprovalDecisionUnavailableError';
}
}
function exactObject(
value: unknown,
expected: readonly string[],
label: string,
): asserts value is Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).sort().join('\0') !== [...expected].sort().join('\0')
) {
throw new ApprovalDecisionRequestError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new ApprovalDecisionRequestError(`${label} is invalid`);
}
return value;
}
function action(
value: Readonly<ApprovedActionBinding>,
): Readonly<ApprovedActionBinding> {
try {
return normalizeApprovedActionBinding(value);
} catch {
throw new ApprovalDecisionRequestError('expected action is invalid');
}
}
function sameAction(
left: Readonly<ApprovedActionBinding>,
right: Readonly<ApprovedActionBinding>,
): boolean {
return (
left.permission === right.permission &&
left.actionType === right.actionType &&
left.actionRef === right.actionRef &&
left.actionDigest === right.actionDigest &&
left.previewDigest === right.previewDigest
);
}
function sameSubject(
left: Readonly<SecurityPrincipal>['subject'],
right: Readonly<SecurityPrincipal>['subject'],
): boolean {
return left.type === right.type && left.id === right.id;
}
function observedTime(now: () => number): number {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new ApprovalDecisionUnavailableError();
}
return value;
}
function audit(
request: Readonly<ApprovalDecisionRequest>,
principal: Readonly<SecurityPrincipal>,
fence: Readonly<SecurityPolicyFence>,
occurredAtMs: number,
): Readonly<SecurityAuditRecord> {
return Object.freeze({
eventId: request.auditEventId,
requestId: request.requestId,
operationId: 'approval.decide',
projectId: request.projectId,
subject: principal.subject,
authenticationId: principal.authenticationId,
outcome: 'allowed',
reasons: Object.freeze(['human_approval_decision']),
fence,
occurredAtMs,
});
}
function normalizeRequest(
value: ApprovalDecisionRequest,
): Readonly<ApprovalDecisionRequest> {
exactObject(
value,
[
'projectId',
'approvalRequestId',
'expectedVersion',
'expectedAction',
'decisionId',
'decision',
'reasonCode',
'auditEventId',
'requestId',
'principal',
],
'request',
);
const projectId = identifier(value.projectId, 'projectId');
const approvalRequestId = identifier(
value.approvalRequestId,
'approvalRequestId',
);
const requestId = identifier(value.requestId, 'requestId');
const decisionId = identifier(value.decisionId, 'decisionId');
if (value.expectedVersion !== 1) {
throw new ApprovalDecisionRequestError('expectedVersion must be 1');
}
if (value.decision !== 'approved' && value.decision !== 'rejected') {
throw new ApprovalDecisionRequestError('decision is invalid');
}
if (
typeof value.reasonCode !== 'string' ||
!REASON_PATTERN.test(value.reasonCode)
) {
throw new ApprovalDecisionRequestError('reasonCode is invalid');
}
if (
typeof value.auditEventId !== 'string' ||
!UUID_V4_PATTERN.test(value.auditEventId)
) {
throw new ApprovalDecisionRequestError('auditEventId is invalid');
}
return Object.freeze({
projectId,
approvalRequestId,
expectedVersion: 1,
expectedAction: action(value.expectedAction),
decisionId,
decision: value.decision,
reasonCode: value.reasonCode,
auditEventId: value.auditEventId,
requestId,
principal: value.principal,
});
}
export function createApprovalDecisionService(
candidateOptions: ApprovalDecisionServiceOptions,
): Readonly<ApprovalDecisionService> {
exactObject(
candidateOptions,
[
'approvals',
'policy',
...(candidateOptions?.confirmAuthorization === undefined
? []
: ['confirmAuthorization']),
...(candidateOptions?.now === undefined ? [] : ['now']),
],
'options',
);
if (
typeof candidateOptions.approvals?.findById !== 'function' ||
typeof candidateOptions.approvals?.decide !== 'function' ||
typeof candidateOptions.policy?.authorize !== 'function' ||
(candidateOptions.confirmAuthorization !== undefined &&
typeof candidateOptions.confirmAuthorization !== 'function') ||
(candidateOptions.now !== undefined && typeof candidateOptions.now !== 'function')
) {
throw new ApprovalDecisionRequestError('options are invalid');
}
const now = candidateOptions.now ?? Date.now;
return Object.freeze({
async decide(requestValue: ApprovalDecisionRequest) {
const request = normalizeRequest(requestValue);
const decidedAtMs = observedTime(now);
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(request.principal, decidedAtMs);
} catch {
throw new ApprovalDecisionAuthorizationError();
}
if (
principal.subject.type !== 'user' ||
!STRONG_HUMAN_ASSURANCES.has(principal.assurance)
) {
throw new ApprovalDecisionAuthorizationError();
}
let authorization;
try {
authorization = await candidateOptions.policy.authorize(
principal,
request.projectId,
'approval.decide',
);
} catch (error) {
throw new ApprovalDecisionUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (authorization.effect !== 'allow' || authorization.fence === null) {
throw new ApprovalDecisionAuthorizationError();
}
let current: Readonly<ApprovalRequestRecord> | null;
try {
const found = await candidateOptions.approvals.findById(
request.approvalRequestId,
);
current = found ? normalizeApprovalRequestRecord(found) : null;
} catch (error) {
throw new ApprovalDecisionUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (!current || current.projectId !== request.projectId) {
throw new ApprovalDecisionTargetUnavailableError();
}
if (!sameAction(current.action, request.expectedAction)) {
throw new ApprovalDecisionBindingConflictError();
}
if (
current.version === 2 &&
current.decisionId === request.decisionId &&
current.decision === request.decision &&
current.decisionReasonCode === request.reasonCode &&
current.decidedBy !== null &&
sameSubject(current.decidedBy, principal.subject)
) {
await candidateOptions.confirmAuthorization?.();
return Object.freeze({ status: 'existing' as const, request: current });
}
await candidateOptions.confirmAuthorization?.();
try {
return await candidateOptions.approvals.decide({
requestId: request.approvalRequestId,
expectedVersion: request.expectedVersion,
decisionId: request.decisionId,
decision: request.decision,
reasonCode: request.reasonCode,
principal,
decidedAtMs,
authorizationFence: authorization.fence,
audit: audit(request, principal, authorization.fence, decidedAtMs),
});
} catch (error) {
if (error instanceof ApprovalUnavailableError) {
throw new ApprovalDecisionUnavailableError({ cause: error });
}
throw error;
}
},
});
}
@@ -0,0 +1,207 @@
import type { ApprovalRequestRecord } from './approvedAction';
export const MAX_APPROVAL_REQUEST_PAGE_SIZE = 64;
export const MAX_APPROVAL_DETAIL_PREVIEW_BYTES = 8 * 1024;
export interface ApprovalRequestCursor {
readonly updatedAtMs: number;
readonly requestId: string;
}
export interface ApprovalRequestPage {
readonly requests: readonly Readonly<ApprovalRequestRecord>[];
readonly truncated: boolean;
readonly next?: Readonly<ApprovalRequestCursor>;
}
export interface ApprovalRequestSource {
listApprovalRequests(options: {
readonly projectId: string;
readonly limit: number;
readonly after?: Readonly<ApprovalRequestCursor>;
}): Promise<Readonly<ApprovalRequestPage>>;
}
export interface ApprovalRequestDetail {
readonly request: Readonly<ApprovalRequestRecord>;
readonly preview: Readonly<ApprovalDetailPreview> | null;
}
export interface ApprovalDetailPreviewField {
readonly kind: 'count' | 'identifier' | 'redacted' | 'text';
readonly label: string;
readonly value: string | null;
}
export interface ApprovalDetailPreview {
readonly title: string;
readonly summary: string;
readonly fields: readonly Readonly<ApprovalDetailPreviewField>[];
readonly warnings: readonly string[];
}
export interface ApprovalRequestDetailSource {
getApprovalRequestDetail(options: {
readonly projectId: string;
readonly requestId: string;
}): Promise<Readonly<ApprovalRequestDetail> | null>;
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const WARNING_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const PREVIEW_FIELD_KINDS = ['count', 'identifier', 'redacted', 'text'] as const;
export class InvalidApprovalDiscoveryValueError extends TypeError {
constructor(message: string) {
super(`Approval discovery value is invalid: ${message}`);
this.name = 'InvalidApprovalDiscoveryValueError';
}
}
function identifier(value: unknown, name: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidApprovalDiscoveryValueError(`${name} is invalid`);
}
return value;
}
function timestamp(value: unknown, name: string): number {
if (!Number.isSafeInteger(value) || Number(value) < 0) {
throw new InvalidApprovalDiscoveryValueError(`${name} is invalid`);
}
return Number(value);
}
export function assertApprovalRequestPageSize(value: number): void {
if (
!Number.isSafeInteger(value) ||
value < 1 ||
value > MAX_APPROVAL_REQUEST_PAGE_SIZE
) {
throw new InvalidApprovalDiscoveryValueError('page size is invalid');
}
}
export function assertApprovalDiscoveryProjectId(value: string): void {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 128 ||
CONTROL_PATTERN.test(value)
) {
throw new InvalidApprovalDiscoveryValueError('projectId is invalid');
}
}
export function assertApprovalDiscoveryRequestId(value: string): void {
identifier(value, 'requestId');
}
export function normalizeApprovalRequestCursor(
value: ApprovalRequestCursor,
): Readonly<ApprovalRequestCursor> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidApprovalDiscoveryValueError('cursor is invalid');
}
const keys = Object.keys(value);
if (
keys.length !== 2 ||
!keys.includes('updatedAtMs') ||
!keys.includes('requestId')
) {
throw new InvalidApprovalDiscoveryValueError('cursor shape is invalid');
}
return Object.freeze({
updatedAtMs: timestamp(value.updatedAtMs, 'cursor updatedAtMs'),
requestId: identifier(value.requestId, 'cursor requestId'),
});
}
function boundedText(value: unknown, maximumBytes: number, name: string): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
CONTROL_PATTERN.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new InvalidApprovalDiscoveryValueError(`${name} is invalid`);
}
return value;
}
export function normalizeApprovalDetailPreview(
value: ApprovalDetailPreview,
): Readonly<ApprovalDetailPreview> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidApprovalDiscoveryValueError('preview is invalid');
}
const keys = Reflect.ownKeys(value);
if (
keys.length !== 4 ||
!['title', 'summary', 'fields', 'warnings'].every((key) =>
Object.hasOwn(value, key),
) ||
!Array.isArray(value.fields) ||
value.fields.length > 16 ||
!Array.isArray(value.warnings) ||
value.warnings.length > 8
) {
throw new InvalidApprovalDiscoveryValueError('preview shape is invalid');
}
const fields = value.fields.map((field) => {
if (
!field ||
typeof field !== 'object' ||
Array.isArray(field) ||
Reflect.ownKeys(field).length !== 3 ||
!Object.hasOwn(field, 'kind') ||
!Object.hasOwn(field, 'label') ||
!Object.hasOwn(field, 'value') ||
!PREVIEW_FIELD_KINDS.includes(field.kind) ||
(field.kind === 'redacted' && field.value !== null) ||
(field.kind !== 'redacted' && field.value === null)
) {
throw new InvalidApprovalDiscoveryValueError('preview field is invalid');
}
return Object.freeze({
kind: field.kind,
label: boundedText(field.label, 128, 'preview field label'),
value:
field.value === null
? null
: boundedText(field.value, 512, 'preview field value'),
});
});
const warnings = value.warnings.map((warning) => {
if (typeof warning !== 'string' || !WARNING_PATTERN.test(warning)) {
throw new InvalidApprovalDiscoveryValueError('preview warning is invalid');
}
return warning;
});
if (new Set(warnings).size !== warnings.length) {
throw new InvalidApprovalDiscoveryValueError('preview warnings are duplicated');
}
const normalized = Object.freeze({
title: boundedText(value.title, 256, 'preview title'),
summary: boundedText(value.summary, 2048, 'preview summary'),
fields: Object.freeze(fields),
warnings: Object.freeze([...warnings].sort()),
});
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_APPROVAL_DETAIL_PREVIEW_BYTES
) {
throw new InvalidApprovalDiscoveryValueError('preview byte budget exceeded');
}
return normalized;
}
export function approvalRequestUpdatedAtMs(
request: Readonly<ApprovalRequestRecord>,
): number {
return timestamp(
request.consumedAtMs ?? request.decidedAtMs ?? request.requestedAtMs,
'request updatedAtMs',
);
}
@@ -0,0 +1,268 @@
import { normalizeApprovalRequestRecord } from './approvedAction';
import {
normalizeApprovalDetailPreview,
type ApprovalRequestDetail,
type ApprovalRequestDetailSource,
} from './approvalDiscovery';
import { ProjectPolicyEngine } from '../security/project-policy/projectPolicy';
import {
normalizeSecurityPrincipal,
type SecurityPolicyFence,
type SecurityPrincipal,
} from '../security/security';
import type { SecurityAuditSink } from '../security/audit/securityAudit';
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const STRONG_HUMAN_ASSURANCES = new Set([
'multi_factor',
'hardware',
'local_console',
]);
export interface ApprovalInspectionRequest {
readonly projectId: string;
readonly approvalRequestId: string;
readonly auditEventId: string;
readonly requestId: string;
readonly principal: Readonly<SecurityPrincipal>;
}
export interface ApprovalInspectionService {
inspect(
request: ApprovalInspectionRequest,
): Promise<Readonly<ApprovalRequestDetail> | null>;
}
export interface ApprovalInspectionServiceOptions {
readonly source: Pick<ApprovalRequestDetailSource, 'getApprovalRequestDetail'>;
readonly policy: Pick<ProjectPolicyEngine, 'authorize'>;
readonly audit: Pick<SecurityAuditSink, 'record'>;
readonly confirmAuthorization?: () => void | Promise<void>;
readonly now?: () => number;
}
export class ApprovalInspectionRequestError extends TypeError {
readonly code = 'APPROVAL_INSPECTION_REQUEST_INVALID';
constructor(message: string) {
super(`Approval inspection request is invalid: ${message}`);
this.name = 'ApprovalInspectionRequestError';
}
}
export class ApprovalInspectionAuthorizationError extends Error {
readonly code = 'APPROVAL_INSPECTION_AUTHORIZATION_REJECTED';
constructor() {
super('Approval inspection authorization was rejected');
this.name = 'ApprovalInspectionAuthorizationError';
}
}
export class ApprovalInspectionUnavailableError extends Error {
readonly code = 'APPROVAL_INSPECTION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Approval inspection authority is unavailable', options);
this.name = 'ApprovalInspectionUnavailableError';
}
}
function exactObject(
value: unknown,
expected: readonly string[],
label: string,
): asserts value is Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).sort().join('\0') !== [...expected].sort().join('\0')
) {
throw new ApprovalInspectionRequestError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new ApprovalInspectionRequestError(`${label} is invalid`);
}
return value;
}
function sameFence(
left: Readonly<SecurityPolicyFence>,
right: Readonly<SecurityPolicyFence>,
): boolean {
return (
left.projectVersion === right.projectVersion &&
left.bindingVersion === right.bindingVersion
);
}
function observedTime(now: () => number): number {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new ApprovalInspectionUnavailableError();
}
return value;
}
function normalizedRequest(
value: ApprovalInspectionRequest,
): Readonly<ApprovalInspectionRequest> {
exactObject(
value,
[
'projectId',
'approvalRequestId',
'auditEventId',
'requestId',
'principal',
],
'request',
);
if (
typeof value.auditEventId !== 'string' ||
!UUID_V4_PATTERN.test(value.auditEventId)
) {
throw new ApprovalInspectionRequestError('auditEventId is invalid');
}
return Object.freeze({
projectId: identifier(value.projectId, 'projectId'),
approvalRequestId: identifier(
value.approvalRequestId,
'approvalRequestId',
),
auditEventId: value.auditEventId,
requestId: identifier(value.requestId, 'requestId'),
principal: value.principal,
});
}
export function createApprovalInspectionService(
options: ApprovalInspectionServiceOptions,
): Readonly<ApprovalInspectionService> {
exactObject(
options,
[
'source',
'policy',
'audit',
...(options?.confirmAuthorization === undefined
? []
: ['confirmAuthorization']),
...(options?.now === undefined ? [] : ['now']),
],
'options',
);
if (
typeof options.source?.getApprovalRequestDetail !== 'function' ||
typeof options.policy?.authorize !== 'function' ||
typeof options.audit?.record !== 'function' ||
(options.confirmAuthorization !== undefined &&
typeof options.confirmAuthorization !== 'function') ||
(options.now !== undefined && typeof options.now !== 'function')
) {
throw new ApprovalInspectionRequestError('options are invalid');
}
const now = options.now ?? Date.now;
return Object.freeze({
async inspect(requestValue: ApprovalInspectionRequest) {
const request = normalizedRequest(requestValue);
const occurredAtMs = observedTime(now);
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(request.principal, occurredAtMs);
} catch {
throw new ApprovalInspectionAuthorizationError();
}
if (
principal.subject.type !== 'user' ||
!STRONG_HUMAN_ASSURANCES.has(principal.assurance)
) {
throw new ApprovalInspectionAuthorizationError();
}
let approvalRead;
let artifactRead;
try {
[approvalRead, artifactRead] = await Promise.all([
options.policy.authorize(
principal,
request.projectId,
'approval.read',
),
options.policy.authorize(
principal,
request.projectId,
'artifact.read',
),
]);
} catch (error) {
throw new ApprovalInspectionUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (
approvalRead.effect !== 'allow' ||
approvalRead.fence === null ||
artifactRead.effect !== 'allow' ||
artifactRead.fence === null ||
!sameFence(approvalRead.fence, artifactRead.fence)
) {
throw new ApprovalInspectionAuthorizationError();
}
await options.confirmAuthorization?.();
let detail: Readonly<ApprovalRequestDetail> | null;
try {
const found = await options.source.getApprovalRequestDetail({
projectId: request.projectId,
requestId: request.approvalRequestId,
});
if (!found) {
detail = null;
} else {
const approval = normalizeApprovalRequestRecord(found.request);
if (
approval.projectId !== request.projectId ||
approval.id !== request.approvalRequestId
) {
throw new ApprovalInspectionUnavailableError();
}
detail = Object.freeze({
request: approval,
preview: found.preview
? normalizeApprovalDetailPreview(found.preview)
: null,
});
}
} catch (error) {
if (error instanceof ApprovalInspectionUnavailableError) throw error;
throw new ApprovalInspectionUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
try {
await options.audit.record({
eventId: request.auditEventId,
requestId: request.requestId,
operationId: 'approval.inspect',
projectId: request.projectId,
subject: principal.subject,
authenticationId: principal.authenticationId,
outcome: 'allowed',
reasons: Object.freeze(['human_approval_inspection']),
fence: approvalRead.fence,
occurredAtMs,
});
} catch (error) {
throw new ApprovalInspectionUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
return detail;
},
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,563 @@
import { randomUUID } from 'node:crypto';
import {
approvedActionExecutionEffectiveStatus,
type ApprovedActionExecutionCursor,
type ApprovedActionExecutionRecord,
type ApprovedActionExecutionRepository,
type ApprovedActionExecutionSnapshot,
} from './approvedActionExecution';
import type { ApprovedActionDispatchRecord } from './approvedAction';
const DEFAULT_LEASE_DURATION_MS = 30_000;
const DEFAULT_RETRY_BASE_MS = 1_000;
const DEFAULT_RETRY_MAX_MS = 60_000;
const DEFAULT_BATCH_SIZE = 4;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const RESULT_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
export type ApprovedActionHandlerInspection =
| Readonly<{ status: 'ready'; actionDigest: string }>
| Readonly<{ status: 'retry' | 'blocked'; resultCode: string }>;
export interface ApprovedActionHandlerExecutionContext {
readonly dispatch: Readonly<ApprovedActionDispatchRecord>;
readonly execution: Readonly<ApprovedActionExecutionRecord>;
readonly idempotencyKey: string;
readonly fence: Readonly<{
owner: string;
leaseToken: string;
version: number;
}>;
}
export interface ApprovedActionHandlerResult {
readonly outcome: 'succeeded' | 'failed' | 'indeterminate';
readonly resultCode: string;
readonly resultDigest?: string;
}
export interface ApprovedActionHandler {
readonly actionType: string;
inspect(
dispatch: Readonly<ApprovedActionDispatchRecord>,
): Promise<ApprovedActionHandlerInspection>;
execute(
context: Readonly<ApprovedActionHandlerExecutionContext>,
): Promise<Readonly<ApprovedActionHandlerResult>>;
}
export interface ApprovedActionDispatcherOptions {
readonly owner: string;
readonly leaseDurationMs?: number;
readonly retryBaseMs?: number;
readonly retryMaxMs?: number;
readonly defaultBatchSize?: number;
readonly clock?: () => number;
readonly createId?: () => string;
}
export interface ApprovedActionDispatchBatchSummary {
readonly scanned: number;
readonly claimed: number;
readonly started: number;
readonly succeeded: number;
readonly failed: number;
readonly blocked: number;
readonly retrying: number;
readonly deferred: number;
readonly recoveryRequired: number;
readonly alreadyTerminal: number;
readonly unavailable: number;
readonly truncated: boolean;
readonly nextCursor?: Readonly<ApprovedActionExecutionCursor>;
}
interface MutableSummary {
scanned: number;
claimed: number;
started: number;
succeeded: number;
failed: number;
blocked: number;
retrying: number;
deferred: number;
recoveryRequired: number;
alreadyTerminal: number;
unavailable: number;
truncated: boolean;
nextCursor?: Readonly<ApprovedActionExecutionCursor>;
}
function positiveInteger(
value: number,
label: string,
maximum = Number.MAX_SAFE_INTEGER,
): number {
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
throw new RangeError(`${label} is invalid`);
}
return value;
}
function identifier(value: string, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new TypeError(`${label} is invalid`);
}
return value;
}
function resultCode(value: string): string {
if (typeof value !== 'string' || !RESULT_CODE_PATTERN.test(value)) {
throw new TypeError('Approved Action result code is invalid');
}
return value;
}
function exactKeys(
value: object,
expected: readonly string[],
optional: readonly string[] = [],
): boolean {
const required = new Set(expected);
const allowed = new Set([...expected, ...optional]);
const actual = Object.keys(value);
return (
expected.every((key) => Object.hasOwn(value, key)) &&
actual.every((key) => allowed.has(key)) &&
[...required].length === expected.length
);
}
function sameFence(
snapshot: Readonly<ApprovedActionExecutionSnapshot>,
owner: string,
leaseToken: string,
version: number,
): boolean {
return (
snapshot.execution.status === 'executing' &&
snapshot.execution.leaseOwner === owner &&
snapshot.execution.leaseToken === leaseToken &&
snapshot.execution.version === version
);
}
export class ApprovedActionDispatcher {
readonly #handlers = new Map<string, ApprovedActionHandler>();
readonly #owner: string;
readonly #leaseDurationMs: number;
readonly #retryBaseMs: number;
readonly #retryMaxMs: number;
readonly #defaultBatchSize: number;
readonly #clock: () => number;
readonly #createId: () => string;
constructor(
readonly repository: ApprovedActionExecutionRepository,
handlers: readonly ApprovedActionHandler[],
options: ApprovedActionDispatcherOptions,
) {
if (
!repository ||
typeof repository.listDueExecutions !== 'function' ||
typeof repository.claimExecution !== 'function' ||
typeof repository.startExecution !== 'function' ||
typeof repository.releaseExecutionBeforeStart !== 'function' ||
typeof repository.completeExecution !== 'function' ||
typeof repository.findExecutionByDispatchId !== 'function'
) {
throw new TypeError('Approved Action execution repository is invalid');
}
if (!Array.isArray(handlers) || !options || typeof options !== 'object') {
throw new TypeError('Approved Action dispatcher options are invalid');
}
this.#owner = identifier(options.owner, 'dispatcher owner');
this.#leaseDurationMs = positiveInteger(
options.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS,
'lease duration',
10 * 60 * 1000,
);
this.#retryBaseMs = positiveInteger(
options.retryBaseMs ?? DEFAULT_RETRY_BASE_MS,
'retry base',
);
this.#retryMaxMs = positiveInteger(
options.retryMaxMs ?? DEFAULT_RETRY_MAX_MS,
'retry maximum',
);
if (this.#retryMaxMs < this.#retryBaseMs) {
throw new RangeError('retry maximum precedes retry base');
}
this.#defaultBatchSize = positiveInteger(
options.defaultBatchSize ?? DEFAULT_BATCH_SIZE,
'default batch size',
64,
);
this.#clock = options.clock ?? Date.now;
this.#createId = options.createId ?? randomUUID;
for (const handler of handlers) {
if (
!handler ||
typeof handler !== 'object' ||
typeof handler.actionType !== 'string' ||
handler.actionType.length < 1 ||
handler.actionType.length > 128 ||
typeof handler.inspect !== 'function' ||
typeof handler.execute !== 'function'
) {
throw new TypeError('Approved Action handler is invalid');
}
if (this.#handlers.has(handler.actionType)) {
throw new TypeError('Approved Action handler is duplicated');
}
this.#handlers.set(handler.actionType, handler);
}
}
async dispatchBatch(
options: Readonly<{
cursor?: ApprovedActionExecutionCursor;
limit?: number;
}> = {},
): Promise<Readonly<ApprovedActionDispatchBatchSummary>> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
!exactKeys(options, [], ['cursor', 'limit'])
) {
throw new TypeError('Approved Action dispatch batch is invalid');
}
const limit = positiveInteger(
options.limit ?? this.#defaultBatchSize,
'batch size',
64,
);
const page = await this.repository.listDueExecutions({
nowMs: this.#now(),
limit,
actionTypes: Object.freeze([...this.#handlers.keys()].sort()),
...(options.cursor ? { cursor: options.cursor } : {}),
});
const summary: MutableSummary = {
scanned: page.executions.length,
claimed: 0,
started: 0,
succeeded: 0,
failed: 0,
blocked: 0,
retrying: 0,
deferred: 0,
recoveryRequired: 0,
alreadyTerminal: 0,
unavailable: 0,
truncated: page.truncated,
...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
};
for (const candidate of page.executions) {
await this.#dispatchOne(candidate.dispatch.id, summary);
}
return Object.freeze({ ...summary });
}
async #dispatchOne(
dispatchId: string,
summary: MutableSummary,
): Promise<void> {
const leaseToken = this.#id('lease token');
let claim;
try {
claim = await this.repository.claimExecution({
dispatchId,
owner: this.#owner,
leaseToken,
nowMs: this.#now(),
leaseDurationMs: this.#leaseDurationMs,
});
} catch {
summary.unavailable += 1;
return;
}
if (claim.status === 'not_found') {
summary.unavailable += 1;
return;
}
if (claim.status !== 'claimed') {
if (claim.status === 'recovery_required') {
summary.recoveryRequired += 1;
} else if (
claim.status === 'succeeded' ||
claim.status === 'failed' ||
claim.status === 'blocked'
) {
summary.alreadyTerminal += 1;
} else {
summary.deferred += 1;
}
return;
}
summary.claimed += 1;
const handler = this.#handlers.get(
claim.snapshot.dispatch.action.actionType,
);
if (!handler) {
await this.#release(
claim.snapshot.execution,
'handler_unavailable',
false,
summary,
);
return;
}
let inspection: ApprovedActionHandlerInspection;
try {
inspection = await handler.inspect(claim.snapshot.dispatch);
this.#assertInspection(inspection);
} catch {
await this.#release(
claim.snapshot.execution,
'handler_inspection_failed',
true,
summary,
);
return;
}
if (inspection.status !== 'ready') {
await this.#release(
claim.snapshot.execution,
inspection.resultCode,
inspection.status === 'retry',
summary,
);
return;
}
if (
inspection.actionDigest !== claim.snapshot.dispatch.action.actionDigest
) {
await this.#release(
claim.snapshot.execution,
'action_digest_mismatch',
false,
summary,
);
return;
}
let started: Readonly<ApprovedActionExecutionSnapshot>;
try {
started = await this.repository.startExecution({
dispatchId,
approvalRequestId: claim.snapshot.dispatch.approvalRequestId,
actionDigest: inspection.actionDigest,
owner: this.#owner,
leaseToken,
expectedVersion: claim.snapshot.execution.version,
startedAtMs: this.#now(),
});
} catch {
const converged = await this.#find(dispatchId);
if (
!converged ||
!sameFence(
converged,
this.#owner,
leaseToken,
claim.snapshot.execution.version + 1,
)
) {
summary.unavailable += 1;
if (
converged?.execution.status === 'executing' ||
(converged &&
approvedActionExecutionEffectiveStatus(
converged.execution,
this.#now(),
) === 'recovery_required')
) {
summary.recoveryRequired += 1;
}
return;
}
started = converged;
}
summary.started += 1;
let result: Readonly<ApprovedActionHandlerResult>;
try {
result = await handler.execute(
Object.freeze({
dispatch: started.dispatch,
execution: started.execution,
idempotencyKey: started.dispatch.id,
fence: Object.freeze({
owner: this.#owner,
leaseToken,
version: started.execution.version,
}),
}),
);
this.#assertResult(result);
} catch {
result = Object.freeze({
outcome: 'indeterminate',
resultCode: 'handler_failed_after_start',
});
}
const resultMutationId = this.#id('result mutation id');
try {
const completed = await this.repository.completeExecution({
dispatchId,
owner: this.#owner,
leaseToken,
expectedVersion: started.execution.version,
resultMutationId,
outcome: result.outcome,
resultCode: result.resultCode,
...(result.resultDigest === undefined
? {}
: { resultDigest: result.resultDigest }),
completedAtMs: this.#now(),
});
this.#countCompletion(completed.execution, summary);
} catch {
const converged = await this.#find(dispatchId);
if (
converged &&
converged.execution.resultMutationId === resultMutationId &&
converged.execution.resultCode === result.resultCode &&
converged.execution.resultDigest === (result.resultDigest ?? null)
) {
this.#countCompletion(converged.execution, summary);
return;
}
summary.unavailable += 1;
summary.recoveryRequired += 1;
}
}
async #release(
execution: Readonly<ApprovedActionExecutionRecord>,
code: string,
retry: boolean,
summary: MutableSummary,
): Promise<void> {
const atMs = this.#now();
try {
const released = await this.repository.releaseExecutionBeforeStart({
dispatchId: execution.dispatchId,
owner: this.#owner,
leaseToken: execution.leaseToken!,
expectedVersion: execution.version,
resultMutationId: this.#id('result mutation id'),
resultCode: resultCode(code),
atMs,
...(retry
? { retryAtMs: this.#nextRetryAt(atMs, execution.attemptCount) }
: {}),
});
if (released.execution.status === 'retry_wait') summary.retrying += 1;
else summary.blocked += 1;
} catch {
summary.unavailable += 1;
}
}
async #find(
dispatchId: string,
): Promise<Readonly<ApprovedActionExecutionSnapshot> | null> {
try {
return await this.repository.findExecutionByDispatchId(dispatchId);
} catch {
return null;
}
}
#countCompletion(
execution: Readonly<ApprovedActionExecutionRecord>,
summary: MutableSummary,
): void {
if (execution.status === 'succeeded') summary.succeeded += 1;
else if (execution.status === 'failed') summary.failed += 1;
else summary.blocked += 1;
}
#assertInspection(
value: unknown,
): asserts value is ApprovedActionHandlerInspection {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Approved Action inspection is invalid');
}
if (
'status' in value &&
value.status === 'ready' &&
exactKeys(value, ['status', 'actionDigest']) &&
'actionDigest' in value &&
typeof value.actionDigest === 'string' &&
DIGEST_PATTERN.test(value.actionDigest)
) {
return;
}
if (
'status' in value &&
(value.status === 'retry' || value.status === 'blocked') &&
exactKeys(value, ['status', 'resultCode']) &&
'resultCode' in value &&
typeof value.resultCode === 'string'
) {
resultCode(value.resultCode);
return;
}
throw new TypeError('Approved Action inspection is invalid');
}
#assertResult(value: unknown): asserts value is ApprovedActionHandlerResult {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['outcome', 'resultCode'], ['resultDigest']) ||
!('outcome' in value) ||
!['succeeded', 'failed', 'indeterminate'].includes(
value.outcome as string,
) ||
!('resultCode' in value) ||
typeof value.resultCode !== 'string'
) {
throw new TypeError('Approved Action result is invalid');
}
resultCode(value.resultCode);
const digest =
'resultDigest' in value ? (value.resultDigest as unknown) : undefined;
if (
(value.outcome === 'succeeded' &&
(typeof digest !== 'string' || !DIGEST_PATTERN.test(digest))) ||
(value.outcome !== 'succeeded' && digest !== undefined)
) {
throw new TypeError('Approved Action result digest is invalid');
}
}
#nextRetryAt(atMs: number, attemptCount: number): number {
const exponent = Math.max(0, Math.min(attemptCount - 1, 30));
const delay = Math.min(
this.#retryMaxMs,
this.#retryBaseMs * 2 ** exponent,
);
return Math.min(Number.MAX_SAFE_INTEGER, atMs + delay);
}
#now(): number {
const nowMs = this.#clock();
if (!Number.isSafeInteger(nowMs) || nowMs < 0) {
throw new RangeError('Approved Action clock is invalid');
}
return nowMs;
}
#id(label: string): string {
return identifier(this.#createId(), label);
}
}
@@ -0,0 +1,958 @@
import { createHash } from 'node:crypto';
import {
approvedActionDispatchDigest,
normalizeApprovedActionDispatchRecord,
type ApprovedActionDispatchRecord,
} from './approvedAction';
export const APPROVED_ACTION_EXECUTION_SCHEMA =
'qinglong/approved-action-execution@v1' as const;
export const APPROVED_ACTION_EXECUTION_STATUSES = [
'pending',
'leased',
'executing',
'retry_wait',
'succeeded',
'failed',
'blocked',
] as const;
export type ApprovedActionExecutionStatus =
(typeof APPROVED_ACTION_EXECUTION_STATUSES)[number];
export type ApprovedActionExecutionEffectiveStatus =
| ApprovedActionExecutionStatus
| 'recovery_required';
export interface ApprovedActionExecutionRecord {
readonly schema: typeof APPROVED_ACTION_EXECUTION_SCHEMA;
readonly dispatchId: string;
readonly dispatchDigest: string;
readonly projectId: string;
readonly status: ApprovedActionExecutionStatus;
readonly version: number;
readonly attemptCount: number;
readonly maxAttempts: number;
readonly eligibleAtMs: number | null;
readonly nextAttemptAtMs: number | null;
readonly leaseOwner: string | null;
readonly leaseToken: string | null;
readonly leaseExpiresAtMs: number | null;
readonly startedAtMs: number | null;
readonly resultMutationId: string | null;
readonly resultCode: string | null;
readonly resultDigest: string | null;
readonly completedAtMs: number | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
readonly executionDigest: string;
}
export interface ApprovedActionExecutionSnapshot {
readonly dispatch: Readonly<ApprovedActionDispatchRecord>;
readonly execution: Readonly<ApprovedActionExecutionRecord>;
}
export interface ApprovedActionExecutionCursor {
readonly eligibleAtMs: number;
readonly dispatchId: string;
}
export interface ListDueApprovedActionExecutionsQuery {
readonly nowMs: number;
readonly limit: number;
readonly actionTypes: readonly string[];
readonly cursor?: ApprovedActionExecutionCursor;
}
export interface ListDueApprovedActionExecutionsResult {
readonly executions: readonly Readonly<ApprovedActionExecutionSnapshot>[];
readonly truncated: boolean;
readonly nextCursor?: Readonly<ApprovedActionExecutionCursor>;
}
export interface ClaimApprovedActionExecutionCommand {
readonly dispatchId: string;
readonly owner: string;
readonly leaseToken: string;
readonly nowMs: number;
readonly leaseDurationMs: number;
}
export type ClaimApprovedActionExecutionResult =
| Readonly<{
status: 'claimed';
snapshot: Readonly<ApprovedActionExecutionSnapshot>;
}>
| Readonly<{ status: 'not_found' }>
| Readonly<{
status:
| 'not_due'
| 'leased'
| 'executing'
| 'recovery_required'
| 'succeeded'
| 'failed'
| 'blocked';
snapshot: Readonly<ApprovedActionExecutionSnapshot>;
}>;
export interface StartApprovedActionExecutionCommand {
readonly dispatchId: string;
readonly approvalRequestId: string;
readonly actionDigest: string;
readonly owner: string;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly startedAtMs: number;
}
export interface RenewApprovedActionExecutionCommand {
readonly dispatchId: string;
readonly owner: string;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly nowMs: number;
readonly leaseDurationMs: number;
}
export interface ReleaseApprovedActionExecutionBeforeStartCommand {
readonly dispatchId: string;
readonly owner: string;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly resultMutationId: string;
readonly resultCode: string;
readonly atMs: number;
readonly retryAtMs?: number;
}
export interface CompleteApprovedActionExecutionCommand {
readonly dispatchId: string;
readonly owner: string;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly resultMutationId: string;
readonly outcome: 'succeeded' | 'failed' | 'indeterminate';
readonly resultCode: string;
readonly resultDigest?: string;
readonly completedAtMs: number;
}
export interface ApprovedActionExecutionRepository {
findExecutionByDispatchId(
dispatchId: string,
): Promise<Readonly<ApprovedActionExecutionSnapshot> | null>;
listDueExecutions(
query: ListDueApprovedActionExecutionsQuery,
): Promise<ListDueApprovedActionExecutionsResult>;
claimExecution(
command: ClaimApprovedActionExecutionCommand,
): Promise<ClaimApprovedActionExecutionResult>;
startExecution(
command: StartApprovedActionExecutionCommand,
): Promise<Readonly<ApprovedActionExecutionSnapshot>>;
renewExecution(
command: RenewApprovedActionExecutionCommand,
): Promise<Readonly<ApprovedActionExecutionSnapshot>>;
releaseExecutionBeforeStart(
command: ReleaseApprovedActionExecutionBeforeStartCommand,
): Promise<Readonly<ApprovedActionExecutionSnapshot>>;
completeExecution(
command: CompleteApprovedActionExecutionCommand,
): Promise<Readonly<ApprovedActionExecutionSnapshot>>;
}
export const DEFAULT_APPROVED_ACTION_MAX_ATTEMPTS = 5;
export const MAX_APPROVED_ACTION_ATTEMPTS = 16;
export const MAX_APPROVED_ACTION_EXECUTION_VERSION = 2_147_483_647;
export const MAX_APPROVED_ACTION_LEASE_ID_LENGTH = 128;
export const MAX_APPROVED_ACTION_RESULT_CODE_LENGTH = 64;
export const MAX_APPROVED_ACTION_EXECUTION_PAGE_SIZE = 64;
export const MAX_APPROVED_ACTION_LEASE_DURATION_MS = 10 * 60 * 1000;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const RESULT_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
export class InvalidApprovedActionExecutionError extends TypeError {
readonly code = 'APPROVED_ACTION_EXECUTION_INVALID';
constructor(message: string) {
super(`Approved Action execution is invalid: ${message}`);
this.name = 'InvalidApprovedActionExecutionError';
}
}
export class ApprovedActionExecutionFenceConflictError extends Error {
readonly code = 'APPROVED_ACTION_EXECUTION_FENCE_CONFLICT';
constructor() {
super('Approved Action execution fence changed');
this.name = 'ApprovedActionExecutionFenceConflictError';
}
}
export class ApprovedActionExecutionStateConflictError extends Error {
readonly code = 'APPROVED_ACTION_EXECUTION_STATE_CONFLICT';
constructor() {
super('Approved Action execution is not in the required state');
this.name = 'ApprovedActionExecutionStateConflictError';
}
}
export class ApprovedActionExecutionBindingConflictError extends Error {
readonly code = 'APPROVED_ACTION_EXECUTION_BINDING_CONFLICT';
constructor() {
super('Approved Action execution does not match its dispatch');
this.name = 'ApprovedActionExecutionBindingConflictError';
}
}
export class ApprovedActionExecutionUnavailableError extends Error {
readonly code = 'APPROVED_ACTION_EXECUTION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Approved Action execution authority is unavailable', options);
this.name = 'ApprovedActionExecutionUnavailableError';
}
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidApprovedActionExecutionError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
optional: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const required = [...expected].sort();
const allowed = new Set([...expected, ...optional]);
if (
required.some((key) => !Object.hasOwn(value, key)) ||
actual.some((key) => !allowed.has(key))
) {
throw new InvalidApprovedActionExecutionError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidApprovedActionExecutionError(`${label} is invalid`);
}
return value;
}
function resultCode(value: unknown): string {
if (typeof value !== 'string' || !RESULT_CODE_PATTERN.test(value)) {
throw new InvalidApprovedActionExecutionError('result code is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidApprovedActionExecutionError(`${label} is invalid`);
}
return value;
}
function integer(
value: unknown,
label: string,
minimum: number,
maximum: number,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) {
throw new InvalidApprovedActionExecutionError(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
return integer(value, label, 0, Number.MAX_SAFE_INTEGER);
}
function nullableTimestamp(value: unknown, label: string): number | null {
return value === null ? null : timestamp(value, label);
}
function nullableIdentifier(value: unknown, label: string): string | null {
return value === null ? null : identifier(value, label);
}
function nullableResultCode(value: unknown): string | null {
return value === null ? null : resultCode(value);
}
function nullableDigest(value: unknown, label: string): string | null {
return value === null ? null : digest(value, label);
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function withoutExecutionDigest(
value: Omit<ApprovedActionExecutionRecord, 'executionDigest'>,
): Omit<ApprovedActionExecutionRecord, 'executionDigest'> {
return Object.freeze(value);
}
function withExecutionDigest(
value: Omit<ApprovedActionExecutionRecord, 'executionDigest'>,
): Readonly<ApprovedActionExecutionRecord> {
const normalized = withoutExecutionDigest(value);
return Object.freeze({
...normalized,
executionDigest: contractDigest(
'qinglong/approved-action-execution-digest@v1',
normalized,
),
});
}
function executionWithoutDigest(
value: Readonly<ApprovedActionExecutionRecord>,
): Omit<ApprovedActionExecutionRecord, 'executionDigest'> {
const { executionDigest: _executionDigest, ...record } = value;
return record;
}
function sameLease(
record: Readonly<ApprovedActionExecutionRecord>,
owner: string,
leaseToken: string,
expectedVersion: number,
): boolean {
return (
record.leaseOwner === owner &&
record.leaseToken === leaseToken &&
record.version === expectedVersion
);
}
export function createApprovedActionExecution(
dispatchValue: ApprovedActionDispatchRecord,
maxAttempts = DEFAULT_APPROVED_ACTION_MAX_ATTEMPTS,
): Readonly<ApprovedActionExecutionRecord> {
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
return withExecutionDigest({
schema: APPROVED_ACTION_EXECUTION_SCHEMA,
dispatchId: dispatch.id,
dispatchDigest: approvedActionDispatchDigest(dispatch),
projectId: dispatch.projectId,
status: 'pending',
version: 0,
attemptCount: 0,
maxAttempts: integer(
maxAttempts,
'maximum attempts',
1,
MAX_APPROVED_ACTION_ATTEMPTS,
),
eligibleAtMs: dispatch.createdAtMs,
nextAttemptAtMs: null,
leaseOwner: null,
leaseToken: null,
leaseExpiresAtMs: null,
startedAtMs: null,
resultMutationId: null,
resultCode: null,
resultDigest: null,
completedAtMs: null,
createdAtMs: dispatch.createdAtMs,
updatedAtMs: dispatch.createdAtMs,
});
}
export function normalizeApprovedActionExecutionRecord(
value: ApprovedActionExecutionRecord,
): Readonly<ApprovedActionExecutionRecord> {
const record = dataRecord(value, 'record');
exactKeys(
record,
[
'schema',
'dispatchId',
'dispatchDigest',
'projectId',
'status',
'version',
'attemptCount',
'maxAttempts',
'eligibleAtMs',
'nextAttemptAtMs',
'leaseOwner',
'leaseToken',
'leaseExpiresAtMs',
'startedAtMs',
'resultMutationId',
'resultCode',
'resultDigest',
'completedAtMs',
'createdAtMs',
'updatedAtMs',
'executionDigest',
],
[],
'record',
);
if (
value.schema !== APPROVED_ACTION_EXECUTION_SCHEMA ||
!APPROVED_ACTION_EXECUTION_STATUSES.includes(value.status)
) {
throw new InvalidApprovedActionExecutionError(
'schema or status is invalid',
);
}
const normalized = {
schema: APPROVED_ACTION_EXECUTION_SCHEMA,
dispatchId: identifier(value.dispatchId, 'dispatch id'),
dispatchDigest: digest(value.dispatchDigest, 'dispatch digest'),
projectId: identifier(value.projectId, 'project id'),
status: value.status,
version: integer(
value.version,
'version',
0,
MAX_APPROVED_ACTION_EXECUTION_VERSION,
),
attemptCount: integer(
value.attemptCount,
'attempt count',
0,
MAX_APPROVED_ACTION_ATTEMPTS,
),
maxAttempts: integer(
value.maxAttempts,
'maximum attempts',
1,
MAX_APPROVED_ACTION_ATTEMPTS,
),
eligibleAtMs: nullableTimestamp(value.eligibleAtMs, 'eligible time'),
nextAttemptAtMs: nullableTimestamp(
value.nextAttemptAtMs,
'next attempt time',
),
leaseOwner: nullableIdentifier(value.leaseOwner, 'lease owner'),
leaseToken: nullableIdentifier(value.leaseToken, 'lease token'),
leaseExpiresAtMs: nullableTimestamp(
value.leaseExpiresAtMs,
'lease expiry',
),
startedAtMs: nullableTimestamp(value.startedAtMs, 'start time'),
resultMutationId: nullableIdentifier(
value.resultMutationId,
'result mutation id',
),
resultCode: nullableResultCode(value.resultCode),
resultDigest: nullableDigest(value.resultDigest, 'result digest'),
completedAtMs: nullableTimestamp(value.completedAtMs, 'completion time'),
createdAtMs: timestamp(value.createdAtMs, 'creation time'),
updatedAtMs: timestamp(value.updatedAtMs, 'update time'),
} satisfies Omit<ApprovedActionExecutionRecord, 'executionDigest'>;
const executionDigest = digest(value.executionDigest, 'execution digest');
if (
normalized.attemptCount > normalized.maxAttempts ||
normalized.updatedAtMs < normalized.createdAtMs
) {
throw new InvalidApprovedActionExecutionError(
'attempt or timestamp range is invalid',
);
}
const leaseValues = [
normalized.leaseOwner,
normalized.leaseToken,
normalized.leaseExpiresAtMs,
];
const hasLease = leaseValues.every((entry) => entry !== null);
if (
leaseValues.some((entry) => entry !== null) !== hasLease ||
(hasLease &&
(normalized.leaseExpiresAtMs! <= normalized.updatedAtMs ||
normalized.leaseExpiresAtMs! - normalized.updatedAtMs >
MAX_APPROVED_ACTION_LEASE_DURATION_MS))
) {
throw new InvalidApprovedActionExecutionError('lease tuple is invalid');
}
const resultValues = [
normalized.resultMutationId,
normalized.resultCode,
];
const hasResult = resultValues.every((entry) => entry !== null);
if (resultValues.some((entry) => entry !== null) !== hasResult) {
throw new InvalidApprovedActionExecutionError('result tuple is invalid');
}
const terminal = ['succeeded', 'failed', 'blocked'].includes(
normalized.status,
);
if (
(normalized.status === 'pending' &&
(normalized.version !== 0 ||
normalized.attemptCount !== 0 ||
normalized.eligibleAtMs === null ||
normalized.nextAttemptAtMs !== null ||
hasLease ||
normalized.startedAtMs !== null ||
hasResult ||
normalized.resultDigest !== null ||
normalized.completedAtMs !== null)) ||
(normalized.status === 'leased' &&
(!hasLease ||
normalized.attemptCount < 1 ||
normalized.eligibleAtMs !== normalized.leaseExpiresAtMs ||
normalized.nextAttemptAtMs !== null ||
normalized.startedAtMs !== null ||
hasResult ||
normalized.resultDigest !== null ||
normalized.completedAtMs !== null)) ||
(normalized.status === 'executing' &&
(!hasLease ||
normalized.attemptCount < 1 ||
normalized.eligibleAtMs !== null ||
normalized.nextAttemptAtMs !== null ||
normalized.startedAtMs === null ||
hasResult ||
normalized.resultDigest !== null ||
normalized.completedAtMs !== null)) ||
(normalized.status === 'retry_wait' &&
(hasLease ||
normalized.attemptCount < 1 ||
normalized.attemptCount >= normalized.maxAttempts ||
normalized.eligibleAtMs === null ||
normalized.eligibleAtMs !== normalized.nextAttemptAtMs ||
normalized.startedAtMs !== null ||
!hasResult ||
normalized.resultDigest !== null ||
normalized.completedAtMs !== null)) ||
(terminal &&
(hasLease ||
normalized.eligibleAtMs !== null ||
normalized.nextAttemptAtMs !== null ||
!hasResult ||
normalized.completedAtMs === null))
) {
throw new InvalidApprovedActionExecutionError(
`${normalized.status} tuple is invalid`,
);
}
if (
normalized.status === 'succeeded' &&
(normalized.startedAtMs === null || normalized.resultDigest === null)
) {
throw new InvalidApprovedActionExecutionError(
'successful execution has no start barrier or result digest',
);
}
if (
normalized.status === 'failed' &&
normalized.startedAtMs === null
) {
throw new InvalidApprovedActionExecutionError(
'failed execution has no start barrier',
);
}
if (
normalized.startedAtMs !== null &&
(normalized.startedAtMs < normalized.createdAtMs ||
normalized.startedAtMs > normalized.updatedAtMs)
) {
throw new InvalidApprovedActionExecutionError(
'start timestamp is invalid',
);
}
if (
normalized.completedAtMs !== null &&
(normalized.completedAtMs <
(normalized.startedAtMs ?? normalized.createdAtMs) ||
normalized.completedAtMs !== normalized.updatedAtMs)
) {
throw new InvalidApprovedActionExecutionError(
'completion timestamp is invalid',
);
}
if (
executionDigest !==
contractDigest(
'qinglong/approved-action-execution-digest@v1',
normalized,
)
) {
throw new InvalidApprovedActionExecutionError(
'execution digest does not match the record',
);
}
return Object.freeze({ ...normalized, executionDigest });
}
export function normalizeApprovedActionExecutionSnapshot(
value: ApprovedActionExecutionSnapshot,
): Readonly<ApprovedActionExecutionSnapshot> {
const snapshot = dataRecord(value, 'snapshot');
exactKeys(snapshot, ['dispatch', 'execution'], [], 'snapshot');
const dispatch = normalizeApprovedActionDispatchRecord(value.dispatch);
const execution = normalizeApprovedActionExecutionRecord(value.execution);
if (
execution.dispatchId !== dispatch.id ||
execution.dispatchDigest !== approvedActionDispatchDigest(dispatch) ||
execution.projectId !== dispatch.projectId
) {
throw new ApprovedActionExecutionBindingConflictError();
}
return Object.freeze({ dispatch, execution });
}
export function normalizeApprovedActionExecutionCursor(
value: ApprovedActionExecutionCursor,
): Readonly<ApprovedActionExecutionCursor> {
const cursor = dataRecord(value, 'cursor');
exactKeys(cursor, ['eligibleAtMs', 'dispatchId'], [], 'cursor');
return Object.freeze({
eligibleAtMs: timestamp(value.eligibleAtMs, 'cursor eligible time'),
dispatchId: identifier(value.dispatchId, 'cursor dispatch id'),
});
}
export function approvedActionExecutionEffectiveStatus(
recordValue: ApprovedActionExecutionRecord,
nowMsValue: number,
): ApprovedActionExecutionEffectiveStatus {
const record = normalizeApprovedActionExecutionRecord(recordValue);
const nowMs = timestamp(nowMsValue, 'observation time');
if (
record.status === 'executing' &&
record.leaseExpiresAtMs !== null &&
nowMs >= record.leaseExpiresAtMs
) {
return 'recovery_required';
}
return record.status;
}
export function claimApprovedActionExecution(
recordValue: ApprovedActionExecutionRecord,
commandValue: Omit<ClaimApprovedActionExecutionCommand, 'dispatchId'>,
): Readonly<ApprovedActionExecutionRecord> {
const record = normalizeApprovedActionExecutionRecord(recordValue);
const command = dataRecord(commandValue, 'claim command');
exactKeys(
command,
['owner', 'leaseToken', 'nowMs', 'leaseDurationMs'],
[],
'claim command',
);
const owner = identifier(commandValue.owner, 'lease owner');
const leaseToken = identifier(commandValue.leaseToken, 'lease token');
const nowMs = timestamp(commandValue.nowMs, 'claim time');
const leaseDurationMs = integer(
commandValue.leaseDurationMs,
'lease duration',
1,
MAX_APPROVED_ACTION_LEASE_DURATION_MS,
);
const due =
(record.status === 'pending' || record.status === 'retry_wait') &&
record.eligibleAtMs !== null &&
record.eligibleAtMs <= nowMs;
const reclaimable =
record.status === 'leased' &&
record.leaseExpiresAtMs !== null &&
record.leaseExpiresAtMs <= nowMs;
if (!due && !reclaimable) {
throw new ApprovedActionExecutionStateConflictError();
}
if (record.attemptCount >= record.maxAttempts) {
throw new ApprovedActionExecutionStateConflictError();
}
const leaseExpiresAtMs = Math.min(
Number.MAX_SAFE_INTEGER,
nowMs + leaseDurationMs,
);
return withExecutionDigest({
...executionWithoutDigest(record),
status: 'leased',
version: record.version + 1,
attemptCount: record.attemptCount + 1,
eligibleAtMs: leaseExpiresAtMs,
nextAttemptAtMs: null,
leaseOwner: owner,
leaseToken,
leaseExpiresAtMs,
startedAtMs: null,
resultMutationId: null,
resultCode: null,
resultDigest: null,
completedAtMs: null,
updatedAtMs: nowMs,
});
}
export function startApprovedActionExecution(
snapshotValue: ApprovedActionExecutionSnapshot,
commandValue: StartApprovedActionExecutionCommand,
): Readonly<ApprovedActionExecutionRecord> {
const snapshot = normalizeApprovedActionExecutionSnapshot(snapshotValue);
const command = dataRecord(commandValue, 'start command');
exactKeys(
command,
[
'dispatchId',
'approvalRequestId',
'actionDigest',
'owner',
'leaseToken',
'expectedVersion',
'startedAtMs',
],
[],
'start command',
);
const dispatchId = identifier(commandValue.dispatchId, 'dispatch id');
const approvalRequestId = identifier(
commandValue.approvalRequestId,
'approval request id',
);
const actionDigest = digest(commandValue.actionDigest, 'action digest');
const owner = identifier(commandValue.owner, 'lease owner');
const leaseToken = identifier(commandValue.leaseToken, 'lease token');
const expectedVersion = integer(
commandValue.expectedVersion,
'expected version',
0,
MAX_APPROVED_ACTION_EXECUTION_VERSION,
);
const startedAtMs = timestamp(commandValue.startedAtMs, 'start time');
if (
snapshot.execution.status !== 'leased' ||
!sameLease(snapshot.execution, owner, leaseToken, expectedVersion) ||
dispatchId !== snapshot.dispatch.id ||
approvalRequestId !== snapshot.dispatch.approvalRequestId ||
actionDigest !== snapshot.dispatch.action.actionDigest ||
snapshot.execution.leaseExpiresAtMs === null ||
startedAtMs < snapshot.execution.updatedAtMs ||
startedAtMs >= snapshot.execution.leaseExpiresAtMs
) {
throw new ApprovedActionExecutionFenceConflictError();
}
return withExecutionDigest({
...executionWithoutDigest(snapshot.execution),
status: 'executing',
version: snapshot.execution.version + 1,
eligibleAtMs: null,
startedAtMs,
updatedAtMs: startedAtMs,
});
}
export function renewApprovedActionExecution(
recordValue: ApprovedActionExecutionRecord,
commandValue: Omit<RenewApprovedActionExecutionCommand, 'dispatchId'>,
): Readonly<ApprovedActionExecutionRecord> {
const record = normalizeApprovedActionExecutionRecord(recordValue);
const command = dataRecord(commandValue, 'renew command');
exactKeys(
command,
['owner', 'leaseToken', 'expectedVersion', 'nowMs', 'leaseDurationMs'],
[],
'renew command',
);
const owner = identifier(commandValue.owner, 'lease owner');
const leaseToken = identifier(commandValue.leaseToken, 'lease token');
const expectedVersion = integer(
commandValue.expectedVersion,
'expected version',
0,
MAX_APPROVED_ACTION_EXECUTION_VERSION,
);
const nowMs = timestamp(commandValue.nowMs, 'renewal time');
const leaseDurationMs = integer(
commandValue.leaseDurationMs,
'lease duration',
1,
MAX_APPROVED_ACTION_LEASE_DURATION_MS,
);
if (
(record.status !== 'leased' && record.status !== 'executing') ||
!sameLease(record, owner, leaseToken, expectedVersion) ||
record.leaseExpiresAtMs === null ||
nowMs < record.updatedAtMs ||
nowMs >= record.leaseExpiresAtMs
) {
throw new ApprovedActionExecutionFenceConflictError();
}
const leaseExpiresAtMs = Math.min(
Number.MAX_SAFE_INTEGER,
nowMs + leaseDurationMs,
);
return withExecutionDigest({
...executionWithoutDigest(record),
version: record.version + 1,
eligibleAtMs:
record.status === 'leased' ? leaseExpiresAtMs : record.eligibleAtMs,
leaseExpiresAtMs,
updatedAtMs: nowMs,
});
}
export function releaseApprovedActionExecutionBeforeStart(
recordValue: ApprovedActionExecutionRecord,
commandValue: Omit<
ReleaseApprovedActionExecutionBeforeStartCommand,
'dispatchId'
>,
): Readonly<ApprovedActionExecutionRecord> {
const record = normalizeApprovedActionExecutionRecord(recordValue);
const command = dataRecord(commandValue, 'release command');
exactKeys(
command,
[
'owner',
'leaseToken',
'expectedVersion',
'resultMutationId',
'resultCode',
'atMs',
],
['retryAtMs'],
'release command',
);
const owner = identifier(commandValue.owner, 'lease owner');
const leaseToken = identifier(commandValue.leaseToken, 'lease token');
const expectedVersion = integer(
commandValue.expectedVersion,
'expected version',
0,
MAX_APPROVED_ACTION_EXECUTION_VERSION,
);
const resultMutationId = identifier(
commandValue.resultMutationId,
'result mutation id',
);
const normalizedResultCode = resultCode(commandValue.resultCode);
const atMs = timestamp(commandValue.atMs, 'release time');
const retryAtMs =
commandValue.retryAtMs === undefined
? undefined
: timestamp(commandValue.retryAtMs, 'retry time');
if (
record.status !== 'leased' ||
!sameLease(record, owner, leaseToken, expectedVersion) ||
record.startedAtMs !== null ||
atMs < record.updatedAtMs ||
(retryAtMs !== undefined && retryAtMs <= atMs)
) {
throw new ApprovedActionExecutionFenceConflictError();
}
const retry =
retryAtMs !== undefined && record.attemptCount < record.maxAttempts;
return withExecutionDigest({
...executionWithoutDigest(record),
status: retry ? 'retry_wait' : 'blocked',
version: record.version + 1,
eligibleAtMs: retry ? retryAtMs! : null,
nextAttemptAtMs: retry ? retryAtMs! : null,
leaseOwner: null,
leaseToken: null,
leaseExpiresAtMs: null,
resultMutationId,
resultCode: normalizedResultCode,
resultDigest: null,
completedAtMs: retry ? null : atMs,
updatedAtMs: atMs,
});
}
export function completeApprovedActionExecution(
recordValue: ApprovedActionExecutionRecord,
commandValue: Omit<CompleteApprovedActionExecutionCommand, 'dispatchId'>,
): Readonly<ApprovedActionExecutionRecord> {
const record = normalizeApprovedActionExecutionRecord(recordValue);
const command = dataRecord(commandValue, 'complete command');
exactKeys(
command,
[
'owner',
'leaseToken',
'expectedVersion',
'resultMutationId',
'outcome',
'resultCode',
'completedAtMs',
],
['resultDigest'],
'complete command',
);
const owner = identifier(commandValue.owner, 'lease owner');
const leaseToken = identifier(commandValue.leaseToken, 'lease token');
const expectedVersion = integer(
commandValue.expectedVersion,
'expected version',
0,
MAX_APPROVED_ACTION_EXECUTION_VERSION,
);
const resultMutationId = identifier(
commandValue.resultMutationId,
'result mutation id',
);
const normalizedResultCode = resultCode(commandValue.resultCode);
const completedAtMs = timestamp(commandValue.completedAtMs, 'completion time');
const resultDigestValue =
commandValue.resultDigest === undefined
? null
: digest(commandValue.resultDigest, 'result digest');
if (
!['succeeded', 'failed', 'indeterminate'].includes(commandValue.outcome) ||
record.status !== 'executing' ||
!sameLease(record, owner, leaseToken, expectedVersion) ||
record.startedAtMs === null ||
completedAtMs < record.updatedAtMs ||
(commandValue.outcome === 'succeeded' && resultDigestValue === null) ||
(commandValue.outcome !== 'succeeded' && resultDigestValue !== null)
) {
throw new ApprovedActionExecutionFenceConflictError();
}
const status =
commandValue.outcome === 'indeterminate'
? 'blocked'
: commandValue.outcome;
return withExecutionDigest({
...executionWithoutDigest(record),
status,
version: record.version + 1,
eligibleAtMs: null,
nextAttemptAtMs: null,
leaseOwner: null,
leaseToken: null,
leaseExpiresAtMs: null,
resultMutationId,
resultCode: normalizedResultCode,
resultDigest: resultDigestValue,
completedAtMs,
updatedAtMs: completedAtMs,
});
}
@@ -0,0 +1,199 @@
export type DeploymentProfile =
| 'edge'
| 'standalone'
| 'cluster-control'
| 'worker';
export type ClusterControlActivationState =
| 'disabled'
| 'schema_ready'
| 'reconciled'
| 'active'
| 'failed'
| 'stopped';
export interface ClusterControlReadinessEvidence {
readonly contractName: string;
readonly contractVersion: number;
readonly serverMajor: number;
readonly migrationIds: readonly string[];
}
export interface ClusterControlReadinessProbe {
assertReady(): Promise<ClusterControlReadinessEvidence>;
}
export interface ClusterControlStartupRecoverySummary {
readonly safe: boolean;
readonly remaining: number;
readonly failed: number;
}
export type ClusterControlStopResult = 'stopped' | 'timed_out';
export type ClusterControlAdmissionDisposer = () => void | Promise<void>;
export interface ClusterControlActivationStack {
reconcile(): Promise<ClusterControlStartupRecoverySummary>;
startLifecycles(): Promise<boolean>;
installAdmission(): ClusterControlAdmissionDisposer;
stop(): Promise<ClusterControlStopResult>;
}
export interface ClusterControlActivationAudit {
readonly state: ClusterControlActivationState;
readonly contractName?: string;
readonly contractVersion?: number;
readonly serverMajor?: number;
readonly migrationCount?: number;
readonly recovery?: ClusterControlStartupRecoverySummary;
}
export interface ClusterControlRuntimeActivationOptions {
readonly enabled?: boolean;
readonly profile: DeploymentProfile;
readonly readiness: ClusterControlReadinessProbe;
readonly create: (
evidence: ClusterControlReadinessEvidence,
) => ClusterControlActivationStack;
readonly audit: (
record: ClusterControlActivationAudit,
) => void | Promise<void>;
}
export type ClusterControlRuntimeActivationResult =
| { readonly status: 'disabled'; stop(): Promise<'stopped'> }
| {
readonly status: 'active';
readonly evidence: ClusterControlReadinessEvidence;
readonly recovery: ClusterControlStartupRecoverySummary;
stop(): Promise<ClusterControlStopResult>;
};
const DISABLED_STOP = async (): Promise<'stopped'> => 'stopped';
function auditEvidence(
evidence: ClusterControlReadinessEvidence,
): Pick<
ClusterControlActivationAudit,
'contractName' | 'contractVersion' | 'serverMajor' | 'migrationCount'
> {
return {
contractName: evidence.contractName,
contractVersion: evidence.contractVersion,
serverMajor: evidence.serverMajor,
migrationCount: evidence.migrationIds.length,
};
}
function assertSafeRecovery(
recovery: ClusterControlStartupRecoverySummary,
): void {
if (!recovery.safe || recovery.remaining !== 0 || recovery.failed !== 0) {
throw new Error('Cluster-control startup recovery did not converge safely');
}
}
/** Enforces readiness -> assembly -> recovery -> lifecycle -> admission order. */
export async function activateClusterControlRuntime(
options: ClusterControlRuntimeActivationOptions,
): Promise<ClusterControlRuntimeActivationResult> {
const enabled = options.enabled ?? false;
if (!enabled) {
await options.audit({ state: 'disabled' });
return { status: 'disabled', stop: DISABLED_STOP };
}
if (options.profile !== 'cluster-control') {
throw new TypeError(
`Deployment profile ${options.profile} cannot activate cluster-control`,
);
}
let evidence: ClusterControlReadinessEvidence | undefined;
let stack: ClusterControlActivationStack | undefined;
let disposeAdmission: ClusterControlAdmissionDisposer | undefined;
try {
evidence = await options.readiness.assertReady();
await options.audit({ state: 'schema_ready', ...auditEvidence(evidence) });
stack = options.create(evidence);
const recovery = await stack.reconcile();
assertSafeRecovery(recovery);
await options.audit({
state: 'reconciled',
...auditEvidence(evidence),
recovery,
});
if (!(await stack.startLifecycles())) {
throw new Error('Cluster-control lifecycles did not start');
}
disposeAdmission = stack.installAdmission();
await options.audit({
state: 'active',
...auditEvidence(evidence),
recovery,
});
let stopPromise: Promise<ClusterControlStopResult> | undefined;
return {
status: 'active',
evidence,
recovery,
stop() {
if (stopPromise) return stopPromise;
stopPromise = (async () => {
let admissionError: unknown;
try {
await disposeAdmission?.();
} catch (error) {
admissionError = error;
}
disposeAdmission = undefined;
const result = await stack!.stop();
if (admissionError) {
try {
await options.audit({
state: 'failed',
...auditEvidence(evidence!),
});
} catch {
// Preserve the admission cleanup failure after stopping the stack.
}
throw admissionError;
}
try {
await options.audit({
state: 'stopped',
...auditEvidence(evidence!),
recovery,
});
} catch {
// Diagnostic failure cannot reverse stopped ownership.
}
return result;
})();
return stopPromise;
},
};
} catch (error) {
try {
await disposeAdmission?.();
} catch {
// Preserve the activation failure and continue stopping the stack.
}
if (stack) {
try {
await stack.stop();
} catch {
// Preserve the activation failure after best-effort cleanup.
}
}
try {
await options.audit({
state: 'failed',
...(evidence ? auditEvidence(evidence) : {}),
});
} catch {
// Diagnostic failure cannot replace the activation failure.
}
throw error;
}
}
@@ -0,0 +1,66 @@
import type { ClusterControlStartupRecoverySummary } from './clusterControlActivation';
export const MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE = 128;
export type ClusterControlRecoveryCandidate = Readonly<
| {
kind: 'run';
id: string;
runId: string;
status: 'created' | 'dispatching' | 'running';
createdAtMs: number;
}
| {
kind: 'attempt';
id: string;
runId: string;
status: 'claimed' | 'starting' | 'running';
createdAtMs: number;
}
>;
export interface ClusterControlRecoveryPage {
/** Observation instant selected by the durable source authority. */
readonly observedAtMs: number;
readonly candidates: readonly ClusterControlRecoveryCandidate[];
/** True means at least one additional candidate exists beyond this page. */
readonly hasMore: boolean;
}
/**
* Cluster-profile port for bounded, durable startup-recovery discovery.
* Implementations must never use an unbounded table scan or return terminal
* work as a candidate.
*/
export interface ClusterControlRecoverySource {
listOutstanding(limit: number): Promise<ClusterControlRecoveryPage>;
}
/**
* Independently proves that a recovery implementation really converged before
* cluster admission is installed. A non-zero remaining value is a lower bound,
* not an expensive exact count.
*/
export class ClusterControlRecoveryConvergenceVerifier {
constructor(private readonly source: ClusterControlRecoverySource) {}
async verify(): Promise<ClusterControlStartupRecoverySummary> {
const page = await this.source.listOutstanding(1);
if (!Number.isSafeInteger(page.observedAtMs) || page.observedAtMs < 0) {
throw new Error('Cluster-control recovery observation is invalid');
}
if (page.candidates.length === 0) {
if (page.hasMore) {
throw new Error(
'Cluster-control recovery source returned hasMore without a candidate',
);
}
return Object.freeze({ safe: true, remaining: 0, failed: 0 });
}
return Object.freeze({
safe: false,
remaining: page.candidates.length + (page.hasMore ? 1 : 0),
failed: 0,
});
}
}
@@ -0,0 +1,356 @@
import type {
ClusterControlRecoveryEvidence,
ClusterControlRecoveryEvidenceProvider,
ClusterControlRecoveryProbeTarget,
} from './clusterControlRecoveryProcessor';
export const MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_PROVIDERS = 32;
export const MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_TIMEOUT_MS = 30_000;
export const CLUSTER_CONTROL_RECOVERY_IDENTITY_FIELDS = [
'workerId',
'workerSessionId',
'workerGeneration',
'executorHandle',
'pid',
'leaseToken',
'leaseTokenDigest',
'leaseGeneration',
'leaseVersion',
'offerId',
] as const;
export type ClusterControlRecoveryIdentityField =
(typeof CLUSTER_CONTROL_RECOVERY_IDENTITY_FIELDS)[number];
export interface ClusterControlRecoveryEvidenceInspectionContext {
/** Resource bound only; PostgreSQL time remains the claim-fence authority. */
readonly timeoutMs: number;
readonly signal: AbortSignal;
}
/**
* Executor-specific, evidence-only capability. It deliberately receives no
* recovery owner/token and exposes no start, stop, retry or completion port.
*/
export interface ClusterControlRecoveryExecutorEvidenceProvider {
readonly executorType: string;
readonly requiredIdentity: readonly ClusterControlRecoveryIdentityField[];
inspect(
target: ClusterControlRecoveryProbeTarget,
context: ClusterControlRecoveryEvidenceInspectionContext,
): Promise<ClusterControlRecoveryEvidence>;
}
export interface ClusterControlRecoveryEvidenceRegistryOptions {
readonly timeoutMs?: number;
}
interface RegisteredProvider {
readonly inspect: ClusterControlRecoveryExecutorEvidenceProvider['inspect'];
readonly requiredIdentity: ReadonlySet<ClusterControlRecoveryIdentityField>;
}
interface ActiveInspection {
readonly controller: AbortController;
readonly resolve: (evidence: ClusterControlRecoveryEvidence) => void;
timer: ReturnType<typeof setTimeout> | undefined;
responded: boolean;
}
const PROVIDER_UNAVAILABLE = Object.freeze({
status: 'unknown',
reason: 'provider_unavailable',
} as const);
const IDENTITY_UNVERIFIABLE = Object.freeze({
status: 'unknown',
reason: 'identity_unverifiable',
} as const);
const CONFLICTING_EVIDENCE = Object.freeze({
status: 'unknown',
reason: 'conflicting_evidence',
} as const);
function integerInRange(
name: string,
value: number,
minimum: number,
maximum: number,
): number {
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);
}
return value;
}
function executorType(value: string): string {
if (!/^[a-z][a-z0-9_.-]{0,63}$/.test(value)) {
throw new TypeError(
'Cluster-control recovery evidence executorType is invalid',
);
}
return value;
}
function requiredIdentity(
fields: readonly ClusterControlRecoveryIdentityField[],
): ReadonlySet<ClusterControlRecoveryIdentityField> {
if (!Array.isArray(fields) || fields.length < 1) {
throw new TypeError(
'Cluster-control recovery evidence provider requires an execution identity',
);
}
const normalized = new Set<ClusterControlRecoveryIdentityField>();
for (const field of fields) {
if (!CLUSTER_CONTROL_RECOVERY_IDENTITY_FIELDS.includes(field)) {
throw new TypeError(
'Cluster-control recovery evidence identity field is invalid',
);
}
if (normalized.has(field)) {
throw new TypeError(
'Cluster-control recovery evidence identity field is duplicated',
);
}
normalized.add(field);
}
return normalized;
}
function optionalString(value: string | undefined, maximum: number): boolean {
return (
value === undefined ||
(value.length > 0 && value.length <= maximum && !value.includes('\0'))
);
}
function optionalSafeInteger(
value: number | undefined,
minimum: number,
): boolean {
return (
value === undefined || (Number.isSafeInteger(value) && value >= minimum)
);
}
function validTarget(target: ClusterControlRecoveryProbeTarget): boolean {
return (
!!target &&
typeof target === 'object' &&
typeof target.runId === 'string' &&
target.runId.length > 0 &&
target.runId.length <= 64 &&
typeof target.attemptId === 'string' &&
target.attemptId.length > 0 &&
target.attemptId.length <= 64 &&
['starting', 'running'].includes(target.attemptStatus) &&
/^[a-z][a-z0-9_.-]{0,63}$/.test(target.executorType) &&
Number.isSafeInteger(target.callbackSequence) &&
target.callbackSequence >= 0 &&
optionalString(target.workerId, 128) &&
(target.workerSessionId === undefined ||
/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
target.workerSessionId,
)) &&
optionalSafeInteger(target.workerGeneration, 1) &&
optionalString(target.executorHandle, 512) &&
optionalSafeInteger(target.pid, 1) &&
optionalString(target.leaseToken, 128) &&
(target.leaseTokenDigest === undefined ||
/^[0-9a-f]{64}$/.test(target.leaseTokenDigest)) &&
optionalSafeInteger(target.leaseGeneration, 1) &&
optionalSafeInteger(target.leaseVersion, 0) &&
optionalSafeInteger(target.leaseExpiresAtMs, 0) &&
optionalString(target.offerId, 128) &&
optionalSafeInteger(target.startedAtMs, 0)
);
}
function hasRequiredIdentity(
target: ClusterControlRecoveryProbeTarget,
fields: ReadonlySet<ClusterControlRecoveryIdentityField>,
): boolean {
for (const field of fields) {
const value = target[field];
if (
field === 'pid' ||
field === 'workerGeneration' ||
field === 'leaseGeneration' ||
field === 'leaseVersion'
) {
if (typeof value !== 'number') return false;
} else if (typeof value !== 'string' || value.length === 0) {
return false;
}
}
return true;
}
function frozenTarget(
target: ClusterControlRecoveryProbeTarget,
): ClusterControlRecoveryProbeTarget {
return Object.freeze({ ...target });
}
function normalizeEvidence(value: unknown): ClusterControlRecoveryEvidence {
if (
value &&
typeof value === 'object' &&
'status' in value &&
value.status === 'running'
) {
return Object.freeze({ status: 'running' });
}
if (
value &&
typeof value === 'object' &&
'status' in value &&
value.status === 'not_running'
) {
return Object.freeze({ status: 'not_running' });
}
if (
value &&
typeof value === 'object' &&
'status' in value &&
value.status === 'unknown' &&
'reason' in value
) {
if (value.reason === 'provider_unavailable') return PROVIDER_UNAVAILABLE;
if (value.reason === 'identity_unverifiable') {
return IDENTITY_UNVERIFIABLE;
}
if (value.reason === 'conflicting_evidence') {
return CONFLICTING_EVIDENCE;
}
}
return CONFLICTING_EVIDENCE;
}
/**
* Exact executor-type router with one in-flight inspection per provider.
* Timeout releases the startup path but keeps the provider busy until its
* abandoned operation settles, preventing unbounded probe accumulation.
*/
export class ClusterControlRecoveryEvidenceRegistry
implements ClusterControlRecoveryEvidenceProvider
{
private readonly providers = new Map<string, RegisteredProvider>();
private readonly active = new Map<string, ActiveInspection>();
private readonly timeoutMs: number;
private disposed = false;
constructor(
providers: readonly ClusterControlRecoveryExecutorEvidenceProvider[],
options: ClusterControlRecoveryEvidenceRegistryOptions = {},
) {
if (
!Array.isArray(providers) ||
providers.length > MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_PROVIDERS
) {
throw new RangeError(
`Cluster-control recovery evidence providers cannot exceed ${MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_PROVIDERS}`,
);
}
this.timeoutMs = integerInRange(
'Cluster-control recovery evidence timeout',
options.timeoutMs ?? 5_000,
1,
MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_TIMEOUT_MS,
);
for (const provider of providers) {
if (!provider || typeof provider.inspect !== 'function') {
throw new TypeError(
'Cluster-control recovery evidence provider is invalid',
);
}
const type = executorType(provider.executorType);
if (this.providers.has(type)) {
throw new TypeError(
`Duplicate cluster-control recovery evidence provider: ${type}`,
);
}
this.providers.set(type, {
inspect: provider.inspect.bind(provider),
requiredIdentity: requiredIdentity(provider.requiredIdentity),
});
}
}
async inspect(
_claim: Parameters<ClusterControlRecoveryEvidenceProvider['inspect']>[0],
target: ClusterControlRecoveryProbeTarget,
): Promise<ClusterControlRecoveryEvidence> {
if (this.disposed) return PROVIDER_UNAVAILABLE;
if (!validTarget(target)) return IDENTITY_UNVERIFIABLE;
const registration = this.providers.get(target.executorType);
if (!registration) return IDENTITY_UNVERIFIABLE;
if (!hasRequiredIdentity(target, registration.requiredIdentity)) {
return IDENTITY_UNVERIFIABLE;
}
if (this.active.has(target.executorType)) return PROVIDER_UNAVAILABLE;
return new Promise<ClusterControlRecoveryEvidence>((resolve) => {
const controller = new AbortController();
const inspection: ActiveInspection = {
controller,
resolve,
timer: undefined,
responded: false,
};
this.active.set(target.executorType, inspection);
const respond = (
evidence: ClusterControlRecoveryEvidence,
release: boolean,
): void => {
if (release && this.active.get(target.executorType) === inspection) {
this.active.delete(target.executorType);
}
if (inspection.timer !== undefined) {
clearTimeout(inspection.timer);
inspection.timer = undefined;
}
if (inspection.responded) return;
inspection.responded = true;
inspection.resolve(evidence);
};
inspection.timer = setTimeout(() => {
inspection.timer = undefined;
controller.abort();
// Keep the slot occupied until the provider promise actually settles.
respond(PROVIDER_UNAVAILABLE, false);
}, this.timeoutMs);
inspection.timer.unref?.();
const context = Object.freeze({
timeoutMs: this.timeoutMs,
signal: controller.signal,
});
Promise.resolve()
.then(() => registration.inspect(frozenTarget(target), context))
.then(
(evidence) => respond(normalizeEvidence(evidence), true),
() => respond(PROVIDER_UNAVAILABLE, true),
);
});
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const inspection of this.active.values()) {
if (inspection.timer !== undefined) clearTimeout(inspection.timer);
inspection.timer = undefined;
inspection.controller.abort();
if (!inspection.responded) {
inspection.responded = true;
inspection.resolve(PROVIDER_UNAVAILABLE);
}
}
this.active.clear();
}
}
@@ -0,0 +1,608 @@
import type { RunAttemptRecord, RunEventRecord, RunRecord } from '../run/run';
import type {
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from '../plugin-package/workflow/pluginPackageWorkflowTaskAttemptAdmission';
import type { StepRunRecord } from '../run/stepRun';
import type {
ClusterControlRecoveryClaim,
ClusterControlRecoveryDisposition,
ClusterControlRecoveryProcessor,
} from './clusterControlRecoverySupervisor';
import { MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS } from './clusterControlRecoverySupervisor';
const ACTIVE_RUN_STATUSES = new Set(['dispatching', 'running']);
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const TERMINAL_ATTEMPT_STATUSES = new Set([
'succeeded',
'failed',
'cancelled',
'timed_out',
'lost',
]);
export const CLUSTER_CONTROL_RECOVERY_UNKNOWN_REASONS = [
'provider_unavailable',
'identity_unverifiable',
'conflicting_evidence',
] as const;
export type ClusterControlRecoveryUnknownReason =
(typeof CLUSTER_CONTROL_RECOVERY_UNKNOWN_REASONS)[number];
export type ClusterControlRecoveryEvidence = Readonly<
| { status: 'running' }
| { status: 'not_running' }
| {
status: 'unknown';
reason: ClusterControlRecoveryUnknownReason;
}
>;
export interface ClusterControlRecoveryProbeTarget {
readonly runId: string;
readonly attemptId: string;
readonly attemptStatus: 'starting' | 'running';
readonly executorType: string;
readonly callbackSequence: number;
readonly workerId?: string;
readonly workerSessionId?: string;
readonly workerGeneration?: number;
readonly executorHandle?: string;
readonly pid?: number;
readonly leaseToken?: string;
readonly leaseTokenDigest?: string;
readonly leaseGeneration?: number;
readonly leaseVersion?: number;
readonly leaseExpiresAtMs?: number;
readonly offerId?: string;
readonly startedAtMs?: number;
}
export interface ClusterControlRecoveryEvidenceProvider {
inspect(
claim: ClusterControlRecoveryClaim,
target: ClusterControlRecoveryProbeTarget,
): Promise<ClusterControlRecoveryEvidence>;
}
export interface ClusterControlRecoverySnapshot {
/** Database-authoritative observation used to revalidate execution leases. */
readonly observedAtMs: number;
readonly run: Readonly<RunRecord> | null;
/** Exact candidate Attempt, or latest Attempt when the candidate is a Run. */
readonly attempt: Readonly<RunAttemptRecord> | null;
/** Immutable Task admission authority when this is a Workflow Task Attempt. */
readonly workflowTask?: Readonly<{
admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
stepRun: Readonly<StepRunRecord>;
}> | null;
}
export type ClusterControlRecoveryLostReason =
| 'attempt_already_lost'
| 'unstarted_claim_expired'
| 'execution_not_running';
export type ClusterControlRecoveryLostAction = Readonly<
| {
kind: 'mark_run_lost';
reason: 'attempt_already_lost';
}
| {
kind: 'mark_attempt_lost';
reason: 'unstarted_claim_expired' | 'execution_not_running';
}
| {
kind: 'mark_attempt_and_run_lost';
reason: 'unstarted_claim_expired' | 'execution_not_running';
}
| {
kind: 'recover_workflow_task';
reason: 'unstarted_claim_expired' | 'execution_not_running';
}
>;
export interface ClusterControlRecoveryResolutionRepository {
load(
claim: ClusterControlRecoveryClaim,
): Promise<ClusterControlRecoverySnapshot | 'fenced'>;
applyLost(
claim: ClusterControlRecoveryClaim,
snapshot: ClusterControlRecoverySnapshot,
action: ClusterControlRecoveryLostAction,
): Promise<'applied' | 'stale' | 'fenced'>;
}
export class ClusterControlRecoveryFenceLostError extends Error {
readonly retryable = true;
constructor() {
super('Cluster-control recovery claim fence was lost');
this.name = 'ClusterControlRecoveryFenceLostError';
}
}
export class InvalidClusterControlRecoveryTransitionError extends Error {
readonly code = 'INVALID_CLUSTER_CONTROL_RECOVERY_TRANSITION';
constructor(message: string) {
super(message);
this.name = 'InvalidClusterControlRecoveryTransitionError';
}
}
export interface ClusterControlRecoveryLostTransition {
readonly attempt?: Readonly<{
run: RunRecord;
attempt: RunAttemptRecord;
event: Readonly<
Omit<RunEventRecord, 'id' | 'actorType' | 'actorId' | 'createdAtMs'>
>;
}>;
readonly run?: Readonly<{
run: RunRecord;
event: Readonly<
Omit<RunEventRecord, 'id' | 'actorType' | 'actorId' | 'createdAtMs'>
>;
}>;
}
function errorMetadata(reason: ClusterControlRecoveryLostReason): Readonly<{
code: string;
summary: string;
}> {
if (reason === 'attempt_already_lost') {
return Object.freeze({
code: 'CLUSTER_RECOVERY_ATTEMPT_ALREADY_LOST',
summary:
'The latest Attempt was already lost before the Run was reconciled',
});
}
if (reason === 'unstarted_claim_expired') {
return Object.freeze({
code: 'CLUSTER_RECOVERY_UNSTARTED_CLAIM_EXPIRED',
summary:
'The unstarted Attempt claim expired before execution was admitted',
});
}
return Object.freeze({
code: 'CLUSTER_RECOVERY_EXECUTION_NOT_RUNNING',
summary:
'Trusted execution evidence proved that the active Attempt is not running',
});
}
function transitionTime(
atMs: number,
run: Readonly<RunRecord>,
attempt?: Readonly<RunAttemptRecord>,
): number {
if (!Number.isSafeInteger(atMs) || atMs < 0) {
throw new InvalidClusterControlRecoveryTransitionError(
'Recovery transition time is invalid',
);
}
return Math.max(
atMs,
run.createdAtMs,
run.startedAtMs ?? 0,
attempt?.createdAtMs ?? 0,
attempt?.startedAtMs ?? 0,
attempt?.finishedAtMs ?? 0,
);
}
function reserveEvent(run: Readonly<RunRecord>): Readonly<{
run: RunRecord;
sequence: number;
}> {
const version = run.version + 1;
const sequence = run.eventSequence + 1;
if (
!Number.isSafeInteger(version) ||
version < 1 ||
!Number.isSafeInteger(sequence) ||
sequence < 1
) {
throw new InvalidClusterControlRecoveryTransitionError(
'Recovery transition version or event sequence overflowed',
);
}
return Object.freeze({
run: { ...run, version, eventSequence: sequence },
sequence,
});
}
function attemptLostTransition(
run: Readonly<RunRecord>,
attempt: Readonly<RunAttemptRecord>,
reason: 'unstarted_claim_expired' | 'execution_not_running',
atMs: number,
): NonNullable<ClusterControlRecoveryLostTransition['attempt']> {
if (
attempt.runId !== run.id ||
!ACTIVE_ATTEMPT_STATUSES.has(attempt.status)
) {
throw new InvalidClusterControlRecoveryTransitionError(
'Recovery Attempt is not an active member of the Run aggregate',
);
}
const metadata = errorMetadata(reason);
const reserved = reserveEvent(run);
const nextAttempt: RunAttemptRecord = {
...attempt,
status: 'lost',
finishedAtMs: atMs,
errorCode: metadata.code,
errorSummary: metadata.summary,
};
return Object.freeze({
run: reserved.run,
attempt: nextAttempt,
event: Object.freeze({
runId: run.id,
sequence: reserved.sequence,
type: 'attempt.lost',
dedupeKey: `cluster-recovery:attempt:${attempt.id}:${attempt.callbackSequence}`,
attemptId: attempt.id,
...(attempt.stepRunId === undefined
? {}
: { stepRunId: attempt.stepRunId }),
payload: Object.freeze({
attempt_id: attempt.id,
attempt: attempt.attempt,
from_status: attempt.status,
to_status: 'lost',
version: reserved.run.version,
error_code: metadata.code,
}),
}),
});
}
function runLostTransition(
run: Readonly<RunRecord>,
attemptId: string,
reason: ClusterControlRecoveryLostReason,
): NonNullable<ClusterControlRecoveryLostTransition['run']> {
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
throw new InvalidClusterControlRecoveryTransitionError(
'Recovery Run is not active',
);
}
const metadata = errorMetadata(reason);
const reserved = reserveEvent(run);
const nextRun: RunRecord = {
...reserved.run,
status: 'lost',
errorCode: metadata.code,
errorSummary: metadata.summary,
};
return Object.freeze({
run: nextRun,
event: Object.freeze({
runId: run.id,
sequence: reserved.sequence,
type: 'run.lost',
dedupeKey: `cluster-recovery:run:${run.id}:${attemptId}:${run.version}`,
attemptId,
payload: Object.freeze({
from_status: run.status,
to_status: 'lost',
version: nextRun.version,
error_code: metadata.code,
}),
}),
});
}
/**
* Builds only the recovery-specific lost transition. It deliberately does not
* create another Attempt, enqueue work, call an Executor or infer completion.
*/
export function buildClusterControlRecoveryLostTransition(
currentRun: Readonly<RunRecord>,
currentAttempt: Readonly<RunAttemptRecord> | null,
action: ClusterControlRecoveryLostAction,
observedAtMs: number,
): ClusterControlRecoveryLostTransition {
if (
currentRun.executionOwner !== 'runtime' ||
currentRun.cancelRequestedAtMs !== undefined
) {
throw new InvalidClusterControlRecoveryTransitionError(
'Recovery lost transition has no runtime ownership authority',
);
}
const atMs = transitionTime(
observedAtMs,
currentRun,
currentAttempt ?? undefined,
);
if (action.kind === 'recover_workflow_task') {
throw new InvalidClusterControlRecoveryTransitionError(
'Workflow Task recovery requires its admission-bound StepRun authority',
);
}
if (action.kind === 'mark_run_lost') {
if (!currentAttempt || currentAttempt.status !== 'lost') {
throw new InvalidClusterControlRecoveryTransitionError(
'Run-only recovery requires an already-lost Attempt',
);
}
return Object.freeze({
run: runLostTransition(currentRun, currentAttempt.id, action.reason),
});
}
if (!currentAttempt) {
throw new InvalidClusterControlRecoveryTransitionError(
'Attempt recovery requires an Attempt',
);
}
if (action.kind === 'mark_attempt_lost') {
if (currentRun.status !== 'lost') {
throw new InvalidClusterControlRecoveryTransitionError(
'Attempt-only recovery requires an already-lost Run',
);
}
return Object.freeze({
attempt: attemptLostTransition(
currentRun,
currentAttempt,
action.reason,
atMs,
),
});
}
if (!ACTIVE_RUN_STATUSES.has(currentRun.status)) {
throw new InvalidClusterControlRecoveryTransitionError(
'Aggregate recovery requires an active Run',
);
}
const attempt = attemptLostTransition(
currentRun,
currentAttempt,
action.reason,
atMs,
);
return Object.freeze({
attempt,
run: runLostTransition(attempt.run, currentAttempt.id, action.reason),
});
}
function retryDelay(value: number | undefined): number {
const delay = value ?? 5_000;
if (
!Number.isSafeInteger(delay) ||
delay < 0 ||
delay > MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS
) {
throw new RangeError(
`Cluster-control evidence retry delay must be between 0 and ${MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS}`,
);
}
return delay;
}
function validSnapshot(
claim: ClusterControlRecoveryClaim,
snapshot: ClusterControlRecoverySnapshot,
): void {
if (
!Number.isSafeInteger(snapshot.observedAtMs) ||
snapshot.observedAtMs < 0 ||
(snapshot.run !== null && snapshot.run.id !== claim.candidate.runId) ||
(claim.candidate.kind === 'attempt' &&
snapshot.attempt !== null &&
snapshot.attempt.id !== claim.candidate.id) ||
(snapshot.workflowTask !== undefined &&
snapshot.workflowTask !== null &&
(claim.candidate.kind !== 'attempt' ||
snapshot.workflowTask.admission.attemptId !==
claim.candidate.id ||
snapshot.workflowTask.admission.runId !==
claim.candidate.runId ||
snapshot.workflowTask.stepRun.id !==
snapshot.workflowTask.admission.stepRunId ||
snapshot.workflowTask.stepRun.runId !==
claim.candidate.runId))
) {
throw new TypeError(
'Cluster-control recovery resolution repository returned an invalid snapshot',
);
}
}
function hasValidLease(
attempt: Readonly<RunAttemptRecord>,
observedAtMs: number,
): boolean {
return (
attempt.leaseExpiresAtMs !== undefined &&
attempt.leaseExpiresAtMs > observedAtMs
);
}
function probeTarget(
attempt: Readonly<RunAttemptRecord>,
): ClusterControlRecoveryProbeTarget {
if (attempt.status !== 'starting' && attempt.status !== 'running') {
throw new TypeError('Cluster-control recovery probe target is not running');
}
return Object.freeze({
runId: attempt.runId,
attemptId: attempt.id,
attemptStatus: attempt.status,
executorType: attempt.executorType,
callbackSequence: attempt.callbackSequence,
...(attempt.workerId === undefined ? {} : { workerId: attempt.workerId }),
...(attempt.workerSessionId === undefined
? {}
: { workerSessionId: attempt.workerSessionId }),
...(attempt.workerGeneration === undefined
? {}
: { workerGeneration: attempt.workerGeneration }),
...(attempt.executorHandle === undefined
? {}
: { executorHandle: attempt.executorHandle }),
...(attempt.pid === undefined ? {} : { pid: attempt.pid }),
...(attempt.leaseToken === undefined
? {}
: { leaseToken: attempt.leaseToken }),
...(attempt.leaseTokenDigest === undefined
? {}
: { leaseTokenDigest: attempt.leaseTokenDigest }),
...(attempt.leaseGeneration === undefined
? {}
: { leaseGeneration: attempt.leaseGeneration }),
...(attempt.leaseVersion === undefined
? {}
: { leaseVersion: attempt.leaseVersion }),
...(attempt.leaseExpiresAtMs === undefined
? {}
: { leaseExpiresAtMs: attempt.leaseExpiresAtMs }),
...(attempt.offerId === undefined ? {} : { offerId: attempt.offerId }),
...(attempt.startedAtMs === undefined
? {}
: { startedAtMs: attempt.startedAtMs }),
});
}
function normalizeEvidence(
evidence: ClusterControlRecoveryEvidence,
): ClusterControlRecoveryEvidence {
if (evidence?.status === 'running') {
return Object.freeze({ status: 'running' });
}
if (evidence?.status === 'not_running') {
return Object.freeze({ status: 'not_running' });
}
if (
evidence?.status === 'unknown' &&
CLUSTER_CONTROL_RECOVERY_UNKNOWN_REASONS.includes(evidence.reason)
) {
return Object.freeze({ status: 'unknown', reason: evidence.reason });
}
throw new TypeError(
'Cluster-control recovery evidence provider returned invalid evidence',
);
}
/**
* Revalidates durable state, requests external evidence only for attempts that
* crossed the start barrier, and delegates fenced atomic mutation to storage.
*/
export class EvidenceBasedClusterControlRecoveryProcessor
implements ClusterControlRecoveryProcessor
{
private readonly retryDelayMs: number;
constructor(
private readonly repository: ClusterControlRecoveryResolutionRepository,
private readonly evidence: ClusterControlRecoveryEvidenceProvider,
options: Readonly<{ retryDelayMs?: number }> = {},
) {
this.retryDelayMs = retryDelay(options.retryDelayMs);
}
async process(
claim: ClusterControlRecoveryClaim,
): Promise<ClusterControlRecoveryDisposition> {
const snapshot = await this.repository.load(claim);
if (snapshot === 'fenced') throw new ClusterControlRecoveryFenceLostError();
validSnapshot(claim, snapshot);
const { run, attempt } = snapshot;
if (!run || run.executionOwner !== 'runtime') {
return Object.freeze({ status: 'resolved' });
}
if (claim.candidate.kind === 'run') {
if (!['created', 'dispatching', 'running'].includes(run.status)) {
return Object.freeze({ status: 'resolved' });
}
if (run.status === 'created' || !attempt) {
return Object.freeze({ status: 'manual' });
}
if (attempt.status === 'lost') {
if (run.cancelRequestedAtMs !== undefined) return this.retry();
return this.apply(claim, snapshot, {
kind: 'mark_run_lost',
reason: 'attempt_already_lost',
});
}
if (TERMINAL_ATTEMPT_STATUSES.has(attempt.status)) {
return Object.freeze({ status: 'manual' });
}
} else {
if (!attempt || attempt.runId !== run.id) {
return Object.freeze({ status: 'resolved' });
}
if (!ACTIVE_ATTEMPT_STATUSES.has(attempt.status)) {
return Object.freeze({ status: 'resolved' });
}
}
if (!attempt || !ACTIVE_ATTEMPT_STATUSES.has(attempt.status)) {
return Object.freeze({ status: 'manual' });
}
if (hasValidLease(attempt, snapshot.observedAtMs)) {
return Object.freeze({ status: 'resolved' });
}
if (
run.status !== 'dispatching' &&
run.status !== 'running' &&
run.status !== 'lost'
) {
return Object.freeze({ status: 'manual' });
}
if (run.cancelRequestedAtMs !== undefined) return this.retry();
const actionKind = snapshot.workflowTask
? 'recover_workflow_task'
: run.status === 'lost'
? 'mark_attempt_lost'
: 'mark_attempt_and_run_lost';
if (attempt.status === 'claimed') {
return this.apply(claim, snapshot, {
kind: actionKind,
reason: 'unstarted_claim_expired',
});
}
const evidence = normalizeEvidence(
await this.evidence.inspect(claim, probeTarget(attempt)),
);
if (evidence.status === 'running') return this.retry();
if (evidence.status === 'unknown') {
return evidence.reason === 'provider_unavailable'
? this.retry()
: Object.freeze({ status: 'manual' });
}
return this.apply(claim, snapshot, {
kind: actionKind,
reason: 'execution_not_running',
});
}
private retry(): ClusterControlRecoveryDisposition {
return Object.freeze({ status: 'retry', delayMs: this.retryDelayMs });
}
private async apply(
claim: ClusterControlRecoveryClaim,
snapshot: ClusterControlRecoverySnapshot,
action: ClusterControlRecoveryLostAction,
): Promise<ClusterControlRecoveryDisposition> {
const result = await this.repository.applyLost(claim, snapshot, action);
if (result === 'fenced') throw new ClusterControlRecoveryFenceLostError();
if (result !== 'applied' && result !== 'stale') {
throw new TypeError(
'Cluster-control recovery resolution repository returned an invalid result',
);
}
return Object.freeze({ status: 'resolved' });
}
}
@@ -0,0 +1,242 @@
import type { ClusterControlRecoveryCandidate } from './clusterControlRecovery';
import type { ClusterControlStartupRecoverySummary } from './clusterControlActivation';
export const MAX_CLUSTER_CONTROL_RECOVERY_CLAIMS_PER_PASS = 128;
export const MAX_CLUSTER_CONTROL_RECOVERY_CLAIM_LEASE_MS = 5 * 60 * 1000;
export const MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS = 5 * 60 * 1000;
export class ClusterControlRecoveryStoreError extends Error {
readonly retryable = true;
constructor(readonly cause?: unknown) {
super('Cluster-control recovery store operation failed');
this.name = 'ClusterControlRecoveryStoreError';
}
}
export interface ClusterControlRecoveryClaim {
readonly candidate: ClusterControlRecoveryCandidate;
readonly observedAtMs: number;
readonly ownerId: string;
readonly token: string;
readonly version: number;
readonly expiresAtMs: number;
}
export interface ClusterControlRecoveryClaimPage {
readonly claims: readonly ClusterControlRecoveryClaim[];
/** Number of candidates observed in this bounded discovery page. */
readonly discovered: number;
readonly hasMore: boolean;
}
export type ClusterControlRecoveryDisposition =
| Readonly<{ status: 'resolved' }>
| Readonly<{ status: 'retry'; delayMs: number }>
| Readonly<{ status: 'manual' }>;
export interface ClusterControlRecoveryClaimRepository {
claim(
options: Readonly<{
ownerId: string;
limit: number;
leaseMs: number;
}>,
): Promise<ClusterControlRecoveryClaimPage>;
settle(
claim: ClusterControlRecoveryClaim,
disposition: ClusterControlRecoveryDisposition,
): Promise<'settled' | 'fenced'>;
}
export interface ClusterControlRecoveryProcessor {
process(
claim: ClusterControlRecoveryClaim,
): Promise<ClusterControlRecoveryDisposition>;
}
export interface ClusterControlRecoverySupervisorOptions {
readonly ownerId: string;
readonly limit?: number;
readonly leaseMs?: number;
readonly retryDelayMs?: number;
}
function integerInRange(
name: string,
value: number,
minimum: number,
maximum: number,
): number {
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);
}
return value;
}
function ownerId(value: string): string {
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) {
throw new TypeError(
'Cluster-control recovery ownerId must contain 1-128 safe identifier characters',
);
}
return value;
}
function targetKey(candidate: ClusterControlRecoveryCandidate): string {
return `${candidate.kind}:${candidate.id}`;
}
function assertClaim(
claim: ClusterControlRecoveryClaim,
expectedOwnerId: string,
): void {
if (
claim.ownerId !== expectedOwnerId ||
typeof claim.token !== 'string' ||
claim.token.length < 16 ||
claim.token.length > 128 ||
!Number.isSafeInteger(claim.version) ||
claim.version < 1 ||
!Number.isSafeInteger(claim.observedAtMs) ||
claim.observedAtMs < 0 ||
!Number.isSafeInteger(claim.expiresAtMs) ||
claim.expiresAtMs <= claim.observedAtMs ||
!claim.candidate ||
typeof claim.candidate.id !== 'string' ||
claim.candidate.id.length === 0
) {
throw new TypeError(
'Cluster-control recovery repository returned an invalid claim',
);
}
}
function normalizeDisposition(
value: ClusterControlRecoveryDisposition,
): ClusterControlRecoveryDisposition {
if (!value || typeof value !== 'object') {
throw new TypeError(
'Cluster-control recovery processor returned no disposition',
);
}
if (value.status === 'resolved') return Object.freeze({ status: 'resolved' });
if (value.status === 'manual') return Object.freeze({ status: 'manual' });
if (value.status === 'retry') {
return Object.freeze({
status: 'retry',
delayMs: integerInRange(
'Cluster-control recovery retry delay',
value.delayMs,
0,
MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS,
),
});
}
throw new TypeError(
'Cluster-control recovery processor returned an invalid disposition',
);
}
/**
* Runs one bounded, sequential recovery pass. It owns no timer and never
* executes a task; the injected processor may only resolve evidence under the
* repository claim fence.
*/
export class ClusterControlRecoverySupervisor {
private readonly ownerId: string;
private readonly limit: number;
private readonly leaseMs: number;
private readonly retryDelayMs: number;
constructor(
private readonly repository: ClusterControlRecoveryClaimRepository,
private readonly processor: ClusterControlRecoveryProcessor,
options: ClusterControlRecoverySupervisorOptions,
) {
this.ownerId = ownerId(options.ownerId);
this.limit = integerInRange(
'Cluster-control recovery claim limit',
options.limit ?? 16,
1,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIMS_PER_PASS,
);
this.leaseMs = integerInRange(
'Cluster-control recovery claim lease',
options.leaseMs ?? 30_000,
1_000,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIM_LEASE_MS,
);
this.retryDelayMs = integerInRange(
'Cluster-control recovery retry delay',
options.retryDelayMs ?? 5_000,
0,
MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS,
);
}
async reconcile(): Promise<ClusterControlStartupRecoverySummary> {
const page = await this.repository.claim({
ownerId: this.ownerId,
limit: this.limit,
leaseMs: this.leaseMs,
});
if (
!Number.isSafeInteger(page.discovered) ||
page.discovered < page.claims.length ||
page.discovered > this.limit ||
typeof page.hasMore !== 'boolean' ||
page.claims.length > this.limit
) {
throw new TypeError(
'Cluster-control recovery repository returned an invalid claim page',
);
}
const keys = new Set<string>();
for (const claim of page.claims) {
assertClaim(claim, this.ownerId);
const key = targetKey(claim.candidate);
if (keys.has(key)) {
throw new TypeError(
'Cluster-control recovery repository returned duplicate claims',
);
}
keys.add(key);
}
let remaining =
page.discovered - page.claims.length + (page.hasMore ? 1 : 0);
let failed = 0;
for (const claim of page.claims) {
let disposition: ClusterControlRecoveryDisposition;
try {
disposition = normalizeDisposition(await this.processor.process(claim));
} catch {
disposition = Object.freeze({
status: 'retry',
delayMs: this.retryDelayMs,
});
}
const settled = await this.repository.settle(claim, disposition);
if (settled === 'fenced') {
remaining += 1;
continue;
}
if (settled !== 'settled') {
throw new TypeError(
'Cluster-control recovery repository returned an invalid settlement',
);
}
if (disposition.status !== 'resolved') {
remaining += 1;
failed += 1;
}
}
return Object.freeze({
safe: remaining === 0 && failed === 0,
remaining,
failed,
});
}
}
@@ -0,0 +1,78 @@
import type { ClusterControlStartupRecoverySummary } from './clusterControlActivation';
export const MAX_CLUSTER_CONTROL_STARTUP_RECOVERY_PASSES = 64;
export interface ClusterControlRecoveryPass {
reconcile(): Promise<ClusterControlStartupRecoverySummary>;
}
export interface ClusterControlStartupRecoveryCoordinatorOptions {
readonly maxPasses?: number;
}
function maxPasses(value: number | undefined): number {
const normalized = value ?? 8;
if (
!Number.isSafeInteger(normalized) ||
normalized < 1 ||
normalized > MAX_CLUSTER_CONTROL_STARTUP_RECOVERY_PASSES
) {
throw new RangeError(
`Cluster-control startup recovery maxPasses must be between 1 and ${MAX_CLUSTER_CONTROL_STARTUP_RECOVERY_PASSES}`,
);
}
return normalized;
}
function normalizeSummary(
value: ClusterControlStartupRecoverySummary,
): ClusterControlStartupRecoverySummary {
if (
!value ||
typeof value !== 'object' ||
typeof value.safe !== 'boolean' ||
!Number.isSafeInteger(value.remaining) ||
value.remaining < 0 ||
!Number.isSafeInteger(value.failed) ||
value.failed < 0 ||
(value.safe && (value.remaining !== 0 || value.failed !== 0)) ||
(!value.safe && value.remaining === 0 && value.failed === 0)
) {
throw new TypeError(
'Cluster-control recovery pass returned an invalid summary',
);
}
return Object.freeze({
safe: value.safe,
remaining: value.remaining,
failed: value.failed,
});
}
/**
* Runs a hard-bounded number of startup passes without a timer or recursion.
* Deferred/manual work stops immediately; pure backlog may consume another
* page, and the independent durable-source verifier remains the final gate.
*/
export class ClusterControlStartupRecoveryCoordinator {
private readonly maxPasses: number;
constructor(
private readonly pass: ClusterControlRecoveryPass,
options: ClusterControlStartupRecoveryCoordinatorOptions = {},
) {
if (!pass || typeof pass.reconcile !== 'function') {
throw new TypeError('Cluster-control recovery pass is invalid');
}
this.maxPasses = maxPasses(options.maxPasses);
}
async reconcile(): Promise<ClusterControlStartupRecoverySummary> {
let latest: ClusterControlStartupRecoverySummary | undefined;
for (let index = 0; index < this.maxPasses; index += 1) {
latest = normalizeSummary(await this.pass.reconcile());
if (latest.safe || latest.failed > 0) return latest;
}
return latest!;
}
}
+159
View File
@@ -0,0 +1,159 @@
export type {
OpenPostgresDatabase,
PostgresClient,
PostgresDatabaseResource,
PostgresPool,
PostgresQueryable,
PostgresQueryResult,
} from './persistence/postgresql';
export {
MIGRATION_CHECKSUM_SCHEMES,
MIGRATION_ID_SCHEMES,
MIGRATION_STREAM_DIALECTS,
InvalidMigrationStreamError,
MigrationStreamAheadOfCodeError,
MigrationStreamChecksumMismatchError,
MigrationStreamHistoryCorruptionError,
auditMigrationStreamHistory,
runMigrationStream,
type MigrationChecksumScheme,
type MigrationIdScheme,
type MigrationStreamDefinition,
type MigrationStreamDialect,
type MigrationStreamManifest,
type MigrationStreamManifestStep,
type MigrationStreamRecord,
type MigrationStreamStep,
type MigrationStreamStore,
type MigrationStreamTransaction,
type RunMigrationStreamOptions,
} from './migration/migrationStream';
export {
activateClusterControlRuntime,
type ClusterControlAdmissionDisposer,
type ClusterControlActivationAudit,
type ClusterControlActivationStack,
type ClusterControlActivationState,
type ClusterControlReadinessEvidence,
type ClusterControlReadinessProbe,
type ClusterControlRuntimeActivationOptions,
type ClusterControlRuntimeActivationResult,
type ClusterControlStartupRecoverySummary,
type ClusterControlStopResult,
type DeploymentProfile,
} from './cluster-control/clusterControlActivation';
export {
MAX_CLUSTER_CONTROL_RECOVERY_PAGE_SIZE,
ClusterControlRecoveryConvergenceVerifier,
type ClusterControlRecoveryCandidate,
type ClusterControlRecoveryPage,
type ClusterControlRecoverySource,
} from './cluster-control/clusterControlRecovery';
export {
MAX_CLUSTER_CONTROL_RECOVERY_CLAIMS_PER_PASS,
MAX_CLUSTER_CONTROL_RECOVERY_CLAIM_LEASE_MS,
MAX_CLUSTER_CONTROL_RECOVERY_RETRY_DELAY_MS,
ClusterControlRecoveryStoreError,
ClusterControlRecoverySupervisor,
type ClusterControlRecoveryClaim,
type ClusterControlRecoveryClaimPage,
type ClusterControlRecoveryClaimRepository,
type ClusterControlRecoveryDisposition,
type ClusterControlRecoveryProcessor,
type ClusterControlRecoverySupervisorOptions,
} from './cluster-control/clusterControlRecoverySupervisor';
export {
CLUSTER_CONTROL_RECOVERY_UNKNOWN_REASONS,
ClusterControlRecoveryFenceLostError,
EvidenceBasedClusterControlRecoveryProcessor,
InvalidClusterControlRecoveryTransitionError,
buildClusterControlRecoveryLostTransition,
type ClusterControlRecoveryEvidence,
type ClusterControlRecoveryEvidenceProvider,
type ClusterControlRecoveryLostAction,
type ClusterControlRecoveryLostReason,
type ClusterControlRecoveryLostTransition,
type ClusterControlRecoveryProbeTarget,
type ClusterControlRecoveryResolutionRepository,
type ClusterControlRecoverySnapshot,
type ClusterControlRecoveryUnknownReason,
} from './cluster-control/clusterControlRecoveryProcessor';
export {
PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA,
InvalidPluginPackageWorkflowTaskRecoveryError,
buildPluginPackageWorkflowTaskRecovery,
type PluginPackageWorkflowTaskRecoveryBundle,
type PluginPackageWorkflowTaskRecoveryInput,
type PluginPackageWorkflowTaskRecoveryReason,
} from './plugin-package/workflow/pluginPackageWorkflowTaskRecovery';
export {
CLUSTER_CONTROL_RECOVERY_IDENTITY_FIELDS,
MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_PROVIDERS,
MAX_CLUSTER_CONTROL_RECOVERY_EVIDENCE_TIMEOUT_MS,
ClusterControlRecoveryEvidenceRegistry,
type ClusterControlRecoveryEvidenceInspectionContext,
type ClusterControlRecoveryEvidenceRegistryOptions,
type ClusterControlRecoveryExecutorEvidenceProvider,
type ClusterControlRecoveryIdentityField,
} from './cluster-control/clusterControlRecoveryEvidenceRegistry';
export {
MAX_CLUSTER_CONTROL_STARTUP_RECOVERY_PASSES,
ClusterControlStartupRecoveryCoordinator,
type ClusterControlRecoveryPass,
type ClusterControlStartupRecoveryCoordinatorOptions,
} from './cluster-control/clusterControlStartupRecoveryCoordinator';
export * from './run/repositoryErrors';
export * from './security/identity-credential/apiCredential';
export * from './security/identity-credential/apiCredentialAdministration';
export * from './security/identity-credential/apiCredentialToken';
export * from './security/identity-credential/identityAdministration';
export * from './security/project-policy/projectPolicy';
export * from './plugin-package/pluginPackage';
export * from './plugin-package/installation/pluginPackageInstall';
export * from './plugin-package/pluginPackageProposal';
export * from './approved-action/approvedActionExecution';
export * from './approved-action/approvedActionDispatcher';
export * from './plugin-package/pluginPackageApprovedActionHandler';
export * from './run/run';
export * from './run/stepRun';
export * from './run/runRepository';
export * from './run/runRetryPolicy';
export * from './run/clusterRunLostRetry';
export * from './run/clusterRunCancellationConvergence';
export * from './task-definition/taskDefinition';
export * from './tool-execution/tool-registry/toolRegistry';
export * from './tool-execution/toolInvocationArtifact';
export * from './tool-execution/trustedToolInvocation';
export * from './tool-execution/toolExecutionEvidence';
export * from './tool-execution/toolExecutionStartBarrier';
export * from './secret/secretReference';
export * from './task-definition/clusterExecutionRevision';
export * from './local-runtime/localStartupRecovery';
export * from './local-runtime/localCompletionReceiptJournal';
export * from './local-runtime/localDispatch';
export * from './local-runtime/localExecutionControl';
export * from './secret/localSecret';
export * from './secret/localSecretAdministration';
export * from './local-owner/localOwnerCredentialRecovery';
export * from './local-owner/localOwnerDeliveryAcknowledgementGc';
export * from './local-owner/localOwnerPepperMaterialGc';
export * from './run/runDispatchLease';
export * from './remote-execution/remoteDispatch';
export * from './remote-execution/remoteRunActivationDelivery';
export * from './remote-execution/remoteSecretDelivery';
export * from './security/security';
export * from './security/audit/securityAudit';
export * from './security/audit/securityAuditQuery';
export * from './worker/workerSession';
export * from './worker/workerCredential';
export * from './worker/workerCredentialToken';
export * from './worker/workerExecutionAttestation';
@@ -0,0 +1,797 @@
import { createHash, timingSafeEqual } from 'node:crypto';
import {
normalizeApiCredentialRecord,
type ApiCredentialRecord,
} from '../security/identity-credential/apiCredential';
import {
normalizeIdentitySubjectRecord,
type IdentitySubjectRecord,
} from '../security/identity-credential/identityAdministration';
import {
assertProjectPolicyProjectId,
normalizeProjectRoleBinding,
type ProjectRoleBindingRecord,
} from '../security/project-policy/projectPolicy';
import { normalizeSecurityPrincipal, type SecurityPrincipal } from '../security/security';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../security/audit/securityAudit';
export const LOCAL_OWNER_BOOTSTRAP_TOKEN_BYTES = 32;
export const LOCAL_OWNER_BOOTSTRAP_CHALLENGE_ID_BYTES = 16;
export const LOCAL_OWNER_BOOTSTRAP_DEFAULT_TTL_MS = 10 * 60 * 1000;
export const LOCAL_OWNER_BOOTSTRAP_MIN_TTL_MS = 60 * 1000;
export const LOCAL_OWNER_BOOTSTRAP_MAX_TTL_MS = 30 * 60 * 1000;
export const LOCAL_OWNER_BOOTSTRAP_SYSTEM_SUBJECT = Object.freeze({
type: 'system' as const,
id: 'owner-bootstrap',
});
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const CHALLENGE_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const DIGEST_DOMAIN = 'qinglong3-local-owner-bootstrap-v1\0';
const MAX_VERSION = 2_147_483_647;
export interface LocalIdentityProvisioningRecord {
readonly mutationId: string;
readonly requestId: string;
readonly identity: IdentitySubjectRecord;
readonly credential: ApiCredentialRecord;
readonly issuer: SecurityPrincipal;
readonly audit: SecurityAuditRecord;
readonly createdAtMs: number;
}
export interface ProvisionLocalIdentityCommand
extends LocalIdentityProvisioningRecord {}
export interface ProvisionLocalIdentityResult {
readonly status: 'inserted' | 'existing';
readonly provisioning: Readonly<LocalIdentityProvisioningRecord>;
}
export interface LocalOwnerBootstrapChallengeRecord {
readonly projectId: string;
readonly version: number;
readonly issueMutationId: string;
readonly issueRequestId: string;
readonly challengeId: string;
readonly tokenDigest: string;
readonly issuer: SecurityPrincipal;
readonly issuedAtMs: number;
readonly expiresAtMs: number;
readonly issueAudit: SecurityAuditRecord;
readonly consumedAtMs?: number;
readonly claimMutationId?: string;
readonly claimRequestId?: string;
readonly claimedPrincipal?: SecurityPrincipal;
readonly credentialId?: string;
readonly credentialVersion?: number;
readonly binding?: ProjectRoleBindingRecord;
readonly claimAudit?: SecurityAuditRecord;
}
export interface IssueLocalOwnerBootstrapChallengeCommand {
readonly projectId: string;
readonly mutationId: string;
readonly requestId: string;
readonly challengeId: string;
readonly tokenDigest: string;
readonly issuer: SecurityPrincipal;
readonly issuedAtMs: number;
readonly expiresAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface IssueLocalOwnerBootstrapChallengeResult {
readonly status: 'inserted' | 'existing';
readonly challenge: Readonly<LocalOwnerBootstrapChallengeRecord>;
}
export interface ClaimLocalOwnerCommand {
readonly projectId: string;
readonly mutationId: string;
readonly requestId: string;
readonly challengeId: string;
readonly tokenDigest: string;
readonly principal: SecurityPrincipal;
readonly credentialId: string;
readonly credentialVersion: number;
readonly claimedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface ClaimLocalOwnerResult {
readonly status: 'inserted' | 'existing';
readonly challenge: Readonly<LocalOwnerBootstrapChallengeRecord>;
readonly binding: Readonly<ProjectRoleBindingRecord>;
}
export interface LocalOwnerCredentialDeliveryAcknowledgementRecord {
readonly kind: 'credential';
readonly mutationId: string;
readonly requestId: string;
readonly subjectId: string;
readonly credentialId: string;
readonly factDigest: string;
readonly ttlMs: number;
readonly deliveryDigest: string;
readonly acknowledgedAtMs: number;
}
export interface LocalOwnerChallengeDeliveryAcknowledgementRecord {
readonly kind: 'challenge';
readonly projectId: string;
readonly mutationId: string;
readonly requestId: string;
readonly challengeId: string;
readonly factDigest: string;
readonly ttlMs: number;
readonly deliveryDigest: string;
readonly acknowledgedAtMs: number;
}
export type LocalOwnerSecretDeliveryAcknowledgementRecord =
| LocalOwnerCredentialDeliveryAcknowledgementRecord
| LocalOwnerChallengeDeliveryAcknowledgementRecord;
export interface RecordLocalOwnerSecretDeliveryAcknowledgementResult {
readonly status: 'inserted' | 'existing';
readonly acknowledgement: Readonly<LocalOwnerSecretDeliveryAcknowledgementRecord>;
}
export interface LocalOwnerBootstrapRepository {
resolveProjectVersion(projectId: string): Promise<number | null>;
resolveProvisioning(
mutationId: string,
): Promise<Readonly<LocalIdentityProvisioningRecord> | null>;
resolveIssuedChallenge(
mutationId: string,
): Promise<Readonly<LocalOwnerBootstrapChallengeRecord> | null>;
resolveDeliveryAcknowledgement(
mutationId: string,
): Promise<Readonly<LocalOwnerSecretDeliveryAcknowledgementRecord> | null>;
recordDeliveryAcknowledgement(
acknowledgement: LocalOwnerSecretDeliveryAcknowledgementRecord,
): Promise<RecordLocalOwnerSecretDeliveryAcknowledgementResult>;
provision(
command: ProvisionLocalIdentityCommand,
): Promise<ProvisionLocalIdentityResult>;
issue(
command: IssueLocalOwnerBootstrapChallengeCommand,
): Promise<IssueLocalOwnerBootstrapChallengeResult>;
claim(command: ClaimLocalOwnerCommand): Promise<ClaimLocalOwnerResult>;
recordAudit(audit: SecurityAuditRecord): Promise<void>;
}
export class InvalidLocalOwnerBootstrapValueError extends TypeError {
constructor(message: string) {
super(`Local owner bootstrap value is invalid: ${message}`);
this.name = 'InvalidLocalOwnerBootstrapValueError';
}
}
export class LocalOwnerBootstrapNotPristineError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_NOT_PRISTINE';
constructor() {
super('Local owner bootstrap is no longer available');
this.name = 'LocalOwnerBootstrapNotPristineError';
}
}
export class LocalOwnerBootstrapChallengeActiveError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_CHALLENGE_ACTIVE';
constructor() {
super('A local owner bootstrap challenge is already active');
this.name = 'LocalOwnerBootstrapChallengeActiveError';
}
}
export class LocalOwnerBootstrapIdentityRequiredError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_IDENTITY_REQUIRED';
constructor() {
super('A provisioned local identity is required');
this.name = 'LocalOwnerBootstrapIdentityRequiredError';
}
}
export class LocalOwnerBootstrapClaimRejectedError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_CLAIM_REJECTED';
constructor() {
super('Local owner bootstrap claim was rejected');
this.name = 'LocalOwnerBootstrapClaimRejectedError';
}
}
export class LocalOwnerBootstrapMutationConflictError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_MUTATION_CONFLICT';
constructor() {
super('Local owner bootstrap mutation conflicts with previous use');
this.name = 'LocalOwnerBootstrapMutationConflictError';
}
}
export class LocalOwnerBootstrapUnavailableError extends Error {
readonly code = 'LOCAL_OWNER_BOOTSTRAP_UNAVAILABLE';
constructor() {
super('Local owner bootstrap is unavailable');
this.name = 'LocalOwnerBootstrapUnavailableError';
}
}
function exactKeys(
value: object,
expected: readonly string[],
name: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidLocalOwnerBootstrapValueError(`${name} shape is invalid`);
}
}
function timestamp(value: number, name: string): number {
if (!Number.isSafeInteger(value) || value < 0) {
throw new InvalidLocalOwnerBootstrapValueError(`${name} is invalid`);
}
return value;
}
export function assertLocalOwnerBootstrapMutationId(value: string): void {
if (typeof value !== 'string' || !UUID_V4_PATTERN.test(value)) {
throw new InvalidLocalOwnerBootstrapValueError('mutationId is invalid');
}
}
export function assertLocalOwnerBootstrapRequestId(value: string): void {
if (typeof value !== 'string' || !REQUEST_ID_PATTERN.test(value)) {
throw new InvalidLocalOwnerBootstrapValueError('requestId is invalid');
}
}
export function assertLocalOwnerBootstrapChallengeId(value: string): void {
if (typeof value !== 'string' || !CHALLENGE_ID_PATTERN.test(value)) {
throw new InvalidLocalOwnerBootstrapValueError('challengeId is invalid');
}
}
export function assertLocalOwnerBootstrapToken(value: string): void {
if (typeof value !== 'string' || !TOKEN_PATTERN.test(value)) {
throw new InvalidLocalOwnerBootstrapValueError('token is invalid');
}
}
export function assertLocalOwnerBootstrapTokenDigest(value: string): void {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidLocalOwnerBootstrapValueError('tokenDigest is invalid');
}
}
export function assertLocalOwnerBootstrapTtl(value: number): void {
if (
!Number.isSafeInteger(value) ||
value < LOCAL_OWNER_BOOTSTRAP_MIN_TTL_MS ||
value > LOCAL_OWNER_BOOTSTRAP_MAX_TTL_MS
) {
throw new InvalidLocalOwnerBootstrapValueError('ttlMs is invalid');
}
}
export function normalizeLocalOwnerSecretDeliveryAcknowledgementRecord(
value: LocalOwnerSecretDeliveryAcknowledgementRecord,
): Readonly<LocalOwnerSecretDeliveryAcknowledgementRecord> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerBootstrapValueError(
'delivery acknowledgement must be an object',
);
}
assertLocalOwnerBootstrapMutationId(value.mutationId);
assertLocalOwnerBootstrapRequestId(value.requestId);
assertLocalOwnerBootstrapTokenDigest(value.factDigest);
assertLocalOwnerBootstrapTokenDigest(value.deliveryDigest);
if (
!Number.isSafeInteger(value.ttlMs) ||
value.ttlMs < 1 ||
!Number.isSafeInteger(value.acknowledgedAtMs) ||
value.acknowledgedAtMs < 0
) {
throw new InvalidLocalOwnerBootstrapValueError(
'delivery acknowledgement lifetime is invalid',
);
}
if (value.kind === 'credential') {
exactKeys(
value,
[
'kind',
'mutationId',
'requestId',
'subjectId',
'credentialId',
'factDigest',
'ttlMs',
'deliveryDigest',
'acknowledgedAtMs',
],
'credential delivery acknowledgement',
);
if (
!/^usr_[A-Za-z0-9_-]{22}$/.test(value.subjectId) ||
!/^own_[A-Za-z0-9_-]{22}$/.test(value.credentialId)
) {
throw new InvalidLocalOwnerBootstrapValueError(
'credential delivery acknowledgement identity is invalid',
);
}
return Object.freeze({ ...value });
}
if (value.kind !== 'challenge') {
throw new InvalidLocalOwnerBootstrapValueError(
'delivery acknowledgement kind is invalid',
);
}
exactKeys(
value,
[
'kind',
'projectId',
'mutationId',
'requestId',
'challengeId',
'factDigest',
'ttlMs',
'deliveryDigest',
'acknowledgedAtMs',
],
'challenge delivery acknowledgement',
);
assertProjectPolicyProjectId(value.projectId);
assertLocalOwnerBootstrapChallengeId(value.challengeId);
return Object.freeze({ ...value });
}
export function localOwnerSecretDeliveryAcknowledgementSemanticDigest(
value: LocalOwnerSecretDeliveryAcknowledgementRecord,
): string {
const record = normalizeLocalOwnerSecretDeliveryAcknowledgementRecord(value);
const hash = createHash('sha256')
.update('qinglong.local-owner-delivery-acknowledgement.v1\0', 'utf8')
.update(record.kind, 'utf8')
.update('\0', 'utf8')
.update(record.mutationId, 'utf8')
.update('\0', 'utf8')
.update(record.requestId, 'utf8')
.update('\0', 'utf8');
if (record.kind === 'credential') {
hash
.update(record.subjectId, 'utf8')
.update('\0', 'utf8')
.update(record.credentialId, 'utf8');
} else {
hash
.update(record.projectId, 'utf8')
.update('\0', 'utf8')
.update(record.challengeId, 'utf8');
}
return hash
.update('\0', 'utf8')
.update(record.factDigest, 'utf8')
.update('\0', 'utf8')
.update(record.deliveryDigest, 'utf8')
.update('\0', 'utf8')
.update(String(record.ttlMs), 'utf8')
.update('\0', 'utf8')
.update(String(record.acknowledgedAtMs), 'utf8')
.digest('hex');
}
export function localOwnerBootstrapTokenDigest(
projectId: string,
challengeId: string,
token: string,
): string {
if (typeof projectId !== 'string' || !REQUEST_ID_PATTERN.test(projectId)) {
throw new InvalidLocalOwnerBootstrapValueError('projectId is invalid');
}
assertLocalOwnerBootstrapChallengeId(challengeId);
assertLocalOwnerBootstrapToken(token);
return createHash('sha256')
.update(DIGEST_DOMAIN, 'utf8')
.update(projectId, 'utf8')
.update('\0', 'utf8')
.update(challengeId, 'utf8')
.update('\0', 'utf8')
.update(token, 'utf8')
.digest('hex');
}
export function localOwnerBootstrapDigestMatches(
expected: string,
actual: string,
): boolean {
assertLocalOwnerBootstrapTokenDigest(expected);
assertLocalOwnerBootstrapTokenDigest(actual);
const left = Buffer.from(expected, 'hex');
const right = Buffer.from(actual, 'hex');
try {
return timingSafeEqual(left, right);
} finally {
left.fill(0);
right.fill(0);
}
}
function localConsolePrincipal(
value: SecurityPrincipal,
nowMs: number,
): Readonly<SecurityPrincipal> {
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(value, nowMs);
} catch {
throw new InvalidLocalOwnerBootstrapValueError('issuer is invalid');
}
if (
principal.subject.type !== LOCAL_OWNER_BOOTSTRAP_SYSTEM_SUBJECT.type ||
principal.subject.id !== LOCAL_OWNER_BOOTSTRAP_SYSTEM_SUBJECT.id ||
principal.assurance !== 'local_console'
) {
throw new InvalidLocalOwnerBootstrapValueError('issuer is invalid');
}
return principal;
}
function userPrincipal(
value: SecurityPrincipal,
nowMs: number,
): Readonly<SecurityPrincipal> {
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(value, nowMs);
} catch {
throw new InvalidLocalOwnerBootstrapValueError('principal is invalid');
}
if (principal.subject.type !== 'user') {
throw new InvalidLocalOwnerBootstrapValueError('principal is invalid');
}
return principal;
}
export function normalizeLocalIdentityProvisioningRecord(
value: LocalIdentityProvisioningRecord,
): Readonly<LocalIdentityProvisioningRecord> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerBootstrapValueError(
'provisioning must be an object',
);
}
exactKeys(
value,
[
'mutationId',
'requestId',
'identity',
'credential',
'issuer',
'audit',
'createdAtMs',
],
'provisioning',
);
assertLocalOwnerBootstrapMutationId(value.mutationId);
assertLocalOwnerBootstrapRequestId(value.requestId);
const createdAtMs = timestamp(value.createdAtMs, 'createdAtMs');
const identity = normalizeIdentitySubjectRecord(value.identity);
const credential = normalizeApiCredentialRecord(value.credential);
const issuer = localConsolePrincipal(value.issuer, createdAtMs);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
identity.subject.type !== 'user' ||
identity.status !== 'active' ||
identity.version !== 1 ||
identity.createdAtMs !== createdAtMs ||
identity.updatedAtMs !== createdAtMs ||
credential.subject.type !== identity.subject.type ||
credential.subject.id !== identity.subject.id ||
credential.subjectStatus !== 'active' ||
credential.version !== 1 ||
credential.state !== 'active' ||
credential.createdAtMs !== createdAtMs ||
credential.notBeforeAtMs !== createdAtMs ||
audit.eventId !== value.mutationId ||
audit.requestId !== value.requestId ||
audit.operationId !== 'identity.bootstrap_provision' ||
audit.projectId !== null ||
audit.subject?.type !== issuer.subject.type ||
audit.subject.id !== issuer.subject.id ||
audit.authenticationId !== issuer.authenticationId ||
audit.outcome !== 'allowed' ||
audit.reasons.length !== 1 ||
audit.reasons[0] !== 'local_console_provisioning' ||
audit.fence !== null ||
audit.occurredAtMs !== createdAtMs
) {
throw new InvalidLocalOwnerBootstrapValueError(
'provisioning semantics are invalid',
);
}
return Object.freeze({
mutationId: value.mutationId,
requestId: value.requestId,
identity,
credential,
issuer,
audit,
createdAtMs,
});
}
export function normalizeIssueLocalOwnerBootstrapChallengeCommand(
value: IssueLocalOwnerBootstrapChallengeCommand,
): Readonly<IssueLocalOwnerBootstrapChallengeCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerBootstrapValueError('issue must be an object');
}
exactKeys(
value,
[
'projectId',
'mutationId',
'requestId',
'challengeId',
'tokenDigest',
'issuer',
'issuedAtMs',
'expiresAtMs',
'audit',
],
'issue',
);
if (
typeof value.projectId !== 'string' ||
!REQUEST_ID_PATTERN.test(value.projectId)
) {
throw new InvalidLocalOwnerBootstrapValueError('projectId is invalid');
}
assertLocalOwnerBootstrapMutationId(value.mutationId);
assertLocalOwnerBootstrapRequestId(value.requestId);
assertLocalOwnerBootstrapChallengeId(value.challengeId);
assertLocalOwnerBootstrapTokenDigest(value.tokenDigest);
const issuedAtMs = timestamp(value.issuedAtMs, 'issuedAtMs');
const expiresAtMs = timestamp(value.expiresAtMs, 'expiresAtMs');
assertLocalOwnerBootstrapTtl(expiresAtMs - issuedAtMs);
const issuer = localConsolePrincipal(value.issuer, issuedAtMs);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.eventId !== value.mutationId ||
audit.requestId !== value.requestId ||
audit.operationId !== 'project.owner_bootstrap_issue' ||
audit.projectId !== value.projectId ||
audit.subject?.type !== issuer.subject.type ||
audit.subject.id !== issuer.subject.id ||
audit.authenticationId !== issuer.authenticationId ||
audit.outcome !== 'allowed' ||
audit.reasons.length !== 1 ||
audit.reasons[0] !== 'local_console_challenge' ||
audit.fence !== null ||
audit.occurredAtMs !== issuedAtMs
) {
throw new InvalidLocalOwnerBootstrapValueError('issue audit is invalid');
}
return Object.freeze({ ...value, issuer, audit, issuedAtMs, expiresAtMs });
}
export function normalizeClaimLocalOwnerCommand(
value: ClaimLocalOwnerCommand,
): Readonly<ClaimLocalOwnerCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerBootstrapValueError('claim must be an object');
}
exactKeys(
value,
[
'projectId',
'mutationId',
'requestId',
'challengeId',
'tokenDigest',
'principal',
'credentialId',
'credentialVersion',
'claimedAtMs',
'audit',
],
'claim',
);
if (
typeof value.projectId !== 'string' ||
!REQUEST_ID_PATTERN.test(value.projectId)
) {
throw new InvalidLocalOwnerBootstrapValueError('projectId is invalid');
}
assertLocalOwnerBootstrapMutationId(value.mutationId);
assertLocalOwnerBootstrapRequestId(value.requestId);
assertLocalOwnerBootstrapChallengeId(value.challengeId);
assertLocalOwnerBootstrapTokenDigest(value.tokenDigest);
const claimedAtMs = timestamp(value.claimedAtMs, 'claimedAtMs');
const principal = userPrincipal(value.principal, claimedAtMs);
if (principal.assurance !== 'single_factor') {
throw new InvalidLocalOwnerBootstrapValueError(
'claim principal assurance is invalid',
);
}
if (
typeof value.credentialId !== 'string' ||
value.credentialId.length < 1 ||
value.credentialId.length > 64 ||
!Number.isSafeInteger(value.credentialVersion) ||
value.credentialVersion < 1 ||
value.credentialVersion > MAX_VERSION
) {
throw new InvalidLocalOwnerBootstrapValueError(
'credential fence is invalid',
);
}
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.eventId !== value.mutationId ||
audit.requestId !== value.requestId ||
audit.operationId !== 'project.owner_bootstrap_claim' ||
audit.projectId !== value.projectId ||
audit.subject?.type !== principal.subject.type ||
audit.subject.id !== principal.subject.id ||
audit.authenticationId !== principal.authenticationId ||
audit.outcome !== 'allowed' ||
audit.reasons.length !== 1 ||
audit.reasons[0] !== 'owner_bootstrap_claim' ||
audit.fence?.bindingVersion !== 1 ||
audit.occurredAtMs !== claimedAtMs
) {
throw new InvalidLocalOwnerBootstrapValueError('claim audit is invalid');
}
return Object.freeze({ ...value, principal, audit, claimedAtMs });
}
export function normalizeLocalOwnerBootstrapChallengeRecord(
value: LocalOwnerBootstrapChallengeRecord,
): Readonly<LocalOwnerBootstrapChallengeRecord> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerBootstrapValueError(
'challenge must be an object',
);
}
const consumed = value.consumedAtMs !== undefined;
exactKeys(
value,
consumed
? [
'projectId',
'version',
'issueMutationId',
'issueRequestId',
'challengeId',
'tokenDigest',
'issuer',
'issuedAtMs',
'expiresAtMs',
'issueAudit',
'consumedAtMs',
'claimMutationId',
'claimRequestId',
'claimedPrincipal',
'credentialId',
'credentialVersion',
'binding',
'claimAudit',
]
: [
'projectId',
'version',
'issueMutationId',
'issueRequestId',
'challengeId',
'tokenDigest',
'issuer',
'issuedAtMs',
'expiresAtMs',
'issueAudit',
],
'challenge',
);
const issue = normalizeIssueLocalOwnerBootstrapChallengeCommand({
projectId: value.projectId,
mutationId: value.issueMutationId,
requestId: value.issueRequestId,
challengeId: value.challengeId,
tokenDigest: value.tokenDigest,
issuer: value.issuer,
issuedAtMs: value.issuedAtMs,
expiresAtMs: value.expiresAtMs,
audit: value.issueAudit,
});
if (
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
value.version > MAX_VERSION
) {
throw new InvalidLocalOwnerBootstrapValueError('version is invalid');
}
if (!consumed) {
return Object.freeze({
projectId: issue.projectId,
version: value.version,
issueMutationId: issue.mutationId,
issueRequestId: issue.requestId,
challengeId: issue.challengeId,
tokenDigest: issue.tokenDigest,
issuer: issue.issuer,
issuedAtMs: issue.issuedAtMs,
expiresAtMs: issue.expiresAtMs,
issueAudit: issue.audit,
});
}
const claim = normalizeClaimLocalOwnerCommand({
projectId: value.projectId,
mutationId: value.claimMutationId!,
requestId: value.claimRequestId!,
challengeId: value.challengeId,
tokenDigest: value.tokenDigest,
principal: value.claimedPrincipal!,
credentialId: value.credentialId!,
credentialVersion: value.credentialVersion!,
claimedAtMs: value.consumedAtMs!,
audit: value.claimAudit!,
});
const binding = normalizeProjectRoleBinding(value.binding!);
if (
binding.projectId !== value.projectId ||
binding.subject.type !== claim.principal.subject.type ||
binding.subject.id !== claim.principal.subject.id ||
binding.version !== 1 ||
binding.state !== 'active' ||
binding.role !== 'owner' ||
binding.mutationId !== claim.mutationId ||
binding.changedBy.type !== LOCAL_OWNER_BOOTSTRAP_SYSTEM_SUBJECT.type ||
binding.changedBy.id !== LOCAL_OWNER_BOOTSTRAP_SYSTEM_SUBJECT.id ||
binding.createdAtMs !== claim.claimedAtMs
) {
throw new InvalidLocalOwnerBootstrapValueError(
'claimed binding is invalid',
);
}
return Object.freeze({
projectId: issue.projectId,
version: value.version,
issueMutationId: issue.mutationId,
issueRequestId: issue.requestId,
challengeId: issue.challengeId,
tokenDigest: issue.tokenDigest,
issuer: issue.issuer,
issuedAtMs: issue.issuedAtMs,
expiresAtMs: issue.expiresAtMs,
issueAudit: issue.audit,
consumedAtMs: claim.claimedAtMs,
claimMutationId: claim.mutationId,
claimRequestId: claim.requestId,
claimedPrincipal: claim.principal,
credentialId: claim.credentialId,
credentialVersion: claim.credentialVersion,
binding,
claimAudit: claim.audit,
});
}
@@ -0,0 +1,441 @@
import {
REVOKED_API_CREDENTIAL_DIGEST,
type ApiCredentialMutationRecord,
} from '../security/identity-credential/apiCredentialAdministration';
import {
assertApiCredentialId,
normalizeApiCredentialRecord,
type ApiCredentialRecord,
} from '../security/identity-credential/apiCredential';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../security/audit/securityAudit';
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const MAX_VERSION = 2_147_483_647;
export type LocalOwnerCredentialRecoveryState =
| 'issued'
| 'acknowledged'
| 'completed';
export interface LocalOwnerCredentialRecoveryRecord {
readonly issueMutationId: string;
readonly issueRequestId: string;
readonly subjectId: string;
readonly previousCredentialId: string;
readonly previousCredentialVersion: number;
readonly replacementCredential: Readonly<ApiCredentialRecord>;
readonly state: LocalOwnerCredentialRecoveryState;
readonly issuedAtMs: number;
readonly deliveryDigest?: string;
readonly acknowledgedAtMs?: number;
readonly completeMutationId?: string;
readonly completeRequestId?: string;
readonly revokedCredentialVersion?: number;
readonly completedAtMs?: number;
}
export interface IssueLocalOwnerCredentialRecoveryCommand {
readonly mutationId: string;
readonly requestId: string;
readonly previousCredentialId: string;
readonly expectedPreviousVersion: number;
readonly replacementCredential: ApiCredentialRecord;
readonly mutation: ApiCredentialMutationRecord;
readonly audit: SecurityAuditRecord;
}
export interface AcknowledgeLocalOwnerCredentialRecoveryCommand {
readonly issueMutationId: string;
readonly requestId: string;
readonly credentialId: string;
readonly factDigest: string;
readonly deliveryDigest: string;
readonly acknowledgedAtMs: number;
}
export interface CompleteLocalOwnerCredentialRecoveryCommand {
readonly issueMutationId: string;
readonly mutationId: string;
readonly requestId: string;
readonly expectedPreviousVersion: number;
readonly revokedCredential: ApiCredentialRecord;
readonly mutation: ApiCredentialMutationRecord;
readonly audit: SecurityAuditRecord;
}
export interface LocalOwnerCredentialRecoveryResult {
readonly status: 'inserted' | 'existing';
readonly recovery: Readonly<LocalOwnerCredentialRecoveryRecord>;
}
export interface LocalOwnerCredentialRecoveryRepository {
resolve(
issueMutationId: string,
): Promise<Readonly<LocalOwnerCredentialRecoveryRecord> | null>;
issue(
command: IssueLocalOwnerCredentialRecoveryCommand,
): Promise<LocalOwnerCredentialRecoveryResult>;
acknowledge(
command: AcknowledgeLocalOwnerCredentialRecoveryCommand,
): Promise<LocalOwnerCredentialRecoveryResult>;
complete(
command: CompleteLocalOwnerCredentialRecoveryCommand,
): Promise<LocalOwnerCredentialRecoveryResult>;
}
export class InvalidLocalOwnerCredentialRecoveryValueError extends TypeError {
constructor(message: string) {
super(`Local Owner credential recovery value is invalid: ${message}`);
this.name = 'InvalidLocalOwnerCredentialRecoveryValueError';
}
}
export class LocalOwnerCredentialRecoveryMutationConflictError extends Error {
readonly code = 'LOCAL_OWNER_CREDENTIAL_RECOVERY_MUTATION_CONFLICT';
constructor() {
super(
'Local Owner credential recovery mutation conflicts with previous use',
);
this.name = 'LocalOwnerCredentialRecoveryMutationConflictError';
}
}
export class LocalOwnerCredentialRecoveryInProgressError extends Error {
readonly code = 'LOCAL_OWNER_CREDENTIAL_RECOVERY_IN_PROGRESS';
constructor() {
super('A Local Owner credential recovery is already in progress');
this.name = 'LocalOwnerCredentialRecoveryInProgressError';
}
}
export class LocalOwnerCredentialRecoveryNotAcknowledgedError extends Error {
readonly code = 'LOCAL_OWNER_CREDENTIAL_RECOVERY_NOT_ACKNOWLEDGED';
constructor() {
super('Replacement credential delivery has not been acknowledged');
this.name = 'LocalOwnerCredentialRecoveryNotAcknowledgedError';
}
}
export class LocalOwnerCredentialRecoveryCredentialUnavailableError extends Error {
readonly code = 'LOCAL_OWNER_CREDENTIAL_RECOVERY_CREDENTIAL_UNAVAILABLE';
constructor() {
super('Local Owner credential is unavailable for recovery');
this.name = 'LocalOwnerCredentialRecoveryCredentialUnavailableError';
}
}
export class LocalOwnerCredentialRecoveryRepositoryUnavailableError extends Error {
readonly code = 'LOCAL_OWNER_CREDENTIAL_RECOVERY_REPOSITORY_UNAVAILABLE';
constructor() {
super('Local Owner credential recovery repository is unavailable');
this.name = 'LocalOwnerCredentialRecoveryRepositoryUnavailableError';
}
}
function exactKeys(value: object, expected: readonly string[]): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'object shape is invalid',
);
}
}
function mutationId(value: unknown, field: string): string {
if (typeof value !== 'string' || !UUID_V4_PATTERN.test(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
`${field} is invalid`,
);
}
return value;
}
function requestId(value: unknown): string {
if (typeof value !== 'string' || !REQUEST_ID_PATTERN.test(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'requestId is invalid',
);
}
return value;
}
function version(value: unknown, field: string): number {
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 1 ||
value > MAX_VERSION
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
`${field} is invalid`,
);
}
return value;
}
function timestamp(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
`${field} is invalid`,
);
}
return value;
}
function digest(value: unknown, field: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
`${field} is invalid`,
);
}
return value;
}
function normalizedMutation(
value: ApiCredentialMutationRecord,
operation: 'issue' | 'revoke',
credential: Readonly<ApiCredentialRecord>,
expectedPreviousVersion: number,
): Readonly<ApiCredentialMutationRecord> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'mutation is invalid',
);
}
exactKeys(value, [
'mutationId',
'operation',
'credentialId',
'credentialVersion',
'expectedPreviousVersion',
'changedBy',
'createdAtMs',
]);
mutationId(value.mutationId, 'mutation.mutationId');
if (
value.operation !== operation ||
value.credentialId !== credential.credentialId ||
value.credentialVersion !== credential.version ||
value.expectedPreviousVersion !== expectedPreviousVersion ||
value.createdAtMs !== credential.createdAtMs ||
value.changedBy.type !== 'system' ||
value.changedBy.id !== 'owner-credential-recovery'
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'mutation semantic is invalid',
);
}
return Object.freeze({
...value,
changedBy: Object.freeze({ ...value.changedBy }),
});
}
function normalizedAudit(
value: SecurityAuditRecord,
mutation: Readonly<ApiCredentialMutationRecord>,
request: string,
): Readonly<SecurityAuditRecord> {
const audit = normalizeSecurityAuditRecord(value);
if (
audit.eventId !== mutation.mutationId ||
audit.requestId !== request ||
audit.operationId !== `credential.${mutation.operation}` ||
audit.projectId !== null ||
audit.subject?.type !== 'system' ||
audit.subject.id !== 'owner-credential-recovery' ||
audit.authenticationId !== 'local-owner-console' ||
audit.outcome !== 'allowed' ||
audit.reasons.length !== 1 ||
audit.reasons[0] !== 'credential_recovery' ||
audit.fence !== null ||
audit.occurredAtMs !== mutation.createdAtMs
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'audit semantic is invalid',
);
}
return audit;
}
export function normalizeIssueLocalOwnerCredentialRecoveryCommand(
value: IssueLocalOwnerCredentialRecoveryCommand,
): Readonly<IssueLocalOwnerCredentialRecoveryCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'command is invalid',
);
}
exactKeys(value, [
'mutationId',
'requestId',
'previousCredentialId',
'expectedPreviousVersion',
'replacementCredential',
'mutation',
'audit',
]);
const issueMutationId = mutationId(value.mutationId, 'mutationId');
const issueRequestId = requestId(value.requestId);
try {
assertApiCredentialId(value.previousCredentialId);
} catch {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'previousCredentialId is invalid',
);
}
const expectedPreviousVersion = version(
value.expectedPreviousVersion,
'expectedPreviousVersion',
);
const replacementCredential = normalizeApiCredentialRecord(
value.replacementCredential,
);
if (
replacementCredential.credentialId === value.previousCredentialId ||
replacementCredential.version !== 1 ||
replacementCredential.state !== 'active' ||
replacementCredential.subject.type !== 'user' ||
replacementCredential.subjectStatus !== 'active'
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'replacement credential is invalid',
);
}
const mutation = normalizedMutation(
value.mutation,
'issue',
replacementCredential,
0,
);
if (mutation.mutationId !== issueMutationId) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'issue mutation identity is invalid',
);
}
return Object.freeze({
mutationId: issueMutationId,
requestId: issueRequestId,
previousCredentialId: value.previousCredentialId,
expectedPreviousVersion,
replacementCredential,
mutation,
audit: normalizedAudit(value.audit, mutation, issueRequestId),
});
}
export function normalizeAcknowledgeLocalOwnerCredentialRecoveryCommand(
value: AcknowledgeLocalOwnerCredentialRecoveryCommand,
): Readonly<AcknowledgeLocalOwnerCredentialRecoveryCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'command is invalid',
);
}
exactKeys(value, [
'issueMutationId',
'requestId',
'credentialId',
'factDigest',
'deliveryDigest',
'acknowledgedAtMs',
]);
const issueMutationId = mutationId(value.issueMutationId, 'issueMutationId');
const normalizedRequestId = requestId(value.requestId);
try {
assertApiCredentialId(value.credentialId);
} catch {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'credentialId is invalid',
);
}
return Object.freeze({
issueMutationId,
requestId: normalizedRequestId,
credentialId: value.credentialId,
factDigest: digest(value.factDigest, 'factDigest'),
deliveryDigest: digest(value.deliveryDigest, 'deliveryDigest'),
acknowledgedAtMs: timestamp(value.acknowledgedAtMs, 'acknowledgedAtMs'),
});
}
export function normalizeCompleteLocalOwnerCredentialRecoveryCommand(
value: CompleteLocalOwnerCredentialRecoveryCommand,
): Readonly<CompleteLocalOwnerCredentialRecoveryCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'command is invalid',
);
}
exactKeys(value, [
'issueMutationId',
'mutationId',
'requestId',
'expectedPreviousVersion',
'revokedCredential',
'mutation',
'audit',
]);
const issueMutationId = mutationId(value.issueMutationId, 'issueMutationId');
const completeMutationId = mutationId(value.mutationId, 'mutationId');
if (completeMutationId === issueMutationId) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'completion mutation must be distinct',
);
}
const completeRequestId = requestId(value.requestId);
const expectedPreviousVersion = version(
value.expectedPreviousVersion,
'expectedPreviousVersion',
);
const revokedCredential = normalizeApiCredentialRecord(
value.revokedCredential,
);
if (
revokedCredential.state !== 'revoked' ||
revokedCredential.version !== expectedPreviousVersion + 1 ||
revokedCredential.subject.type !== 'user' ||
revokedCredential.secretDigest !== REVOKED_API_CREDENTIAL_DIGEST ||
revokedCredential.notBeforeAtMs !== revokedCredential.createdAtMs ||
revokedCredential.expiresAtMs !== revokedCredential.createdAtMs + 1
) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'revoked credential is invalid',
);
}
const mutation = normalizedMutation(
value.mutation,
'revoke',
revokedCredential,
expectedPreviousVersion,
);
if (mutation.mutationId !== completeMutationId) {
throw new InvalidLocalOwnerCredentialRecoveryValueError(
'completion mutation identity is invalid',
);
}
return Object.freeze({
issueMutationId,
mutationId: completeMutationId,
requestId: completeRequestId,
expectedPreviousVersion,
revokedCredential,
mutation,
audit: normalizedAudit(value.audit, mutation, completeRequestId),
});
}
@@ -0,0 +1,336 @@
import { createHash } from 'node:crypto';
import {
assertLocalOwnerBootstrapMutationId,
assertLocalOwnerBootstrapRequestId,
} from './localOwnerBootstrap';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../security/audit/securityAudit';
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const DAY_MS = 86_400_000;
export const MIN_LOCAL_OWNER_ACKNOWLEDGEMENT_REPLAY_RETENTION_MS = 30 * DAY_MS;
export const MIN_LOCAL_OWNER_ACKNOWLEDGEMENT_AUDIT_RETENTION_MS = 30 * DAY_MS;
export const MAX_LOCAL_OWNER_ACKNOWLEDGEMENT_RETENTION_MS = 10 * 365 * DAY_MS;
export interface LocalOwnerDeliveryAcknowledgementGcRetentionPolicy {
readonly version: 1;
readonly replayRetentionMs: number;
readonly auditRetentionMs: number;
}
export interface LocalOwnerDeliveryBridgeClearEvidence {
readonly kind: 'credential' | 'challenge';
readonly acknowledgementMutationId: string;
readonly inspectedAtMs: number;
readonly evidenceDigest: string;
}
export interface CompactLocalOwnerDeliveryAcknowledgementCommand {
readonly mutationId: string;
readonly requestId: string;
readonly acknowledgementMutationId: string;
readonly expectedKind: 'credential' | 'challenge';
readonly expectedDeliveryDigest: string;
readonly bridgeClearEvidence: LocalOwnerDeliveryBridgeClearEvidence;
readonly retentionPolicy: LocalOwnerDeliveryAcknowledgementGcRetentionPolicy;
readonly compactedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface LocalOwnerDeliveryAcknowledgementGcRecord {
readonly mutationId: string;
readonly requestId: string;
readonly acknowledgementMutationId: string;
readonly acknowledgementKind: 'credential' | 'challenge';
readonly deliveryDigest: string;
readonly acknowledgedAtMs: number;
readonly acknowledgementSemanticDigest: string;
readonly bridgeClearEvidenceDigest: string;
readonly retentionPolicy: Readonly<LocalOwnerDeliveryAcknowledgementGcRetentionPolicy>;
readonly retentionPolicyDigest: string;
readonly retentionEligibleAtMs: number;
readonly compactedAtMs: number;
}
export interface LocalOwnerDeliveryAcknowledgementGcResult {
readonly status: 'inserted' | 'existing';
readonly record: Readonly<LocalOwnerDeliveryAcknowledgementGcRecord>;
}
export interface LocalOwnerDeliveryAcknowledgementGcRepository {
resolveByAcknowledgement(
acknowledgementMutationId: string,
): Promise<Readonly<LocalOwnerDeliveryAcknowledgementGcRecord> | null>;
compact(
command: CompactLocalOwnerDeliveryAcknowledgementCommand,
): Promise<Readonly<LocalOwnerDeliveryAcknowledgementGcResult>>;
}
export class InvalidLocalOwnerDeliveryAcknowledgementGcValueError extends TypeError {
constructor(message: string) {
super(
`Local Owner delivery acknowledgement GC value is invalid: ${message}`,
);
this.name = 'InvalidLocalOwnerDeliveryAcknowledgementGcValueError';
}
}
export class LocalOwnerDeliveryAcknowledgementGcMutationConflictError extends Error {
readonly code = 'LOCAL_OWNER_DELIVERY_ACKNOWLEDGEMENT_GC_MUTATION_CONFLICT';
constructor() {
super('Local Owner delivery acknowledgement GC mutation conflicts');
this.name = 'LocalOwnerDeliveryAcknowledgementGcMutationConflictError';
}
}
export class LocalOwnerDeliveryAcknowledgementGcRetentionPendingError extends Error {
readonly code = 'LOCAL_OWNER_DELIVERY_ACKNOWLEDGEMENT_GC_RETENTION_PENDING';
constructor(readonly eligibleAtMs: number) {
super('Local Owner delivery acknowledgement retention has not elapsed');
this.name = 'LocalOwnerDeliveryAcknowledgementGcRetentionPendingError';
}
}
export class LocalOwnerDeliveryAcknowledgementGcReferenceConflictError extends Error {
readonly code = 'LOCAL_OWNER_DELIVERY_ACKNOWLEDGEMENT_GC_REFERENCE_CONFLICT';
constructor() {
super('Local Owner delivery acknowledgement source is still active');
this.name = 'LocalOwnerDeliveryAcknowledgementGcReferenceConflictError';
}
}
export class LocalOwnerDeliveryAcknowledgementGcRepositoryUnavailableError extends Error {
readonly code =
'LOCAL_OWNER_DELIVERY_ACKNOWLEDGEMENT_GC_REPOSITORY_UNAVAILABLE';
constructor() {
super('Local Owner delivery acknowledgement GC repository is unavailable');
this.name = 'LocalOwnerDeliveryAcknowledgementGcRepositoryUnavailableError';
}
}
function exactKeys(value: object, expected: readonly string[]): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'object shape is invalid',
);
}
}
function mutationId(value: unknown, field: string): string {
try {
assertLocalOwnerBootstrapMutationId(value as string);
} catch {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
`${field} is invalid`,
);
}
return value as string;
}
function requestId(value: unknown): string {
try {
assertLocalOwnerBootstrapRequestId(value as string);
} catch {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'requestId is invalid',
);
}
return value as string;
}
function digest(value: unknown, field: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
`${field} is invalid`,
);
}
return value;
}
function timestamp(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
`${field} is invalid`,
);
}
return value;
}
function retention(
value: unknown,
): Readonly<LocalOwnerDeliveryAcknowledgementGcRetentionPolicy> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'retentionPolicy is invalid',
);
}
exactKeys(value, ['version', 'replayRetentionMs', 'auditRetentionMs']);
const policy = value as Record<string, unknown>;
const replayRetentionMs = timestamp(
policy.replayRetentionMs,
'replayRetentionMs',
);
const auditRetentionMs = timestamp(
policy.auditRetentionMs,
'auditRetentionMs',
);
if (
policy.version !== 1 ||
replayRetentionMs < MIN_LOCAL_OWNER_ACKNOWLEDGEMENT_REPLAY_RETENTION_MS ||
auditRetentionMs < MIN_LOCAL_OWNER_ACKNOWLEDGEMENT_AUDIT_RETENTION_MS ||
replayRetentionMs > MAX_LOCAL_OWNER_ACKNOWLEDGEMENT_RETENTION_MS ||
auditRetentionMs > MAX_LOCAL_OWNER_ACKNOWLEDGEMENT_RETENTION_MS
) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'retentionPolicy is outside the reviewed bounds',
);
}
return Object.freeze({
version: 1 as const,
replayRetentionMs,
auditRetentionMs,
});
}
function bridgeEvidence(
value: LocalOwnerDeliveryBridgeClearEvidence,
): Readonly<LocalOwnerDeliveryBridgeClearEvidence> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'bridgeClearEvidence is invalid',
);
}
exactKeys(value, [
'kind',
'acknowledgementMutationId',
'inspectedAtMs',
'evidenceDigest',
]);
if (value.kind !== 'credential' && value.kind !== 'challenge') {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'bridge kind is invalid',
);
}
return Object.freeze({
kind: value.kind,
acknowledgementMutationId: mutationId(
value.acknowledgementMutationId,
'acknowledgementMutationId',
),
inspectedAtMs: timestamp(value.inspectedAtMs, 'inspectedAtMs'),
evidenceDigest: digest(value.evidenceDigest, 'evidenceDigest'),
});
}
function audit(
value: SecurityAuditRecord,
mutation: string,
request: string,
occurredAtMs: number,
): Readonly<SecurityAuditRecord> {
const normalized = normalizeSecurityAuditRecord(value);
if (
normalized.eventId !== mutation ||
normalized.requestId !== request ||
normalized.operationId !== 'owner.delivery_acknowledgement.gc' ||
normalized.projectId !== null ||
normalized.subject?.type !== 'system' ||
normalized.subject.id !== 'owner-acknowledgement-gc' ||
normalized.authenticationId !== 'local-owner-console' ||
normalized.outcome !== 'allowed' ||
normalized.reasons.length !== 1 ||
normalized.reasons[0] !== 'delivery_acknowledgement_gc' ||
normalized.fence !== null ||
normalized.occurredAtMs !== occurredAtMs
) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'audit is not bound to the GC mutation',
);
}
return normalized;
}
export function localOwnerDeliveryAcknowledgementGcRetentionPolicyDigest(
value: LocalOwnerDeliveryAcknowledgementGcRetentionPolicy,
): string {
const policy = retention(value);
return createHash('sha256')
.update('qinglong.local-owner-delivery-acknowledgement-gc-policy.v1\0')
.update(String(policy.replayRetentionMs), 'utf8')
.update('\0', 'utf8')
.update(String(policy.auditRetentionMs), 'utf8')
.digest('hex');
}
export function normalizeCompactLocalOwnerDeliveryAcknowledgementCommand(
value: CompactLocalOwnerDeliveryAcknowledgementCommand,
): Readonly<CompactLocalOwnerDeliveryAcknowledgementCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'compact command is invalid',
);
}
exactKeys(value, [
'mutationId',
'requestId',
'acknowledgementMutationId',
'expectedKind',
'expectedDeliveryDigest',
'bridgeClearEvidence',
'retentionPolicy',
'compactedAtMs',
'audit',
]);
const normalizedMutationId = mutationId(value.mutationId, 'mutationId');
const normalizedAcknowledgementMutationId = mutationId(
value.acknowledgementMutationId,
'acknowledgementMutationId',
);
const normalizedRequestId = requestId(value.requestId);
const normalizedBridge = bridgeEvidence(value.bridgeClearEvidence);
const compactedAtMs = timestamp(value.compactedAtMs, 'compactedAtMs');
if (
normalizedMutationId === normalizedAcknowledgementMutationId ||
(value.expectedKind !== 'credential' &&
value.expectedKind !== 'challenge') ||
normalizedBridge.kind !== value.expectedKind ||
normalizedBridge.acknowledgementMutationId !==
normalizedAcknowledgementMutationId ||
normalizedBridge.inspectedAtMs !== compactedAtMs
) {
throw new InvalidLocalOwnerDeliveryAcknowledgementGcValueError(
'GC identity binding is invalid',
);
}
return Object.freeze({
mutationId: normalizedMutationId,
requestId: normalizedRequestId,
acknowledgementMutationId: normalizedAcknowledgementMutationId,
expectedKind: value.expectedKind,
expectedDeliveryDigest: digest(
value.expectedDeliveryDigest,
'expectedDeliveryDigest',
),
bridgeClearEvidence: normalizedBridge,
retentionPolicy: retention(value.retentionPolicy),
compactedAtMs,
audit: audit(
value.audit,
normalizedMutationId,
normalizedRequestId,
compactedAtMs,
),
});
}
@@ -0,0 +1,252 @@
import { assertApiCredentialPepperKeyId } from '../security/identity-credential/apiCredential';
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const MAX_VERSION = 2_147_483_647;
export const MAX_LOCAL_OWNER_PEPPER_KEYS = 8;
export type LocalOwnerPepperKeyState =
| 'recovery_required'
| 'staged'
| 'active'
| 'retired';
export interface LocalOwnerPepperKeyRecord {
readonly pepperKeyId: string;
readonly materialDigest?: string;
readonly backupDigest?: string;
readonly state: LocalOwnerPepperKeyState;
readonly version: number;
readonly registerMutationId?: string;
readonly activateMutationId?: string;
readonly retireMutationId?: string;
readonly registeredAtMs: number;
readonly activatedAtMs?: number;
readonly retiredAtMs?: number;
}
export interface LocalOwnerPepperActivationRecord {
readonly generation: number;
readonly mutationId: string;
readonly expectedGeneration: number;
readonly previousPepperKeyId?: string;
readonly activePepperKeyId: string;
readonly materialDigest: string;
readonly backupDigest: string;
readonly activatedAtMs: number;
}
export interface RegisterLocalOwnerPepperKeyCommand {
readonly mutationId: string;
readonly pepperKeyId: string;
readonly materialDigest: string;
readonly backupDigest: string;
readonly registeredAtMs: number;
}
export interface RegisterLocalOwnerPepperKeyResult {
readonly status: 'inserted' | 'existing';
readonly key: Readonly<LocalOwnerPepperKeyRecord>;
}
export interface ActivateLocalOwnerPepperKeyCommand {
readonly mutationId: string;
readonly pepperKeyId: string;
readonly expectedGeneration: number;
readonly expectedActivePepperKeyId?: string;
readonly activatedAtMs: number;
}
export interface ActivateLocalOwnerPepperKeyResult {
readonly status: 'inserted' | 'existing';
readonly activation: Readonly<LocalOwnerPepperActivationRecord>;
}
export interface LocalOwnerPepperReferenceSummary {
readonly pepperKeyId: string;
readonly inspectedAtMs: number;
readonly currentCredentialReferences: number;
readonly inFlightRecoveryReferences: number;
readonly historicalCredentialReferences: number;
readonly runtimeReferencesClear: boolean;
}
export interface LocalOwnerPepperRepository {
resolveKey(
pepperKeyId: string,
): Promise<Readonly<LocalOwnerPepperKeyRecord> | null>;
resolveActive(): Promise<Readonly<LocalOwnerPepperActivationRecord> | null>;
register(
command: RegisterLocalOwnerPepperKeyCommand,
): Promise<RegisterLocalOwnerPepperKeyResult>;
activate(
command: ActivateLocalOwnerPepperKeyCommand,
): Promise<ActivateLocalOwnerPepperKeyResult>;
}
export interface LocalOwnerPepperReferenceRepository
extends LocalOwnerPepperRepository {
inspectReferences(
pepperKeyId: string,
inspectedAtMs: number,
): Promise<Readonly<LocalOwnerPepperReferenceSummary>>;
}
export class InvalidLocalOwnerPepperValueError extends TypeError {
constructor(message: string) {
super(`Local Owner pepper value is invalid: ${message}`);
this.name = 'InvalidLocalOwnerPepperValueError';
}
}
export class LocalOwnerPepperMutationConflictError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MUTATION_CONFLICT';
constructor() {
super('Local Owner pepper mutation conflicts with previous use');
this.name = 'LocalOwnerPepperMutationConflictError';
}
}
export class LocalOwnerPepperGenerationConflictError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_GENERATION_CONFLICT';
constructor() {
super('Local Owner active pepper generation changed');
this.name = 'LocalOwnerPepperGenerationConflictError';
}
}
export class LocalOwnerPepperKeyNotActivatableError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_KEY_NOT_ACTIVATABLE';
constructor() {
super('Local Owner pepper key is not staged for activation');
this.name = 'LocalOwnerPepperKeyNotActivatableError';
}
}
export class LocalOwnerPepperCatalogFullError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_CATALOG_FULL';
constructor() {
super('Local Owner pepper catalog reached its hard key limit');
this.name = 'LocalOwnerPepperCatalogFullError';
}
}
export class LocalOwnerPepperRepositoryUnavailableError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_REPOSITORY_UNAVAILABLE';
constructor() {
super('Local Owner pepper repository is unavailable');
this.name = 'LocalOwnerPepperRepositoryUnavailableError';
}
}
function exactKeys(value: object, expected: readonly string[]): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidLocalOwnerPepperValueError('object shape is invalid');
}
}
function assertDigest(value: unknown, field: string): asserts value is string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidLocalOwnerPepperValueError(`${field} is invalid`);
}
}
function assertMutationId(value: unknown): asserts value is string {
if (typeof value !== 'string' || !UUID_V4_PATTERN.test(value)) {
throw new InvalidLocalOwnerPepperValueError('mutationId is invalid');
}
}
function assertInteger(
value: unknown,
field: string,
minimum: number,
maximum = MAX_VERSION,
): asserts value is number {
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < minimum ||
value > maximum
) {
throw new InvalidLocalOwnerPepperValueError(`${field} is invalid`);
}
}
export function normalizeRegisterLocalOwnerPepperKeyCommand(
value: RegisterLocalOwnerPepperKeyCommand,
): Readonly<RegisterLocalOwnerPepperKeyCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerPepperValueError('command is invalid');
}
exactKeys(value, [
'backupDigest',
'materialDigest',
'mutationId',
'pepperKeyId',
'registeredAtMs',
]);
assertMutationId(value.mutationId);
try {
assertApiCredentialPepperKeyId(value.pepperKeyId);
} catch {
throw new InvalidLocalOwnerPepperValueError('pepperKeyId is invalid');
}
assertDigest(value.materialDigest, 'materialDigest');
assertDigest(value.backupDigest, 'backupDigest');
assertInteger(
value.registeredAtMs,
'registeredAtMs',
0,
Number.MAX_SAFE_INTEGER,
);
return Object.freeze({ ...value });
}
export function normalizeActivateLocalOwnerPepperKeyCommand(
value: ActivateLocalOwnerPepperKeyCommand,
): Readonly<ActivateLocalOwnerPepperKeyCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerPepperValueError('command is invalid');
}
exactKeys(value, [
'activatedAtMs',
'expectedGeneration',
...(value.expectedActivePepperKeyId === undefined
? []
: ['expectedActivePepperKeyId']),
'mutationId',
'pepperKeyId',
]);
assertMutationId(value.mutationId);
try {
assertApiCredentialPepperKeyId(value.pepperKeyId);
if (value.expectedActivePepperKeyId !== undefined) {
assertApiCredentialPepperKeyId(value.expectedActivePepperKeyId);
}
} catch {
throw new InvalidLocalOwnerPepperValueError(
'pepper key identity is invalid',
);
}
assertInteger(value.expectedGeneration, 'expectedGeneration', 0);
assertInteger(
value.activatedAtMs,
'activatedAtMs',
0,
Number.MAX_SAFE_INTEGER,
);
return Object.freeze({ ...value });
}
@@ -0,0 +1,410 @@
import { createHash } from 'node:crypto';
import { assertApiCredentialPepperKeyId } from '../security/identity-credential/apiCredential';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../security/audit/securityAudit';
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const DAY_MS = 86_400_000;
export const MIN_LOCAL_OWNER_PEPPER_ACK_RETENTION_MS = 7 * DAY_MS;
export const MIN_LOCAL_OWNER_PEPPER_AUDIT_RETENTION_MS = 30 * DAY_MS;
export const MIN_LOCAL_OWNER_PEPPER_BACKUP_RETENTION_MS = 30 * DAY_MS;
export const MAX_LOCAL_OWNER_PEPPER_RETENTION_MS = 10 * 365 * DAY_MS;
export interface LocalOwnerPepperMaterialGcRetentionPolicy {
readonly version: 1;
readonly acknowledgementRetentionMs: number;
readonly auditRetentionMs: number;
readonly backupRetentionMs: number;
}
export type LocalOwnerPepperMaterialGcState = 'prepared' | 'completed';
export interface LocalOwnerPepperMaterialGcRecord {
readonly prepareMutationId: string;
readonly prepareRequestId: string;
readonly pepperKeyId: string;
readonly materialDigest: string;
readonly backupMaterialDigest: string;
readonly activePepperKeyId: string;
readonly activeGeneration: number;
readonly activeMaterialDigest: string;
readonly retentionPolicy: Readonly<LocalOwnerPepperMaterialGcRetentionPolicy>;
readonly retentionPolicyDigest: string;
readonly referencesInspectedAtMs: number;
readonly retentionEligibleAtMs: number;
readonly preparedAtMs: number;
readonly state: LocalOwnerPepperMaterialGcState;
readonly completeMutationId?: string;
readonly completeRequestId?: string;
readonly destructionProofDigest?: string;
readonly completedAtMs?: number;
}
export interface PrepareLocalOwnerPepperMaterialGcCommand {
readonly mutationId: string;
readonly requestId: string;
readonly pepperKeyId: string;
readonly expectedMaterialDigest: string;
readonly expectedBackupMaterialDigest: string;
readonly expectedActivePepperKeyId: string;
readonly expectedActiveGeneration: number;
readonly expectedActiveMaterialDigest: string;
readonly retentionPolicy: LocalOwnerPepperMaterialGcRetentionPolicy;
readonly preparedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface CompleteLocalOwnerPepperMaterialGcCommand {
readonly prepareMutationId: string;
readonly mutationId: string;
readonly requestId: string;
readonly destructionProofDigest: string;
readonly completedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface LocalOwnerPepperMaterialGcResult {
readonly status: 'inserted' | 'existing';
readonly record: Readonly<LocalOwnerPepperMaterialGcRecord>;
}
export interface LocalOwnerPepperMaterialGcRepository {
resolve(
prepareMutationId: string,
): Promise<Readonly<LocalOwnerPepperMaterialGcRecord> | null>;
prepare(
command: PrepareLocalOwnerPepperMaterialGcCommand,
): Promise<LocalOwnerPepperMaterialGcResult>;
complete(
command: CompleteLocalOwnerPepperMaterialGcCommand,
): Promise<LocalOwnerPepperMaterialGcResult>;
}
export class InvalidLocalOwnerPepperMaterialGcValueError extends TypeError {
constructor(message: string) {
super(`Local Owner pepper material GC value is invalid: ${message}`);
this.name = 'InvalidLocalOwnerPepperMaterialGcValueError';
}
}
export class LocalOwnerPepperMaterialGcMutationConflictError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MATERIAL_GC_MUTATION_CONFLICT';
constructor() {
super(
'Local Owner pepper material GC mutation conflicts with previous use',
);
this.name = 'LocalOwnerPepperMaterialGcMutationConflictError';
}
}
export class LocalOwnerPepperMaterialGcInProgressError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MATERIAL_GC_IN_PROGRESS';
constructor() {
super('A Local Owner pepper material GC is already in progress');
this.name = 'LocalOwnerPepperMaterialGcInProgressError';
}
}
export class LocalOwnerPepperMaterialGcReferenceConflictError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MATERIAL_GC_REFERENCE_CONFLICT';
constructor() {
super('Local Owner pepper material still has runtime references');
this.name = 'LocalOwnerPepperMaterialGcReferenceConflictError';
}
}
export class LocalOwnerPepperMaterialGcRetentionPendingError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MATERIAL_GC_RETENTION_PENDING';
constructor(readonly eligibleAtMs: number) {
super('Local Owner pepper material retention period has not elapsed');
this.name = 'LocalOwnerPepperMaterialGcRetentionPendingError';
}
}
export class LocalOwnerPepperMaterialGcRepositoryUnavailableError extends Error {
readonly code = 'LOCAL_OWNER_PEPPER_MATERIAL_GC_REPOSITORY_UNAVAILABLE';
constructor() {
super('Local Owner pepper material GC repository is unavailable');
this.name = 'LocalOwnerPepperMaterialGcRepositoryUnavailableError';
}
}
function exactKeys(value: object, expected: readonly string[]): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'object shape is invalid',
);
}
}
function mutationId(value: unknown, field: string): string {
if (typeof value !== 'string' || !UUID_V4_PATTERN.test(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
`${field} is invalid`,
);
}
return value;
}
function requestId(value: unknown): string {
if (typeof value !== 'string' || !REQUEST_ID_PATTERN.test(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'requestId is invalid',
);
}
return value;
}
function digest(value: unknown, field: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
`${field} is invalid`,
);
}
return value;
}
function timestamp(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
`${field} is invalid`,
);
}
return value;
}
function positiveInteger(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
`${field} is invalid`,
);
}
return value;
}
function retention(
value: unknown,
): Readonly<LocalOwnerPepperMaterialGcRetentionPolicy> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'retentionPolicy is invalid',
);
}
exactKeys(value, [
'version',
'acknowledgementRetentionMs',
'auditRetentionMs',
'backupRetentionMs',
]);
const policy = value as Record<string, unknown>;
const acknowledgementRetentionMs = positiveInteger(
policy.acknowledgementRetentionMs,
'acknowledgementRetentionMs',
);
const auditRetentionMs = positiveInteger(
policy.auditRetentionMs,
'auditRetentionMs',
);
const backupRetentionMs = positiveInteger(
policy.backupRetentionMs,
'backupRetentionMs',
);
if (
policy.version !== 1 ||
acknowledgementRetentionMs < MIN_LOCAL_OWNER_PEPPER_ACK_RETENTION_MS ||
auditRetentionMs < MIN_LOCAL_OWNER_PEPPER_AUDIT_RETENTION_MS ||
backupRetentionMs < MIN_LOCAL_OWNER_PEPPER_BACKUP_RETENTION_MS ||
acknowledgementRetentionMs > MAX_LOCAL_OWNER_PEPPER_RETENTION_MS ||
auditRetentionMs > MAX_LOCAL_OWNER_PEPPER_RETENTION_MS ||
backupRetentionMs > MAX_LOCAL_OWNER_PEPPER_RETENTION_MS
) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'retentionPolicy is outside the reviewed bounds',
);
}
return Object.freeze({
version: 1 as const,
acknowledgementRetentionMs,
auditRetentionMs,
backupRetentionMs,
});
}
function audit(
value: SecurityAuditRecord,
mutation: string,
request: string,
operation: 'prepare' | 'complete',
occurredAtMs: number,
): Readonly<SecurityAuditRecord> {
const normalized = normalizeSecurityAuditRecord(value);
if (
normalized.eventId !== mutation ||
normalized.requestId !== request ||
normalized.operationId !== `owner.pepper.material_gc.${operation}` ||
normalized.projectId !== null ||
normalized.subject === null ||
normalized.subject.type !== 'system' ||
normalized.subject.id !== 'owner-pepper-gc' ||
normalized.authenticationId !== 'local-owner-console' ||
normalized.outcome !== 'allowed' ||
normalized.reasons.length !== 1 ||
normalized.reasons[0] !== 'pepper_material_gc' ||
normalized.fence !== null ||
normalized.occurredAtMs !== occurredAtMs
) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'audit is not bound to the GC mutation',
);
}
return normalized;
}
export function localOwnerPepperMaterialGcRetentionPolicyDigest(
value: LocalOwnerPepperMaterialGcRetentionPolicy,
): string {
const policy = retention(value);
return createHash('sha256')
.update('qinglong.local-owner-pepper-material-gc-policy.v1\0', 'utf8')
.update(String(policy.acknowledgementRetentionMs), 'utf8')
.update('\0', 'utf8')
.update(String(policy.auditRetentionMs), 'utf8')
.update('\0', 'utf8')
.update(String(policy.backupRetentionMs), 'utf8')
.digest('hex');
}
export function normalizePrepareLocalOwnerPepperMaterialGcCommand(
value: PrepareLocalOwnerPepperMaterialGcCommand,
): Readonly<PrepareLocalOwnerPepperMaterialGcCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'prepare command is invalid',
);
}
exactKeys(value, [
'mutationId',
'requestId',
'pepperKeyId',
'expectedMaterialDigest',
'expectedBackupMaterialDigest',
'expectedActivePepperKeyId',
'expectedActiveGeneration',
'expectedActiveMaterialDigest',
'retentionPolicy',
'preparedAtMs',
'audit',
]);
const normalizedMutationId = mutationId(value.mutationId, 'mutationId');
const normalizedRequestId = requestId(value.requestId);
const normalizedPepperKeyId = value.pepperKeyId;
const normalizedActivePepperKeyId = value.expectedActivePepperKeyId;
try {
assertApiCredentialPepperKeyId(normalizedPepperKeyId);
assertApiCredentialPepperKeyId(normalizedActivePepperKeyId);
} catch {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'pepper key identity is invalid',
);
}
if (normalizedPepperKeyId === normalizedActivePepperKeyId) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'retired and active pepper keys must differ',
);
}
const preparedAtMs = timestamp(value.preparedAtMs, 'preparedAtMs');
return Object.freeze({
mutationId: normalizedMutationId,
requestId: normalizedRequestId,
pepperKeyId: normalizedPepperKeyId,
expectedMaterialDigest: digest(
value.expectedMaterialDigest,
'expectedMaterialDigest',
),
expectedBackupMaterialDigest: digest(
value.expectedBackupMaterialDigest,
'expectedBackupMaterialDigest',
),
expectedActivePepperKeyId: normalizedActivePepperKeyId,
expectedActiveGeneration: positiveInteger(
value.expectedActiveGeneration,
'expectedActiveGeneration',
),
expectedActiveMaterialDigest: digest(
value.expectedActiveMaterialDigest,
'expectedActiveMaterialDigest',
),
retentionPolicy: retention(value.retentionPolicy),
preparedAtMs,
audit: audit(
value.audit,
normalizedMutationId,
normalizedRequestId,
'prepare',
preparedAtMs,
),
});
}
export function normalizeCompleteLocalOwnerPepperMaterialGcCommand(
value: CompleteLocalOwnerPepperMaterialGcCommand,
): Readonly<CompleteLocalOwnerPepperMaterialGcCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'complete command is invalid',
);
}
exactKeys(value, [
'prepareMutationId',
'mutationId',
'requestId',
'destructionProofDigest',
'completedAtMs',
'audit',
]);
const prepareMutationId = mutationId(
value.prepareMutationId,
'prepareMutationId',
);
const normalizedMutationId = mutationId(value.mutationId, 'mutationId');
if (prepareMutationId === normalizedMutationId) {
throw new InvalidLocalOwnerPepperMaterialGcValueError(
'completion mutation must be distinct',
);
}
const normalizedRequestId = requestId(value.requestId);
const completedAtMs = timestamp(value.completedAtMs, 'completedAtMs');
return Object.freeze({
prepareMutationId,
mutationId: normalizedMutationId,
requestId: normalizedRequestId,
destructionProofDigest: digest(
value.destructionProofDigest,
'destructionProofDigest',
),
completedAtMs,
audit: audit(
value.audit,
normalizedMutationId,
normalizedRequestId,
'complete',
completedAtMs,
),
});
}
@@ -0,0 +1,104 @@
import type { RunAttemptStatus } from '../run/run';
export const LOCAL_COMPLETION_RECEIPT_JOURNAL_STATES = [
'pending',
'quarantined',
] as const;
export const MAX_LOCAL_COMPLETION_RECEIPT_JOURNAL_PAGE = 64;
export type LocalCompletionReceiptJournalState =
(typeof LOCAL_COMPLETION_RECEIPT_JOURNAL_STATES)[number];
export interface LocalCompletionReceiptJournalRecord {
readonly attemptId: string;
readonly runId: string;
readonly state: LocalCompletionReceiptJournalState;
readonly registeredAtMs: number;
readonly updatedAtMs: number;
readonly quarantineRef?: string;
readonly purgeAfterMs?: number;
}
export interface LocalCompletionReceiptJournalCandidate
extends LocalCompletionReceiptJournalRecord {
readonly attemptStatus: RunAttemptStatus;
readonly executorType: string;
readonly finishedAtMs?: number;
}
export interface LocalCompletionReceiptJournalCursor {
readonly updatedAtMs: number;
readonly attemptId: string;
}
export interface LocalCompletionReceiptJournalPage {
readonly candidates: readonly LocalCompletionReceiptJournalCandidate[];
readonly truncated: boolean;
readonly nextCursor?: LocalCompletionReceiptJournalCursor;
}
export interface RegisterLocalCompletionReceiptCommand {
readonly attemptId: string;
readonly runId: string;
readonly registeredAtMs: number;
}
export interface QuarantineLocalCompletionReceiptCommand {
readonly attemptId: string;
readonly quarantineRef: string;
readonly purgeAfterMs: number;
readonly updatedAtMs: number;
}
export interface LocalCompletionReceiptJournal {
register(command: RegisterLocalCompletionReceiptCommand): Promise<void>;
markQuarantined(
command: QuarantineLocalCompletionReceiptCommand,
): Promise<void>;
resolve(attemptId: string): Promise<boolean>;
listCandidates(options: {
readonly observedAtMs: number;
readonly cursor?: LocalCompletionReceiptJournalCursor;
readonly limit?: number;
}): Promise<LocalCompletionReceiptJournalPage>;
}
const PORTABLE_LOCAL_EXECUTION_ID =
/^[A-Za-z0-9][A-Za-z0-9._:-]{0,35}$/;
export function assertLocalCompletionReceiptId(
value: string,
field: 'runId' | 'attemptId',
): void {
if (!PORTABLE_LOCAL_EXECUTION_ID.test(value)) {
throw new TypeError(`${field} must be a bounded portable execution ID`);
}
}
export function assertLocalCompletionReceiptTimestamp(
value: number,
field: string,
): void {
if (!Number.isSafeInteger(value) || value < 0) {
throw new RangeError(`${field} must be a non-negative safe integer`);
}
}
export function assertLocalCompletionReceiptJournalCursor(
cursor: LocalCompletionReceiptJournalCursor,
): void {
assertLocalCompletionReceiptTimestamp(cursor.updatedAtMs, 'updatedAtMs');
assertLocalCompletionReceiptId(cursor.attemptId, 'attemptId');
}
export function assertLocalCompletionReceiptJournalLimit(limit: number): void {
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > MAX_LOCAL_COMPLETION_RECEIPT_JOURNAL_PAGE
) {
throw new RangeError(
`limit must be between 1 and ${MAX_LOCAL_COMPLETION_RECEIPT_JOURNAL_PAGE}`,
);
}
}
@@ -0,0 +1,453 @@
import { createHash } from 'node:crypto';
export type { LocalSecretEnvironmentProvider } from '../secret/localSecret';
export const LOCAL_PROCESS_EXECUTOR_TYPE = 'local_process';
export const MAX_LOCAL_DISPATCH_PAGE_SIZE = 64;
export const MAX_LOCAL_DISPATCH_ENVIRONMENT_ENTRIES = 256;
export const MAX_LOCAL_DISPATCH_ENVIRONMENT_BYTES = 64 * 1024;
export const MAX_LOCAL_DISPATCH_SECRET_REFS = 64;
export const MAX_LOCAL_DISPATCH_TIMEOUT_MS = 365 * 24 * 60 * 60_000;
const CONTEXT_REF_PATTERN = /^localctx:sha256:[a-f0-9]{64}$/;
const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
export type LocalDispatchCommand =
| Readonly<{
kind: 'argv';
file: string;
args: readonly string[];
}>
| Readonly<{
kind: 'shell';
command: string;
shell?: '/bin/sh' | '/bin/bash';
}>;
export interface LocalDispatchCandidateCursor {
readonly priority: number;
readonly queuedAtMs: number;
readonly attemptCreatedAtMs: number;
readonly attemptId: string;
}
export interface LocalDispatchCandidate extends LocalDispatchCandidateCursor {
readonly runId: string;
readonly stepRunId?: string;
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly attemptNumber: number;
readonly executorType: typeof LOCAL_PROCESS_EXECUTOR_TYPE;
}
export interface LocalDispatchCandidatePage {
readonly candidates: readonly LocalDispatchCandidate[];
readonly truncated: boolean;
}
export interface LocalTaskExecutionRevisionContent {
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly executorType: typeof LOCAL_PROCESS_EXECUTOR_TYPE;
readonly command: LocalDispatchCommand;
readonly workingDirectory?: string;
readonly timeoutMs?: number;
readonly contextRef: string;
readonly createdAtMs: number;
}
export interface LocalTaskExecutionRevision
extends LocalTaskExecutionRevisionContent {
readonly contentDigest: string;
}
export type LocalExecutionEnvironmentBinding =
| Readonly<{ name: string; kind: 'public'; value: string }>
| Readonly<{ name: string; kind: 'secret'; secretRef: string }>;
export interface LocalExecutionContextRecipe {
readonly contextRef: string;
readonly environment: readonly LocalExecutionEnvironmentBinding[];
readonly contentDigest: string;
readonly createdAtMs: number;
}
export interface LocalDispatchCandidateSource {
listLocalDispatchCandidates(options: {
readonly limit: number;
readonly after?: LocalDispatchCandidateCursor;
}): Promise<LocalDispatchCandidatePage>;
}
export interface LocalTaskExecutionRevisionSource {
resolveLocalTaskExecutionRevision(identity: {
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
}): Promise<LocalTaskExecutionRevision | null>;
}
export interface LocalExecutionContextRecipeSource {
resolveLocalExecutionContextRecipe(
contextRef: string,
): Promise<LocalExecutionContextRecipe | null>;
}
export interface LocalDispatchDefinitionWriter {
appendLocalExecutionContextRecipe(
recipe: LocalExecutionContextRecipe,
): Promise<'inserted' | 'existing'>;
appendLocalTaskExecutionRevision(
revision: LocalTaskExecutionRevision,
): Promise<'inserted' | 'existing'>;
}
export interface LocalDispatchStore
extends LocalDispatchCandidateSource,
LocalTaskExecutionRevisionSource,
LocalExecutionContextRecipeSource,
LocalDispatchDefinitionWriter {}
function assertBoundedText(
value: unknown,
field: string,
maximumBytes: number,
): asserts value is string {
if (
typeof value !== 'string' ||
value.length === 0 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new TypeError(`${field} is invalid`);
}
}
function assertIdentifier(
value: unknown,
field: string,
): asserts value is string {
assertBoundedText(value, field, 255);
if (/\r|\n|[\u0001-\u001f\u007f]/.test(value)) {
throw new TypeError(`${field} is invalid`);
}
}
function assertTimestamp(
value: unknown,
field: string,
): asserts value is number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new TypeError(`${field} is invalid`);
}
}
export function assertLocalDispatchContextRef(
value: unknown,
): asserts value is string {
if (typeof value !== 'string' || !CONTEXT_REF_PATTERN.test(value)) {
throw new TypeError('Local dispatch contextRef is invalid');
}
}
export function normalizeLocalDispatchCommand(
command: LocalDispatchCommand,
): LocalDispatchCommand {
if (!command || typeof command !== 'object' || Array.isArray(command)) {
throw new TypeError('Local dispatch command is invalid');
}
if (command.kind === 'argv') {
assertBoundedText(command.file, 'Local dispatch executable', 4096);
if (!command.file.startsWith('/')) {
throw new TypeError('Local dispatch executable must be absolute');
}
if (!Array.isArray(command.args) || command.args.length > 256) {
throw new TypeError('Local dispatch arguments are invalid');
}
let bytes = Buffer.byteLength(command.file, 'utf8');
const args = command.args.map((argument) => {
if (
typeof argument !== 'string' ||
argument.includes('\0') ||
Buffer.byteLength(argument, 'utf8') > 16 * 1024
) {
throw new TypeError('Local dispatch argument is invalid');
}
bytes += Buffer.byteLength(argument, 'utf8');
return argument;
});
if (bytes > 64 * 1024) {
throw new RangeError('Local dispatch command exceeds its byte budget');
}
return Object.freeze({
kind: 'argv' as const,
file: command.file,
args: Object.freeze(args),
});
}
if (command.kind === 'shell') {
assertBoundedText(
command.command,
'Local dispatch shell command',
64 * 1024,
);
if (
command.shell !== undefined &&
command.shell !== '/bin/sh' &&
command.shell !== '/bin/bash'
) {
throw new TypeError('Local dispatch shell is not allowlisted');
}
return Object.freeze({
kind: 'shell' as const,
command: command.command,
...(command.shell === undefined ? {} : { shell: command.shell }),
});
}
throw new TypeError('Local dispatch command kind is invalid');
}
export function normalizeLocalDispatchCandidate(
candidate: LocalDispatchCandidate,
): LocalDispatchCandidate {
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
throw new TypeError('Local dispatch candidate is invalid');
}
assertIdentifier(candidate.runId, 'Local dispatch runId');
assertIdentifier(candidate.attemptId, 'Local dispatch attemptId');
if (candidate.stepRunId !== undefined) {
assertIdentifier(candidate.stepRunId, 'Local dispatch stepRunId');
}
assertIdentifier(candidate.projectId, 'Local dispatch projectId');
assertIdentifier(candidate.taskId, 'Local dispatch taskId');
assertIdentifier(candidate.taskRevision, 'Local dispatch taskRevision');
if (!Number.isSafeInteger(candidate.priority)) {
throw new TypeError('Local dispatch priority is invalid');
}
assertTimestamp(candidate.queuedAtMs, 'Local dispatch queuedAtMs');
assertTimestamp(
candidate.attemptCreatedAtMs,
'Local dispatch attemptCreatedAtMs',
);
if (
!Number.isSafeInteger(candidate.attemptNumber) ||
candidate.attemptNumber < 1
) {
throw new TypeError('Local dispatch attempt number is invalid');
}
if (candidate.executorType !== LOCAL_PROCESS_EXECUTOR_TYPE) {
throw new TypeError('Local dispatch executor type is invalid');
}
return Object.freeze({ ...candidate });
}
export function assertLocalDispatchPageSize(limit: number): void {
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > MAX_LOCAL_DISPATCH_PAGE_SIZE
) {
throw new RangeError(
`Local dispatch page size must be between 1 and ${MAX_LOCAL_DISPATCH_PAGE_SIZE}`,
);
}
}
function normalizeLocalTaskExecutionRevisionContent(
revision: LocalTaskExecutionRevisionContent,
): LocalTaskExecutionRevisionContent {
if (!revision || typeof revision !== 'object' || Array.isArray(revision)) {
throw new TypeError('Local Task execution revision is invalid');
}
assertIdentifier(revision.projectId, 'Local Task revision projectId');
assertIdentifier(revision.taskId, 'Local Task revision taskId');
assertIdentifier(revision.taskRevision, 'Local Task revision identity');
if (revision.executorType !== LOCAL_PROCESS_EXECUTOR_TYPE) {
throw new TypeError('Local Task revision executor type is invalid');
}
const command = normalizeLocalDispatchCommand(revision.command);
if (revision.workingDirectory !== undefined) {
assertBoundedText(
revision.workingDirectory,
'Local Task working directory',
4096,
);
if (!revision.workingDirectory.startsWith('/')) {
throw new TypeError('Local Task working directory must be absolute');
}
}
if (
revision.timeoutMs !== undefined &&
(!Number.isSafeInteger(revision.timeoutMs) ||
revision.timeoutMs < 1 ||
revision.timeoutMs > MAX_LOCAL_DISPATCH_TIMEOUT_MS)
) {
throw new RangeError('Local Task timeout is invalid');
}
assertLocalDispatchContextRef(revision.contextRef);
assertTimestamp(revision.createdAtMs, 'Local Task revision createdAtMs');
return Object.freeze({
projectId: revision.projectId,
taskId: revision.taskId,
taskRevision: revision.taskRevision,
executorType: LOCAL_PROCESS_EXECUTOR_TYPE,
command,
...(revision.workingDirectory === undefined
? {}
: { workingDirectory: revision.workingDirectory }),
...(revision.timeoutMs === undefined
? {}
: { timeoutMs: revision.timeoutMs }),
contextRef: revision.contextRef,
createdAtMs: revision.createdAtMs,
});
}
function localTaskExecutionRevisionDigestFromCanonical(
revision: LocalTaskExecutionRevisionContent,
): string {
const { createdAtMs: _createdAtMs, ...immutableContent } = revision;
return createHash('sha256')
.update('qinglong.local-task-execution-revision.v1\0', 'utf8')
.update(JSON.stringify(immutableContent), 'utf8')
.digest('hex');
}
export function localTaskExecutionRevisionDigest(
revision: LocalTaskExecutionRevisionContent,
): string {
return localTaskExecutionRevisionDigestFromCanonical(
normalizeLocalTaskExecutionRevisionContent(revision),
);
}
export function createLocalTaskExecutionRevision(
revision: LocalTaskExecutionRevisionContent,
): LocalTaskExecutionRevision {
const content = normalizeLocalTaskExecutionRevisionContent(revision);
return Object.freeze({
...content,
contentDigest: localTaskExecutionRevisionDigestFromCanonical(content),
});
}
export function normalizeLocalTaskExecutionRevision(
revision: LocalTaskExecutionRevision,
): LocalTaskExecutionRevision {
const content = normalizeLocalTaskExecutionRevisionContent(revision);
const contentDigest = localTaskExecutionRevisionDigestFromCanonical(content);
if (
typeof revision.contentDigest !== 'string' ||
!/^[a-f0-9]{64}$/.test(revision.contentDigest) ||
revision.contentDigest !== contentDigest
) {
throw new TypeError(
'Local Task execution revision digest does not match its content',
);
}
return Object.freeze({ ...content, contentDigest });
}
function canonicalBindings(
bindings: readonly LocalExecutionEnvironmentBinding[],
): readonly LocalExecutionEnvironmentBinding[] {
if (
!Array.isArray(bindings) ||
bindings.length > MAX_LOCAL_DISPATCH_ENVIRONMENT_ENTRIES
) {
throw new TypeError('Local context environment bindings are invalid');
}
const names = new Set<string>();
let bytes = 0;
const normalized = bindings.map((binding) => {
if (!binding || typeof binding !== 'object' || Array.isArray(binding)) {
throw new TypeError('Local context environment binding is invalid');
}
if (
!ENVIRONMENT_NAME_PATTERN.test(binding.name) ||
binding.name.startsWith('QL3_') ||
names.has(binding.name)
) {
throw new TypeError(
'Local context environment name is invalid or duplicated',
);
}
names.add(binding.name);
bytes += Buffer.byteLength(binding.name, 'utf8');
if (binding.kind === 'public') {
if (typeof binding.value !== 'string' || binding.value.includes('\0')) {
throw new TypeError('Local context public value is invalid');
}
bytes += Buffer.byteLength(binding.value, 'utf8');
return Object.freeze({
name: binding.name,
kind: 'public' as const,
value: binding.value,
});
}
if (binding.kind === 'secret') {
assertBoundedText(binding.secretRef, 'Local context secretRef', 512);
bytes += Buffer.byteLength(binding.secretRef, 'utf8');
return Object.freeze({
name: binding.name,
kind: 'secret' as const,
secretRef: binding.secretRef,
});
}
throw new TypeError('Local context environment binding kind is invalid');
});
if (bytes > MAX_LOCAL_DISPATCH_ENVIRONMENT_BYTES) {
throw new RangeError('Local context environment exceeds its byte budget');
}
normalized.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze(normalized);
}
function bindingsDigest(
bindings: readonly LocalExecutionEnvironmentBinding[],
): string {
return createHash('sha256')
.update(JSON.stringify(bindings), 'utf8')
.digest('hex');
}
export function createLocalExecutionContextRecipe(input: {
readonly environment: readonly LocalExecutionEnvironmentBinding[];
readonly createdAtMs: number;
}): LocalExecutionContextRecipe {
assertTimestamp(input.createdAtMs, 'Local context recipe createdAtMs');
const environment = canonicalBindings(input.environment);
const contentDigest = bindingsDigest(environment);
return Object.freeze({
contextRef: `localctx:sha256:${contentDigest}`,
environment,
contentDigest,
createdAtMs: input.createdAtMs,
});
}
export function normalizeLocalExecutionContextRecipe(
recipe: LocalExecutionContextRecipe,
): LocalExecutionContextRecipe {
if (!recipe || typeof recipe !== 'object' || Array.isArray(recipe)) {
throw new TypeError('Local execution context recipe is invalid');
}
assertLocalDispatchContextRef(recipe.contextRef);
assertTimestamp(recipe.createdAtMs, 'Local context recipe createdAtMs');
const environment = canonicalBindings(recipe.environment);
const contentDigest = bindingsDigest(environment);
if (
recipe.contentDigest !== contentDigest ||
recipe.contextRef !== `localctx:sha256:${contentDigest}` ||
JSON.stringify(recipe.environment) !== JSON.stringify(environment)
) {
throw new TypeError('Local execution context recipe is not canonical');
}
return Object.freeze({
contextRef: recipe.contextRef,
environment,
contentDigest,
createdAtMs: recipe.createdAtMs,
});
}
@@ -0,0 +1,225 @@
import type { RunCancellationReason } from '../run/run';
export const MAX_LOCAL_EXECUTION_CONTROL_PAGE = 64;
export const LOCAL_EXECUTION_CONTROL_KINDS = [
'cancellation',
'deadline',
] as const;
export type LocalExecutionControlKind =
(typeof LOCAL_EXECUTION_CONTROL_KINDS)[number];
export interface LocalExecutionControlCandidate {
readonly kind: LocalExecutionControlKind;
readonly runId: string;
readonly attemptId: string;
readonly dueAtMs: number;
readonly cancelReason?: RunCancellationReason;
}
export interface LocalExecutionControlCursor {
readonly dueAtMs: number;
readonly kind: LocalExecutionControlKind;
readonly attemptId: string;
}
export interface LocalExecutionControlPage {
readonly candidates: readonly LocalExecutionControlCandidate[];
readonly truncated: boolean;
readonly nextCursor?: LocalExecutionControlCursor;
}
export interface LocalActiveExecutionCandidate {
readonly runId: string;
readonly attemptId: string;
readonly attemptCreatedAtMs: number;
}
export interface LocalActiveExecutionCursor {
readonly attemptCreatedAtMs: number;
readonly attemptId: string;
}
export interface LocalActiveExecutionPage {
readonly candidates: readonly LocalActiveExecutionCandidate[];
readonly truncated: boolean;
readonly nextCursor?: LocalActiveExecutionCursor;
}
export interface LocalExecutionControlSource {
listLocalExecutionControlCandidates(options: {
readonly observedAtMs: number;
readonly limit: number;
readonly after?: LocalExecutionControlCursor;
}): Promise<LocalExecutionControlPage>;
listLocalActiveExecutions(options: {
readonly limit: number;
readonly after?: LocalActiveExecutionCursor;
}): Promise<LocalActiveExecutionPage>;
}
const CONTROL_CANDIDATE_KEYS = Object.freeze([
'attemptId',
'cancelReason',
'dueAtMs',
'kind',
'runId',
]);
const ACTIVE_CANDIDATE_KEYS = Object.freeze([
'attemptCreatedAtMs',
'attemptId',
'runId',
]);
const CANCELLATION_REASONS = new Set<RunCancellationReason>([
'user',
'policy',
'shutdown',
'reconcile',
'timeout',
]);
function exactKeys(value: Record<string, unknown>, expected: readonly string[]) {
return (
JSON.stringify(Object.keys(value).sort()) ===
JSON.stringify([...expected].sort())
);
}
function boundedIdentity(value: unknown, field: string): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
/[\0\r\n]/.test(value)
) {
throw new TypeError(`${field} is invalid`);
}
return value;
}
function safeTimestamp(value: unknown, field: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new RangeError(`${field} must be a non-negative safe integer`);
}
return value as number;
}
function controlKind(value: unknown): LocalExecutionControlKind {
if (value !== 'cancellation' && value !== 'deadline') {
throw new TypeError('Local execution control kind is invalid');
}
return value;
}
export function assertLocalExecutionControlLimit(limit: number): void {
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > MAX_LOCAL_EXECUTION_CONTROL_PAGE
) {
throw new RangeError(
`limit must be between 1 and ${MAX_LOCAL_EXECUTION_CONTROL_PAGE}`,
);
}
}
export function normalizeLocalExecutionControlCandidate(
value: LocalExecutionControlCandidate,
): Readonly<LocalExecutionControlCandidate> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Local execution control candidate is invalid');
}
const record = value as unknown as Record<string, unknown>;
const kind = controlKind(record.kind);
const expectedKeys =
kind === 'cancellation'
? CONTROL_CANDIDATE_KEYS
: CONTROL_CANDIDATE_KEYS.filter((key) => key !== 'cancelReason');
if (!exactKeys(record, expectedKeys)) {
throw new TypeError('Local execution control candidate shape is invalid');
}
const cancelReason = record.cancelReason;
if (
kind === 'cancellation' &&
!CANCELLATION_REASONS.has(cancelReason as RunCancellationReason)
) {
throw new TypeError('Local execution cancellation reason is invalid');
}
return Object.freeze({
kind,
runId: boundedIdentity(record.runId, 'runId'),
attemptId: boundedIdentity(record.attemptId, 'attemptId'),
dueAtMs: safeTimestamp(record.dueAtMs, 'dueAtMs'),
...(kind === 'cancellation'
? { cancelReason: cancelReason as RunCancellationReason }
: {}),
});
}
export function normalizeLocalExecutionControlCursor(
value: LocalExecutionControlCursor,
): Readonly<LocalExecutionControlCursor> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value as unknown as Record<string, unknown>, [
'attemptId',
'dueAtMs',
'kind',
])
) {
throw new TypeError('Local execution control cursor is invalid');
}
return Object.freeze({
dueAtMs: safeTimestamp(value.dueAtMs, 'dueAtMs'),
kind: controlKind(value.kind),
attemptId: boundedIdentity(value.attemptId, 'attemptId'),
});
}
export function normalizeLocalActiveExecutionCandidate(
value: LocalActiveExecutionCandidate,
): Readonly<LocalActiveExecutionCandidate> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value as unknown as Record<string, unknown>, ACTIVE_CANDIDATE_KEYS)
) {
throw new TypeError('Local active execution candidate is invalid');
}
return Object.freeze({
runId: boundedIdentity(value.runId, 'runId'),
attemptId: boundedIdentity(value.attemptId, 'attemptId'),
attemptCreatedAtMs: safeTimestamp(
value.attemptCreatedAtMs,
'attemptCreatedAtMs',
),
});
}
export function normalizeLocalActiveExecutionCursor(
value: LocalActiveExecutionCursor,
): Readonly<LocalActiveExecutionCursor> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value as unknown as Record<string, unknown>, [
'attemptCreatedAtMs',
'attemptId',
])
) {
throw new TypeError('Local active execution cursor is invalid');
}
return Object.freeze({
attemptCreatedAtMs: safeTimestamp(
value.attemptCreatedAtMs,
'attemptCreatedAtMs',
),
attemptId: boundedIdentity(value.attemptId, 'attemptId'),
});
}
@@ -0,0 +1,21 @@
/** Bounds one startup recovery observation independently of the local Profile. */
export const MAX_LOCAL_RUN_STARTUP_RECOVERY_CANDIDATES = 256;
export type LocalRunStartupRecoveryStatus = 'dispatching' | 'running';
export interface LocalRunStartupRecoveryCandidate {
readonly runId: string;
readonly runStatus: LocalRunStartupRecoveryStatus;
readonly activeAttemptCount: number;
}
export interface LocalRunStartupRecoveryPage {
readonly candidates: readonly LocalRunStartupRecoveryCandidate[];
readonly truncated: boolean;
}
export interface LocalRunStartupRecoverySource {
inspectCandidates(options?: {
readonly limit?: number;
}): Promise<LocalRunStartupRecoveryPage>;
}
@@ -0,0 +1,384 @@
export const MIGRATION_STREAM_DIALECTS = ['sqlite', 'postgresql'] as const;
export type MigrationStreamDialect = (typeof MIGRATION_STREAM_DIALECTS)[number];
export const MIGRATION_ID_SCHEMES = [
'sqlite-numbered',
'postgres-prefixed',
] as const;
export type MigrationIdScheme = (typeof MIGRATION_ID_SCHEMES)[number];
export const MIGRATION_CHECKSUM_SCHEMES = ['sha256', 'legacy-opaque'] as const;
export type MigrationChecksumScheme =
(typeof MIGRATION_CHECKSUM_SCHEMES)[number];
export interface MigrationStreamRecord {
streamId: string;
dialect: MigrationStreamDialect;
migrationId: string;
checksum: string;
appliedAtMs: number;
}
export interface MigrationStreamManifestStep {
id: string;
checksum: string;
}
export interface MigrationStreamStep<TContext>
extends MigrationStreamManifestStep {
up(context: TContext): Promise<void>;
}
export interface MigrationStreamTransaction<TContext> {
readonly context: TContext;
findById(migrationId: string): Promise<MigrationStreamRecord | null>;
insert(record: MigrationStreamRecord): Promise<void>;
}
export interface MigrationStreamStore<TContext> {
ensureHistory(): Promise<void>;
listAll(): Promise<readonly MigrationStreamRecord[]>;
findById(migrationId: string): Promise<MigrationStreamRecord | null>;
transaction<T>(
work: (transaction: MigrationStreamTransaction<TContext>) => Promise<T>,
): Promise<T>;
}
export interface MigrationStreamManifest {
id: string;
dialect: MigrationStreamDialect;
migrationIdScheme: MigrationIdScheme;
checksumScheme: MigrationChecksumScheme;
migrations: readonly MigrationStreamManifestStep[];
}
export interface MigrationStreamDefinition<TContext>
extends MigrationStreamManifest {
migrations: readonly MigrationStreamStep<TContext>[];
}
export interface RunMigrationStreamOptions<TContext> {
stream: MigrationStreamDefinition<TContext>;
store: MigrationStreamStore<TContext>;
clock?: () => number;
logger?: { info(message: string): unknown };
}
const STREAM_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
const SQLITE_MIGRATION_ID_PATTERN = /^\d{4}-[a-z0-9][a-z0-9-]{0,122}$/;
const POSTGRES_MIGRATION_ID_PATTERN = /^pg-\d{4}-[a-z0-9][a-z0-9-]{0,119}$/;
const CHECKSUM_PATTERN = /^[0-9a-f]{64}$/;
const MAX_LEGACY_CHECKSUM_LENGTH = 255;
export class InvalidMigrationStreamError extends TypeError {
constructor(message: string) {
super(`Migration stream is invalid: ${message}`);
this.name = 'InvalidMigrationStreamError';
}
}
export class MigrationStreamChecksumMismatchError extends Error {
constructor(
readonly migrationId: string,
readonly databaseChecksum: string,
readonly codeChecksum: string,
) {
super(
`Migration checksum mismatch: ${migrationId} ` +
`(database=${databaseChecksum}, code=${codeChecksum})`,
);
this.name = 'MigrationStreamChecksumMismatchError';
}
}
export class MigrationStreamHistoryCorruptionError extends Error {
constructor(readonly migrationId: string) {
super(`Migration history is corrupt: ${migrationId}`);
this.name = 'MigrationStreamHistoryCorruptionError';
}
}
export class MigrationStreamAheadOfCodeError extends Error {
constructor(readonly migrationId: string) {
super(`Migration history is ahead of this code: ${migrationId}`);
this.name = 'MigrationStreamAheadOfCodeError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const keys = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
keys.length === canonical.length &&
keys.every((key, index) => key === canonical[index])
);
}
function checksumIsValid(
scheme: MigrationChecksumScheme,
value: unknown,
): value is string {
if (typeof value !== 'string') return false;
return scheme === 'sha256'
? CHECKSUM_PATTERN.test(value)
: value.length <= MAX_LEGACY_CHECKSUM_LENGTH;
}
function validateStream(
stream: MigrationStreamManifest,
executable: boolean,
): void {
if (!stream || typeof stream !== 'object' || Array.isArray(stream)) {
throw new InvalidMigrationStreamError('definition must be an object');
}
if (
!exactKeys(stream, [
'id',
'dialect',
'migrationIdScheme',
'checksumScheme',
'migrations',
])
) {
throw new InvalidMigrationStreamError('definition shape is invalid');
}
if (!STREAM_ID_PATTERN.test(stream.id)) {
throw new InvalidMigrationStreamError('id is invalid');
}
if (!MIGRATION_STREAM_DIALECTS.includes(stream.dialect)) {
throw new InvalidMigrationStreamError('dialect is invalid');
}
if (!MIGRATION_ID_SCHEMES.includes(stream.migrationIdScheme)) {
throw new InvalidMigrationStreamError('migrationIdScheme is invalid');
}
if (!MIGRATION_CHECKSUM_SCHEMES.includes(stream.checksumScheme)) {
throw new InvalidMigrationStreamError('checksumScheme is invalid');
}
if (
(stream.dialect === 'sqlite' &&
stream.migrationIdScheme !== 'sqlite-numbered') ||
(stream.dialect === 'postgresql' &&
stream.migrationIdScheme !== 'postgres-prefixed')
) {
throw new InvalidMigrationStreamError(
'migrationIdScheme does not match dialect',
);
}
if (!Array.isArray(stream.migrations)) {
throw new InvalidMigrationStreamError('migrations must be an array');
}
const ids = new Set<string>();
for (const migration of stream.migrations) {
const idPattern =
stream.migrationIdScheme === 'sqlite-numbered'
? SQLITE_MIGRATION_ID_PATTERN
: POSTGRES_MIGRATION_ID_PATTERN;
const objectShape =
migration !== null &&
typeof migration === 'object' &&
!Array.isArray(migration);
const manifestShape =
objectShape && exactKeys(migration, ['id', 'checksum']);
const definitionShape =
objectShape &&
exactKeys(migration, ['id', 'checksum', 'up']) &&
typeof (migration as Partial<MigrationStreamStep<unknown>>).up ===
'function';
if (
!objectShape ||
!(manifestShape || definitionShape) ||
(executable && !definitionShape) ||
!idPattern.test(migration.id) ||
!checksumIsValid(stream.checksumScheme, migration.checksum)
) {
throw new InvalidMigrationStreamError('migration is invalid');
}
if (ids.has(migration.id)) {
throw new InvalidMigrationStreamError(
`duplicate migration id: ${migration.id}`,
);
}
ids.add(migration.id);
}
}
function validateDefinition<TContext>(
stream: MigrationStreamDefinition<TContext>,
): void {
validateStream(stream, true);
}
function validateRecord(
value: MigrationStreamRecord,
stream: MigrationStreamManifest,
migrationId: string,
): void {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'streamId',
'dialect',
'migrationId',
'checksum',
'appliedAtMs',
]) ||
value.streamId !== stream.id ||
value.dialect !== stream.dialect ||
value.migrationId !== migrationId ||
!checksumIsValid(stream.checksumScheme, value.checksum) ||
!Number.isSafeInteger(value.appliedAtMs) ||
value.appliedAtMs < 0
) {
throw new MigrationStreamHistoryCorruptionError(migrationId);
}
}
function assertChecksum(
record: MigrationStreamRecord,
migration: MigrationStreamManifestStep,
): void {
if (record.checksum !== migration.checksum) {
throw new MigrationStreamChecksumMismatchError(
migration.id,
record.checksum,
migration.checksum,
);
}
}
export function auditMigrationStreamHistory(
history: readonly MigrationStreamRecord[],
stream: MigrationStreamManifest,
): ReadonlySet<string> {
validateStream(stream, false);
if (!Array.isArray(history)) {
throw new MigrationStreamHistoryCorruptionError('history');
}
const migrationsById = new Map(
stream.migrations.map((migration, index) => [
migration.id,
{ migration, index },
]),
);
const appliedIds = new Set<string>();
const appliedIndexes = new Set<number>();
for (const record of history) {
const expected = migrationsById.get(record?.migrationId);
if (!expected) {
throw new MigrationStreamAheadOfCodeError(
record?.migrationId ?? 'unknown',
);
}
if (appliedIds.has(record.migrationId)) {
throw new MigrationStreamHistoryCorruptionError(record.migrationId);
}
validateRecord(record, stream, expected.migration.id);
assertChecksum(record, expected.migration);
appliedIds.add(record.migrationId);
appliedIndexes.add(expected.index);
}
for (let index = 0; index < appliedIndexes.size; index += 1) {
if (!appliedIndexes.has(index)) {
const missingMigration = stream.migrations[index];
throw new MigrationStreamHistoryCorruptionError(
missingMigration?.id ?? 'history',
);
}
}
return appliedIds;
}
/**
* Dialect-neutral migration ordering and history semantics. Concrete stores own
* SQL, leader election and transaction APIs; this core never imports a driver.
*/
export async function runMigrationStream<TContext>(
options: RunMigrationStreamOptions<TContext>,
): Promise<void> {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new InvalidMigrationStreamError('options must be an object');
}
const expectedKeys = [
'stream',
'store',
...(options.clock === undefined ? [] : ['clock']),
...(options.logger === undefined ? [] : ['logger']),
];
if (!exactKeys(options, expectedKeys)) {
throw new InvalidMigrationStreamError('options shape is invalid');
}
validateDefinition(options.stream);
if (
!options.store ||
typeof options.store !== 'object' ||
typeof options.store.ensureHistory !== 'function' ||
typeof options.store.listAll !== 'function' ||
typeof options.store.findById !== 'function' ||
typeof options.store.transaction !== 'function'
) {
throw new InvalidMigrationStreamError('store is invalid');
}
const clock = options.clock ?? Date.now;
if (typeof clock !== 'function') {
throw new InvalidMigrationStreamError('clock is invalid');
}
await options.store.ensureHistory();
const appliedAtStart = auditMigrationStreamHistory(
await options.store.listAll(),
options.stream,
);
for (const migration of options.stream.migrations) {
if (appliedAtStart.has(migration.id)) continue;
const applied = await options.store.findById(migration.id);
if (applied) {
validateRecord(
applied,
options.stream as MigrationStreamDefinition<unknown>,
migration.id,
);
assertChecksum(applied, migration as MigrationStreamStep<unknown>);
continue;
}
let appliedNow = false;
await options.store.transaction(async (transaction) => {
const appliedInsideTransaction = await transaction.findById(migration.id);
if (appliedInsideTransaction) {
validateRecord(
appliedInsideTransaction,
options.stream as MigrationStreamDefinition<unknown>,
migration.id,
);
assertChecksum(
appliedInsideTransaction,
migration as MigrationStreamStep<unknown>,
);
return;
}
await migration.up(transaction.context);
const appliedAtMs = clock();
if (!Number.isSafeInteger(appliedAtMs) || appliedAtMs < 0) {
throw new InvalidMigrationStreamError(
'clock must return a non-negative safe integer',
);
}
await transaction.insert({
streamId: options.stream.id,
dialect: options.stream.dialect,
migrationId: migration.id,
checksum: migration.checksum,
appliedAtMs,
});
appliedNow = true;
});
if (appliedNow) {
options.logger?.info(
`[migration:${options.stream.id}] Applied ${migration.id}`,
);
}
}
}
@@ -0,0 +1,28 @@
export interface PostgresQueryResult<
TRow extends Record<string, unknown> = Record<string, unknown>,
> {
readonly rows: readonly TRow[];
readonly rowCount?: number | null;
}
export interface PostgresQueryable {
query<TRow extends Record<string, unknown> = Record<string, unknown>>(
text: string,
values?: readonly unknown[],
): Promise<PostgresQueryResult<TRow>>;
}
export interface PostgresClient extends PostgresQueryable {
release(): void;
}
export interface PostgresPool extends PostgresQueryable {
connect(): Promise<PostgresClient>;
}
export interface PostgresDatabaseResource {
readonly pool: PostgresPool;
close(): Promise<void>;
}
export type OpenPostgresDatabase = () => Promise<PostgresDatabaseResource>;
@@ -0,0 +1,202 @@
import { createHash } from 'node:crypto';
import type {
PluginPackagePlanOperation,
PluginPackageRisk,
} from '../../pluginPackage';
import {
InvalidPluginPackageLockError,
InvalidPluginPackageInstallError,
} from './contracts';
export const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
export const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
export const OCI_LOCATOR_PATTERN =
/^oci:\/\/([^/?#]+)\/([a-z0-9]+(?:[._-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)*)@sha256:([0-9a-f]{64})$/;
export const OCI_REGISTRY_PATTERN =
/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*)(?::([1-9][0-9]{0,4}))?$/;
export const OFFLINE_LOCATOR_PATTERN = /^offline:sha256:([0-9a-f]{64})$/;
export const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export const PLAN_RISKS: readonly PluginPackageRisk[] = ['low', 'medium', 'high'];
export const PLAN_OPERATIONS: readonly PluginPackagePlanOperation[] = [
'install',
'reinstall',
'upgrade',
'rollback',
];
export const PLAN_FINDING_CODES = new Set([
'architecture_unsupported',
'deployment_profile_unsupported',
'disk_insufficient',
'memory_below_recommendation',
'qinglong_version_unsupported',
'runtime_missing',
'runtime_version_unsupported',
]);
export function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): void {
const actual = Object.keys(value).sort();
const allowed = new Set([...required, ...optional]);
if (
required.some((key) => !actual.includes(key)) ||
actual.some((key) => !allowed.has(key))
) {
throw new ErrorType(`${label} shape is invalid`);
}
}
export function lockObject(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageLockError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
export function installObject(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
export function identifier(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function boundedText(
value: unknown,
label: string,
maximumBytes: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
CONTROL_PATTERN.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function digest(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function timestamp(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function positiveInteger(
value: unknown,
label: string,
maximum: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function nonNegativeInteger(
value: unknown,
label: string,
maximum: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) > maximum
) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function canonicalJson(value: unknown): string {
if (value === null || typeof value === 'boolean')
return JSON.stringify(value);
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
throw new InvalidPluginPackageLockError(
'digest input contains an invalid number',
);
}
return JSON.stringify(Object.is(value, -0) ? 0 : value);
}
if (typeof value === 'string') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
}
const record = lockObject(value, 'digest input');
const entries = Object.keys(record)
.sort()
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
return `{${entries.join(',')}}`;
}
export function contentDigest(value: unknown): string {
return createHash('sha256').update(canonicalJson(value)).digest('hex');
}
@@ -0,0 +1,360 @@
import type {
PluginPackageArchitecture,
PluginPackageDeploymentProfile,
PluginPackageInstallEnvironment,
PluginPackageInstallPlan,
PluginPackageManifest,
PluginPackagePlanOperation,
} from '../../pluginPackage';
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import type { PluginPackageResourceReference } from '../../pluginPackageResourceGeneration';
export const PLUGIN_PACKAGE_LOCK_SCHEMA =
'qinglong/plugin-package-lock@v2' as const;
export const PLUGIN_PACKAGE_INSTALL_SCHEMA =
'qinglong/plugin-package-install@v1' as const;
export const PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA =
'qinglong/plugin-package-install-action@v1' as const;
export const MAX_PLUGIN_PACKAGE_SOURCE_BYTES = 1024 ** 4;
export const MAX_PLUGIN_PACKAGE_INSTALL_VERSION = 2_147_483_647;
export const MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE = 64;
export const PLUGIN_PACKAGE_SOURCE_KINDS = ['oci', 'offline'] as const;
export const PLUGIN_PACKAGE_INSTALL_STATES = [
'queued',
'staged',
'activating',
'active',
'failed',
] as const;
export const PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS = [
'source_unavailable',
'source_mismatch',
'stage_failed',
'activation_failed',
'activation_fact_conflict',
'approval_expired',
'policy_fence_changed',
'resource_exhausted',
] as const;
export const PLUGIN_PACKAGE_INSTALL_RECOVERY_ACTIONS = [
'resume_stage',
'resume_activation',
'inspect_activation',
'none',
] as const;
export type PluginPackageSourceKind =
(typeof PLUGIN_PACKAGE_SOURCE_KINDS)[number];
export type PluginPackageInstallState =
(typeof PLUGIN_PACKAGE_INSTALL_STATES)[number];
export type PluginPackageInstallFailureReason =
(typeof PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS)[number];
export type PluginPackageInstallRecoveryAction =
(typeof PLUGIN_PACKAGE_INSTALL_RECOVERY_ACTIONS)[number];
export interface PluginPackageSourceLock {
readonly kind: PluginPackageSourceKind;
readonly locator: string;
readonly artifactDigest: string;
readonly artifactBytes: number;
readonly contentDigest: string;
}
export interface PluginPackageApprovalLock {
readonly requestId: string;
readonly requestVersion: number;
readonly dispatchId: string;
readonly actionDigest: string;
readonly previewDigest: string;
readonly approvedBy: Readonly<SecuritySubject>;
readonly approvedAtMs: number;
readonly expiresAtMs: number;
readonly fence: Readonly<SecurityPolicyFence>;
}
export interface CreatePluginPackageLockInput {
readonly lockId: string;
readonly projectId: string;
readonly manifest: PluginPackageManifest;
readonly plan: PluginPackageInstallPlan;
readonly environment: PluginPackageInstallEnvironment;
readonly previousManifest?: PluginPackageManifest;
readonly source: PluginPackageSourceLock;
readonly approval: PluginPackageApprovalLock;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly targetGeneration: number;
readonly previousLockDigest?: string;
readonly createdAtMs: number;
}
export type PluginPackageInstallActionInput = Omit<
CreatePluginPackageLockInput,
'approval' | 'createdAtMs'
>;
export interface PluginPackageLock {
readonly schema: typeof PLUGIN_PACKAGE_LOCK_SCHEMA;
readonly lockId: string;
readonly projectId: string;
readonly packageName: string;
readonly packageVersion: string;
readonly operation: PluginPackagePlanOperation;
readonly source: Readonly<PluginPackageSourceLock>;
readonly manifestDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
readonly planDigest: string;
readonly environmentDigest: string;
readonly actionDigest: string;
readonly approval: Readonly<PluginPackageApprovalLock>;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly targetGeneration: number;
readonly previousLockDigest?: string;
readonly createdAtMs: number;
readonly lockDigest: string;
}
export interface PluginPackageStageReceipt {
readonly stageRef: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly evidenceDigest: string;
readonly stagedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageActivationReceipt {
readonly activationRef: string;
readonly intentDigest: string;
readonly generation: number;
readonly contentDigest: string;
readonly activatedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackageActivationReceiptInput = Omit<
PluginPackageActivationReceipt,
'receiptDigest'
>;
export interface PluginPackageInstallFailure {
readonly reason: PluginPackageInstallFailureReason;
readonly failedFrom: Exclude<PluginPackageInstallState, 'active' | 'failed'>;
readonly failedAtMs: number;
}
export interface PluginPackageInstallRecord {
readonly schema: typeof PLUGIN_PACKAGE_INSTALL_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly packageVersion: string;
readonly operation: PluginPackagePlanOperation;
readonly lockDigest: string;
readonly targetGeneration: number;
readonly previousActiveLockDigest: string | null;
readonly activeLockDigest: string | null;
readonly state: PluginPackageInstallState;
readonly version: number;
readonly lastMutationId: string;
readonly lastMutationDigest: string;
readonly stageReceipt: Readonly<PluginPackageStageReceipt> | null;
readonly activationReceipt: Readonly<PluginPackageActivationReceipt> | null;
readonly failure: Readonly<PluginPackageInstallFailure> | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
readonly recordDigest: string;
}
export interface CreatePluginPackageInstallInput {
readonly installationId: string;
readonly mutationId: string;
readonly occurredAtMs: number;
}
export type PluginPackageInstallEvent =
| Readonly<{
type: 'stage_completed';
mutationId: string;
occurredAtMs: number;
stageRef: string;
artifactDigest: string;
manifestDigest: string;
contentDigest: string;
evidenceDigest: string;
}>
| Readonly<{
type: 'activation_started';
mutationId: string;
occurredAtMs: number;
}>
| Readonly<{
type: 'activation_committed';
mutationId: string;
occurredAtMs: number;
activationRef: string;
intentDigest: string;
generation: number;
contentDigest: string;
}>
| Readonly<{
type: 'failed';
mutationId: string;
occurredAtMs: number;
reason: PluginPackageInstallFailureReason;
}>;
export interface PluginPackageInstallCommit {
readonly installationId: string;
readonly expectedVersion: number;
readonly expectedRecordDigest: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly record: Readonly<PluginPackageInstallRecord>;
}
export interface PluginPackageInstallHeadExpectation {
readonly installationId: string;
readonly version: number;
readonly recordDigest: string;
}
export interface PluginPackageInstallCreate {
readonly installationId: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly expectedHead: Readonly<PluginPackageInstallHeadExpectation> | null;
readonly lock: Readonly<PluginPackageLock>;
readonly record: Readonly<PluginPackageInstallRecord>;
}
export interface PluginPackageInstallRecoveryCursor {
readonly packageName: string;
readonly installationId: string;
}
export interface PluginPackageInstallRecoveryPage {
readonly records: readonly Readonly<PluginPackageInstallRecord>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallRecoveryCursor>;
}
export interface PluginPackageInstallInventoryCursor {
readonly packageName: string;
}
export interface PluginPackageInstallInventoryQuarantine {
readonly eventDigest: string;
readonly reasonCode: 'suspected_key_compromise' | 'confirmed_key_compromise';
readonly authorizationMode: 'dual_control' | 'break_glass';
readonly occurredAtMs: number;
readonly capabilityStatus: 'not_active' | 'withdrawn';
readonly receiptDigest: string;
readonly committedAtMs: number;
}
export interface PluginPackageInstallInventoryItem {
readonly record: Readonly<PluginPackageInstallRecord>;
readonly quarantine: Readonly<PluginPackageInstallInventoryQuarantine> | null;
}
export interface PluginPackageInstallInventoryPage {
readonly items: readonly Readonly<PluginPackageInstallInventoryItem>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallInventoryCursor>;
}
/**
* Read-only product query boundary for the current install head of each package.
* It stays separate from the mutation/recovery repository so management
* surfaces cannot accidentally acquire write authority.
*/
export interface PluginPackageInstallInventoryRepository {
findCurrent(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageInstallInventoryItem> | null>;
listCurrentPage(options: {
readonly projectId: string;
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallInventoryCursor>;
}): Promise<Readonly<PluginPackageInstallInventoryPage>>;
}
export interface PluginPackageInstallRepository {
find(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageInstallRecord> | null>;
findLock(lockDigest: string): Promise<Readonly<PluginPackageLock> | null>;
create(command: Readonly<PluginPackageInstallCreate>): Promise<
Readonly<{
status: 'created' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
>;
commit(command: Readonly<PluginPackageInstallCommit>): Promise<
Readonly<{
status: 'committed' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
>;
listRecoveryPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallRecoveryCursor>;
}): Promise<Readonly<PluginPackageInstallRecoveryPage>>;
}
export class InvalidPluginPackageLockError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_LOCK_INVALID';
constructor(message: string) {
super(`Plugin Package lock is invalid: ${message}`);
this.name = 'InvalidPluginPackageLockError';
}
}
export class InvalidPluginPackageInstallError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_INVALID';
constructor(message: string) {
super(`Plugin Package install is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallError';
}
}
export class PluginPackageInstallTransitionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_TRANSITION_CONFLICT';
constructor() {
super('Plugin Package install transition conflicts with durable state');
this.name = 'PluginPackageInstallTransitionConflictError';
}
}
export class PluginPackageInstallMutationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_MUTATION_CONFLICT';
constructor() {
super(
'Plugin Package install mutation conflicts with its previous request',
);
this.name = 'PluginPackageInstallMutationConflictError';
}
}
export class PluginPackageInstallUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package install storage is unavailable', options);
this.name = 'PluginPackageInstallUnavailableError';
}
}
@@ -0,0 +1,930 @@
import { createHash } from 'node:crypto';
import {
PLUGIN_PACKAGE_ARCHITECTURES,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES,
type PluginPackageArchitecture,
type PluginPackageDeploymentProfile,
type PluginPackageInstallEnvironment,
type PluginPackageInstallPlan,
type PluginPackageManifest,
type PluginPackagePlanOperation,
type PluginPackageRisk,
normalizePluginPackageManifest,
normalizePluginPackageInstallEnvironment,
planPluginPackageInstall,
} from '../../pluginPackage';
import {
SECURITY_SUBJECT_TYPES,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../../security/security';
import {
createPluginPackageResourceGenerationFromReferences,
normalizePluginPackageResourceReferences,
pluginPackageResourceReferencesFromContents,
type PluginPackageResourceReference,
} from '../../pluginPackageResourceGeneration';
import { semver } from '../../../versioning/pinnedSemver';
import {
PLUGIN_PACKAGE_LOCK_SCHEMA,
PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA,
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_SOURCE_KINDS,
InvalidPluginPackageLockError,
type PluginPackageSourceKind,
type PluginPackageSourceLock,
type PluginPackageApprovalLock,
type CreatePluginPackageLockInput,
type PluginPackageInstallActionInput,
type PluginPackageLock,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
OCI_LOCATOR_PATTERN,
OCI_REGISTRY_PATTERN,
OFFLINE_LOCATOR_PATTERN,
PLAN_RISKS,
PLAN_OPERATIONS,
PLAN_FINDING_CODES,
exactKeys,
lockObject,
identifier,
boundedText,
digest,
timestamp,
positiveInteger,
nonNegativeInteger,
canonicalJson,
contentDigest,
} from './codec';
export function serializePluginPackageManifest(
value: PluginPackageManifest,
): string {
return canonicalJson(normalizePluginPackageManifest(value));
}
export function pluginPackageManifestDigest(
value: PluginPackageManifest,
): string {
return createHash('sha256')
.update(serializePluginPackageManifest(value), 'utf8')
.digest('hex');
}
export function normalizeSource(value: unknown): Readonly<PluginPackageSourceLock> {
const source = lockObject(value, 'source');
exactKeys(
source,
['kind', 'locator', 'artifactDigest', 'artifactBytes', 'contentDigest'],
[],
'source',
InvalidPluginPackageLockError,
);
if (
!PLUGIN_PACKAGE_SOURCE_KINDS.includes(
source.kind as PluginPackageSourceKind,
)
) {
throw new InvalidPluginPackageLockError('source kind is invalid');
}
const kind = source.kind as PluginPackageSourceKind;
const locator = boundedText(
source.locator,
'source locator',
512,
InvalidPluginPackageLockError,
);
const artifactDigest = digest(
source.artifactDigest,
'source artifact digest',
InvalidPluginPackageLockError,
);
const locatorMatch =
kind === 'oci'
? locator.match(OCI_LOCATOR_PATTERN)
: locator.match(OFFLINE_LOCATOR_PATTERN);
if (!locatorMatch) {
throw new InvalidPluginPackageLockError('source locator is not immutable');
}
if (kind === 'oci') {
const registryMatch = locatorMatch[1]?.match(OCI_REGISTRY_PATTERN);
if (
!registryMatch ||
Buffer.byteLength(registryMatch[1]!, 'utf8') > 253 ||
(registryMatch[2] !== undefined && Number(registryMatch[2]) > 65_535)
) {
throw new InvalidPluginPackageLockError(
'source OCI registry is not canonical',
);
}
} else if (locatorMatch.at(-1) !== artifactDigest) {
throw new InvalidPluginPackageLockError(
'offline source locator does not match its artifact digest',
);
}
return Object.freeze({
kind,
locator,
artifactDigest,
artifactBytes: positiveInteger(
source.artifactBytes,
'source artifact bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
contentDigest: digest(
source.contentDigest,
'source content digest',
InvalidPluginPackageLockError,
),
});
}
export function normalizeSubject(value: unknown): Readonly<SecuritySubject> {
const subject = lockObject(value, 'approval subject');
exactKeys(
subject,
['type', 'id'],
[],
'approval subject',
InvalidPluginPackageLockError,
);
if (
!SECURITY_SUBJECT_TYPES.includes(subject.type as SecuritySubject['type'])
) {
throw new InvalidPluginPackageLockError('approval subject type is invalid');
}
return Object.freeze({
type: subject.type as SecuritySubject['type'],
id: boundedText(
subject.id,
'approval subject id',
255,
InvalidPluginPackageLockError,
),
});
}
export function normalizeFence(value: unknown): Readonly<SecurityPolicyFence> {
const fence = lockObject(value, 'approval fence');
exactKeys(
fence,
['projectVersion', 'bindingVersion'],
[],
'approval fence',
InvalidPluginPackageLockError,
);
return Object.freeze({
projectVersion: positiveInteger(
fence.projectVersion,
'approval project version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
bindingVersion:
fence.bindingVersion === null
? null
: positiveInteger(
fence.bindingVersion,
'approval binding version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
});
}
export function normalizeApproval(
value: unknown,
createdAtMs: number,
): Readonly<PluginPackageApprovalLock> {
const approval = lockObject(value, 'approval');
exactKeys(
approval,
[
'requestId',
'requestVersion',
'dispatchId',
'actionDigest',
'previewDigest',
'approvedBy',
'approvedAtMs',
'expiresAtMs',
'fence',
],
[],
'approval',
InvalidPluginPackageLockError,
);
const approvedAtMs = timestamp(
approval.approvedAtMs,
'approval time',
InvalidPluginPackageLockError,
);
const expiresAtMs = timestamp(
approval.expiresAtMs,
'approval expiry',
InvalidPluginPackageLockError,
);
if (approvedAtMs > createdAtMs || expiresAtMs <= createdAtMs) {
throw new InvalidPluginPackageLockError(
'approval is not active when the lock is created',
);
}
const approvedBy = normalizeSubject(approval.approvedBy);
if (approvedBy.type !== 'user') {
throw new InvalidPluginPackageLockError(
'package installation requires a human approval',
);
}
return Object.freeze({
requestId: identifier(
approval.requestId,
'approval request id',
InvalidPluginPackageLockError,
),
requestVersion: positiveInteger(
approval.requestVersion,
'approval request version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
dispatchId: identifier(
approval.dispatchId,
'approval dispatch id',
InvalidPluginPackageLockError,
),
actionDigest: digest(
approval.actionDigest,
'approval action digest',
InvalidPluginPackageLockError,
),
previewDigest: digest(
approval.previewDigest,
'approval preview digest',
InvalidPluginPackageLockError,
),
approvedBy,
approvedAtMs,
expiresAtMs,
fence: normalizeFence(approval.fence),
});
}
export function normalizeStringArray(
value: unknown,
label: string,
): readonly string[] {
if (!Array.isArray(value) || value.length > 256) {
throw new InvalidPluginPackageLockError(`${label} is invalid`);
}
const normalized = value.map((entry) =>
boundedText(entry, label, 512, InvalidPluginPackageLockError),
);
if (
new Set(normalized).size !== normalized.length ||
normalized.some(
(entry, index) => index > 0 && normalized[index - 1]! > entry,
)
) {
throw new InvalidPluginPackageLockError(
`${label} must be unique and sorted`,
);
}
return Object.freeze(normalized);
}
export function normalizePlan(value: unknown): Readonly<PluginPackageInstallPlan> {
const plan = lockObject(value, 'install plan');
exactKeys(
plan,
[
'package',
'operation',
'compatible',
'risk',
'approvalRequired',
'permissionReapprovalRequired',
'permissionDelta',
'resources',
'contents',
'findings',
],
[],
'install plan',
InvalidPluginPackageLockError,
);
if (
plan.compatible !== true ||
plan.approvalRequired !== true ||
typeof plan.permissionReapprovalRequired !== 'boolean' ||
!PLAN_RISKS.includes(plan.risk as PluginPackageRisk) ||
!PLAN_OPERATIONS.includes(plan.operation as PluginPackagePlanOperation)
) {
throw new InvalidPluginPackageLockError(
'install plan is not compatible or has invalid policy fields',
);
}
const packageValue = lockObject(plan.package, 'install plan package');
exactKeys(
packageValue,
['name', 'toVersion'],
['fromVersion'],
'install plan package',
InvalidPluginPackageLockError,
);
const packageName = boundedText(
packageValue.name,
'install plan package name',
64,
InvalidPluginPackageLockError,
);
if (!PACKAGE_NAME_PATTERN.test(packageName)) {
throw new InvalidPluginPackageLockError(
'install plan package name is invalid',
);
}
const toVersion = boundedText(
packageValue.toVersion,
'install plan target version',
128,
InvalidPluginPackageLockError,
);
if (semver().valid(toVersion) !== toVersion) {
throw new InvalidPluginPackageLockError(
'install plan target version is invalid',
);
}
const operation = plan.operation as PluginPackagePlanOperation;
const fromVersion =
packageValue.fromVersion === undefined
? undefined
: boundedText(
packageValue.fromVersion,
'install plan source version',
128,
InvalidPluginPackageLockError,
);
if (
fromVersion !== undefined &&
semver().valid(fromVersion) !== fromVersion
) {
throw new InvalidPluginPackageLockError(
'install plan source version is invalid',
);
}
if (
(operation === 'install' && fromVersion !== undefined) ||
(operation !== 'install' && fromVersion === undefined)
) {
throw new InvalidPluginPackageLockError(
'install plan operation does not match its package versions',
);
}
const delta = lockObject(plan.permissionDelta, 'permission delta');
exactKeys(
delta,
['added', 'removed'],
[],
'permission delta',
InvalidPluginPackageLockError,
);
const resources = lockObject(plan.resources, 'install resources');
exactKeys(
resources,
['memoryRecommendedBytes', 'diskInstallBytes', 'diskWorkingBytes'],
[],
'install resources',
InvalidPluginPackageLockError,
);
const contents = lockObject(plan.contents, 'install contents');
exactKeys(
contents,
['tasks', 'workflows', 'prompts', 'tools'],
[],
'install contents',
InvalidPluginPackageLockError,
);
if (!Array.isArray(plan.findings) || plan.findings.length > 32) {
throw new InvalidPluginPackageLockError('install findings are invalid');
}
const findings = plan.findings.map((entry) => {
const finding = lockObject(entry, 'install finding');
exactKeys(
finding,
['code', 'severity', 'subject'],
[],
'install finding',
InvalidPluginPackageLockError,
);
if (
!PLAN_FINDING_CODES.has(finding.code as string) ||
finding.severity !== 'warning'
) {
throw new InvalidPluginPackageLockError(
'compatible install plan contains an invalid finding',
);
}
return Object.freeze({
code: finding.code as PluginPackageInstallPlan['findings'][number]['code'],
severity: 'warning' as const,
subject: boundedText(
finding.subject,
'install finding subject',
512,
InvalidPluginPackageLockError,
),
});
});
return Object.freeze({
package: Object.freeze({
name: packageName,
...(fromVersion === undefined ? {} : { fromVersion }),
toVersion,
}),
operation,
compatible: true,
risk: plan.risk as PluginPackageRisk,
approvalRequired: true,
permissionReapprovalRequired: plan.permissionReapprovalRequired as boolean,
permissionDelta: Object.freeze({
added: normalizeStringArray(delta.added, 'added permission'),
removed: normalizeStringArray(delta.removed, 'removed permission'),
}),
resources: Object.freeze({
memoryRecommendedBytes: positiveInteger(
resources.memoryRecommendedBytes,
'recommended memory bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
diskInstallBytes: positiveInteger(
resources.diskInstallBytes,
'install disk bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
diskWorkingBytes: positiveInteger(
resources.diskWorkingBytes,
'working disk bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
}),
contents: Object.freeze({
tasks: nonNegativeInteger(
contents.tasks,
'task count',
256,
InvalidPluginPackageLockError,
),
workflows: nonNegativeInteger(
contents.workflows,
'workflow count',
256,
InvalidPluginPackageLockError,
),
prompts: nonNegativeInteger(
contents.prompts,
'prompt count',
256,
InvalidPluginPackageLockError,
),
tools: nonNegativeInteger(
contents.tools,
'tool count',
256,
InvalidPluginPackageLockError,
),
}),
findings: Object.freeze(findings),
});
}
export function lockActionPayload(
input: Readonly<{
lockId: string;
projectId: string;
packageName: string;
packageVersion: string;
operation: PluginPackagePlanOperation;
source: Readonly<PluginPackageSourceLock>;
manifestDigest: string;
resources: readonly Readonly<PluginPackageResourceReference>[];
planDigest: string;
environmentDigest: string;
architecture: PluginPackageArchitecture;
deploymentProfile: PluginPackageDeploymentProfile;
targetGeneration: number;
previousLockDigest?: string;
}>,
): Readonly<Record<string, unknown>> {
return Object.freeze({
schema: PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA,
lockId: input.lockId,
projectId: input.projectId,
packageName: input.packageName,
packageVersion: input.packageVersion,
operation: input.operation,
source: input.source,
manifestDigest: input.manifestDigest,
resources: input.resources,
planDigest: input.planDigest,
environmentDigest: input.environmentDigest,
architecture: input.architecture,
deploymentProfile: input.deploymentProfile,
targetGeneration: input.targetGeneration,
...(input.previousLockDigest === undefined
? {}
: { previousLockDigest: input.previousLockDigest }),
});
}
export function pluginPackageInstallActionDigest(
input: Omit<CreatePluginPackageLockInput, 'approval' | 'createdAtMs'>,
): string {
const value = lockObject(input, 'install action input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'architecture',
'deploymentProfile',
'targetGeneration',
],
['previousLockDigest', 'previousManifest'],
'install action input',
InvalidPluginPackageLockError,
);
const prepared = prepareLockFields({
...input,
createdAtMs: 0,
});
return contentDigest(lockActionPayload(prepared));
}
export function pluginPackageInstallPlanDigest(
value: PluginPackageInstallPlan,
): string {
return contentDigest(normalizePlan(value));
}
export function normalizePluginPackageInstallActionInput(
input: PluginPackageInstallActionInput,
): Readonly<PluginPackageInstallActionInput> {
const value = lockObject(input, 'install action input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'architecture',
'deploymentProfile',
'targetGeneration',
],
['previousLockDigest', 'previousManifest'],
'install action input',
InvalidPluginPackageLockError,
);
const prepared = prepareLockFields({
...input,
createdAtMs: 0,
});
const previousManifest =
input.previousManifest === undefined
? undefined
: normalizePluginPackageManifest(input.previousManifest);
return Object.freeze({
lockId: prepared.lockId,
projectId: prepared.projectId,
manifest: normalizePluginPackageManifest(input.manifest),
plan: normalizePlan(input.plan),
environment: normalizePluginPackageInstallEnvironment(input.environment),
...(previousManifest === undefined ? {} : { previousManifest }),
source: prepared.source,
architecture: prepared.architecture,
deploymentProfile: prepared.deploymentProfile,
targetGeneration: prepared.targetGeneration,
...(prepared.previousLockDigest === undefined
? {}
: { previousLockDigest: prepared.previousLockDigest }),
});
}
export function prepareLockFields(
input: Omit<CreatePluginPackageLockInput, 'approval'>,
): Readonly<{
lockId: string;
projectId: string;
packageName: string;
packageVersion: string;
operation: PluginPackagePlanOperation;
source: Readonly<PluginPackageSourceLock>;
manifestDigest: string;
resources: readonly Readonly<PluginPackageResourceReference>[];
planDigest: string;
environmentDigest: string;
architecture: PluginPackageArchitecture;
deploymentProfile: PluginPackageDeploymentProfile;
targetGeneration: number;
previousLockDigest?: string;
createdAtMs: number;
}> {
const manifest = normalizePluginPackageManifest(input.manifest);
const environment = normalizePluginPackageInstallEnvironment(
input.environment,
);
const previousManifest =
input.previousManifest === undefined
? undefined
: normalizePluginPackageManifest(input.previousManifest);
const plan = normalizePlan(input.plan);
const expectedPlan = normalizePlan(
planPluginPackageInstall(manifest, environment, previousManifest),
);
if (
manifest.metadata.name !== plan.package.name ||
manifest.metadata.version !== plan.package.toVersion ||
contentDigest(plan) !== contentDigest(expectedPlan)
) {
throw new InvalidPluginPackageLockError(
'manifest, environment or previous manifest does not match the install plan',
);
}
if (!PLUGIN_PACKAGE_ARCHITECTURES.includes(input.architecture)) {
throw new InvalidPluginPackageLockError('target architecture is invalid');
}
if (!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(input.deploymentProfile)) {
throw new InvalidPluginPackageLockError(
'target deployment profile is invalid',
);
}
if (
input.architecture !== environment.architecture ||
input.deploymentProfile !== environment.deploymentProfile
) {
throw new InvalidPluginPackageLockError(
'target architecture or profile does not match the install environment',
);
}
const targetGeneration = positiveInteger(
input.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
);
const previousLockDigest =
input.previousLockDigest === undefined
? undefined
: digest(
input.previousLockDigest,
'previous lock digest',
InvalidPluginPackageLockError,
);
if (
(plan.operation === 'install' &&
(targetGeneration !== 1 || previousLockDigest !== undefined)) ||
(plan.operation !== 'install' &&
(targetGeneration < 2 || previousLockDigest === undefined))
) {
throw new InvalidPluginPackageLockError(
'operation does not match the target generation or previous lock',
);
}
return Object.freeze({
lockId: identifier(input.lockId, 'lock id', InvalidPluginPackageLockError),
projectId: boundedText(
input.projectId,
'project id',
128,
InvalidPluginPackageLockError,
),
packageName: manifest.metadata.name,
packageVersion: manifest.metadata.version,
operation: plan.operation,
source: normalizeSource(input.source),
manifestDigest: pluginPackageManifestDigest(manifest),
resources: pluginPackageResourceReferencesFromContents(
manifest.spec.contents,
),
planDigest: contentDigest(plan),
environmentDigest: contentDigest(environment),
architecture: input.architecture,
deploymentProfile: input.deploymentProfile,
targetGeneration,
...(previousLockDigest === undefined ? {} : { previousLockDigest }),
createdAtMs: timestamp(
input.createdAtMs,
'lock creation time',
InvalidPluginPackageLockError,
),
});
}
export function createPluginPackageLock(
input: CreatePluginPackageLockInput,
): Readonly<PluginPackageLock> {
const value = lockObject(input, 'lock input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'approval',
'architecture',
'deploymentProfile',
'targetGeneration',
'createdAtMs',
],
['previousLockDigest', 'previousManifest'],
'lock input',
InvalidPluginPackageLockError,
);
const fields = prepareLockFields(input);
const actionDigest = contentDigest(lockActionPayload(fields));
const approval = normalizeApproval(input.approval, fields.createdAtMs);
if (
approval.actionDigest !== actionDigest ||
approval.previewDigest !== fields.planDigest
) {
throw new InvalidPluginPackageLockError(
'approval is not bound to this action and preview',
);
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_LOCK_SCHEMA,
...fields,
actionDigest,
approval,
});
return Object.freeze({
...unsigned,
lockDigest: contentDigest(unsigned),
});
}
export function normalizePluginPackageLock(
value: PluginPackageLock,
): Readonly<PluginPackageLock> {
const lock = lockObject(value, 'lock');
exactKeys(
lock,
[
'schema',
'lockId',
'projectId',
'packageName',
'packageVersion',
'operation',
'source',
'manifestDigest',
'resources',
'planDigest',
'environmentDigest',
'actionDigest',
'approval',
'architecture',
'deploymentProfile',
'targetGeneration',
'createdAtMs',
'lockDigest',
],
['previousLockDigest'],
'lock',
InvalidPluginPackageLockError,
);
if (
lock.schema !== PLUGIN_PACKAGE_LOCK_SCHEMA ||
!PLAN_OPERATIONS.includes(lock.operation as PluginPackagePlanOperation) ||
!PLUGIN_PACKAGE_ARCHITECTURES.includes(
lock.architecture as PluginPackageArchitecture,
) ||
!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(
lock.deploymentProfile as PluginPackageDeploymentProfile,
)
) {
throw new InvalidPluginPackageLockError('lock vocabulary is invalid');
}
const targetGeneration = positiveInteger(
lock.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
);
const previousLockDigest =
lock.previousLockDigest === undefined
? undefined
: digest(
lock.previousLockDigest,
'previous lock digest',
InvalidPluginPackageLockError,
);
if (
(lock.operation === 'install' &&
(targetGeneration !== 1 || previousLockDigest !== undefined)) ||
(lock.operation !== 'install' &&
(targetGeneration < 2 || previousLockDigest === undefined))
) {
throw new InvalidPluginPackageLockError(
'operation does not match lock generation',
);
}
const createdAtMs = timestamp(
lock.createdAtMs,
'lock creation time',
InvalidPluginPackageLockError,
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_LOCK_SCHEMA,
lockId: identifier(lock.lockId, 'lock id', InvalidPluginPackageLockError),
projectId: boundedText(
lock.projectId,
'project id',
128,
InvalidPluginPackageLockError,
),
packageName: boundedText(
lock.packageName,
'package name',
64,
InvalidPluginPackageLockError,
),
packageVersion: boundedText(
lock.packageVersion,
'package version',
128,
InvalidPluginPackageLockError,
),
operation: lock.operation as PluginPackagePlanOperation,
source: normalizeSource(lock.source),
manifestDigest: digest(
lock.manifestDigest,
'manifest digest',
InvalidPluginPackageLockError,
),
resources: normalizePluginPackageResourceReferences(lock.resources),
planDigest: digest(
lock.planDigest,
'plan digest',
InvalidPluginPackageLockError,
),
environmentDigest: digest(
lock.environmentDigest,
'environment digest',
InvalidPluginPackageLockError,
),
actionDigest: digest(
lock.actionDigest,
'action digest',
InvalidPluginPackageLockError,
),
approval: normalizeApproval(lock.approval, createdAtMs),
architecture: lock.architecture as PluginPackageArchitecture,
deploymentProfile: lock.deploymentProfile as PluginPackageDeploymentProfile,
targetGeneration,
...(previousLockDigest === undefined ? {} : { previousLockDigest }),
createdAtMs,
});
if (
!PACKAGE_NAME_PATTERN.test(unsigned.packageName) ||
semver().valid(unsigned.packageVersion) !== unsigned.packageVersion ||
unsigned.approval.approvedBy.type !== 'user'
) {
throw new InvalidPluginPackageLockError(
'lock package identity or human approval is invalid',
);
}
if (
unsigned.approval.actionDigest !== unsigned.actionDigest ||
unsigned.approval.previewDigest !== unsigned.planDigest ||
contentDigest(lockActionPayload(unsigned)) !== unsigned.actionDigest
) {
throw new InvalidPluginPackageLockError('lock approval binding is invalid');
}
const lockDigest = digest(
lock.lockDigest,
'lock digest',
InvalidPluginPackageLockError,
);
if (contentDigest(unsigned) !== lockDigest) {
throw new InvalidPluginPackageLockError('lock digest does not match');
}
return Object.freeze({ ...unsigned, lockDigest });
}
@@ -0,0 +1,560 @@
import type { PluginPackagePlanOperation } from '../../pluginPackage';
import { semver } from '../../../versioning/pinnedSemver';
import {
PLUGIN_PACKAGE_INSTALL_SCHEMA,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_INSTALL_STATES,
PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
type PluginPackageInstallState,
type PluginPackageInstallFailureReason,
type PluginPackageLock,
type PluginPackageStageReceipt,
type PluginPackageActivationReceipt,
type CreatePluginPackageActivationReceiptInput,
type PluginPackageInstallFailure,
type PluginPackageInstallRecord,
type CreatePluginPackageInstallInput,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
PLAN_OPERATIONS,
exactKeys,
installObject,
identifier,
boundedText,
digest,
timestamp,
positiveInteger,
contentDigest,
} from './codec';
import { normalizePluginPackageLock } from './lock';
export function initialMutationDigest(
lockDigest: string,
input: Readonly<CreatePluginPackageInstallInput>,
): string {
return contentDigest({
type: 'install_created',
lockDigest,
installationId: input.installationId,
mutationId: input.mutationId,
occurredAtMs: input.occurredAtMs,
});
}
export function recordWithoutDigest(
value: Omit<PluginPackageInstallRecord, 'recordDigest'>,
): Omit<PluginPackageInstallRecord, 'recordDigest'> {
return Object.freeze(value);
}
export function withRecordDigest(
value: Omit<PluginPackageInstallRecord, 'recordDigest'>,
): Readonly<PluginPackageInstallRecord> {
const normalized = recordWithoutDigest(value);
return Object.freeze({
...normalized,
recordDigest: contentDigest(normalized),
});
}
export function createPluginPackageInstall(
lockValue: PluginPackageLock,
input: CreatePluginPackageInstallInput,
): Readonly<PluginPackageInstallRecord> {
const lock = normalizePluginPackageLock(lockValue);
const value = installObject(input, 'create input');
exactKeys(
value,
['installationId', 'mutationId', 'occurredAtMs'],
[],
'create input',
InvalidPluginPackageInstallError,
);
const occurredAtMs = timestamp(
input.occurredAtMs,
'creation time',
InvalidPluginPackageInstallError,
);
if (
occurredAtMs < lock.createdAtMs ||
occurredAtMs >= lock.approval.expiresAtMs
) {
throw new InvalidPluginPackageInstallError(
'creation time is outside the approved action lifetime',
);
}
const normalizedInput = Object.freeze({
installationId: identifier(
input.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
mutationId: identifier(
input.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
),
occurredAtMs,
});
const previousActiveLockDigest = lock.previousLockDigest ?? null;
return withRecordDigest({
schema: PLUGIN_PACKAGE_INSTALL_SCHEMA,
installationId: normalizedInput.installationId,
projectId: lock.projectId,
packageName: lock.packageName,
packageVersion: lock.packageVersion,
operation: lock.operation,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest,
activeLockDigest: previousActiveLockDigest,
state: 'queued',
version: 1,
lastMutationId: normalizedInput.mutationId,
lastMutationDigest: initialMutationDigest(lock.lockDigest, normalizedInput),
stageReceipt: null,
activationReceipt: null,
failure: null,
createdAtMs: occurredAtMs,
updatedAtMs: occurredAtMs,
});
}
export function normalizeStageReceipt(
value: unknown,
): Readonly<PluginPackageStageReceipt> {
const receipt = installObject(value, 'stage receipt');
exactKeys(
receipt,
[
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
'stagedAtMs',
'receiptDigest',
],
[],
'stage receipt',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
stageRef: identifier(
receipt.stageRef,
'stage reference',
InvalidPluginPackageInstallError,
),
artifactDigest: digest(
receipt.artifactDigest,
'staged artifact digest',
InvalidPluginPackageInstallError,
),
manifestDigest: digest(
receipt.manifestDigest,
'staged manifest digest',
InvalidPluginPackageInstallError,
),
contentDigest: digest(
receipt.contentDigest,
'staged content digest',
InvalidPluginPackageInstallError,
),
evidenceDigest: digest(
receipt.evidenceDigest,
'staged evidence digest',
InvalidPluginPackageInstallError,
),
stagedAtMs: timestamp(
receipt.stagedAtMs,
'staged time',
InvalidPluginPackageInstallError,
),
});
const receiptDigest = digest(
receipt.receiptDigest,
'stage receipt digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageInstallError(
'stage receipt digest does not match',
);
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function normalizePluginPackageActivationReceipt(
value: unknown,
): Readonly<PluginPackageActivationReceipt> {
const receipt = installObject(value, 'activation receipt');
exactKeys(
receipt,
[
'activationRef',
'intentDigest',
'generation',
'contentDigest',
'activatedAtMs',
'receiptDigest',
],
[],
'activation receipt',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
activationRef: identifier(
receipt.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
receipt.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
receipt.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
receipt.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
activatedAtMs: timestamp(
receipt.activatedAtMs,
'activation time',
InvalidPluginPackageInstallError,
),
});
const receiptDigest = digest(
receipt.receiptDigest,
'activation receipt digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageInstallError(
'activation receipt digest does not match',
);
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function createPluginPackageActivationReceipt(
value: CreatePluginPackageActivationReceiptInput,
): Readonly<PluginPackageActivationReceipt> {
const receipt = installObject(value, 'activation receipt input');
exactKeys(
receipt,
[
'activationRef',
'intentDigest',
'generation',
'contentDigest',
'activatedAtMs',
],
[],
'activation receipt input',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
activationRef: identifier(
value.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
value.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
value.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
value.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
activatedAtMs: timestamp(
value.activatedAtMs,
'activated time',
InvalidPluginPackageInstallError,
),
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function normalizeFailure(
value: unknown,
): Readonly<PluginPackageInstallFailure> {
const failure = installObject(value, 'failure');
exactKeys(
failure,
['reason', 'failedFrom', 'failedAtMs'],
[],
'failure',
InvalidPluginPackageInstallError,
);
if (
!PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS.includes(
failure.reason as PluginPackageInstallFailureReason,
) ||
!['queued', 'staged', 'activating'].includes(failure.failedFrom as string)
) {
throw new InvalidPluginPackageInstallError('failure vocabulary is invalid');
}
return Object.freeze({
reason: failure.reason as PluginPackageInstallFailureReason,
failedFrom: failure.failedFrom as PluginPackageInstallFailure['failedFrom'],
failedAtMs: timestamp(
failure.failedAtMs,
'failure time',
InvalidPluginPackageInstallError,
),
});
}
export function normalizePluginPackageInstallRecord(
value: PluginPackageInstallRecord,
): Readonly<PluginPackageInstallRecord> {
const record = installObject(value, 'record');
exactKeys(
record,
[
'schema',
'installationId',
'projectId',
'packageName',
'packageVersion',
'operation',
'lockDigest',
'targetGeneration',
'previousActiveLockDigest',
'activeLockDigest',
'state',
'version',
'lastMutationId',
'lastMutationDigest',
'stageReceipt',
'activationReceipt',
'failure',
'createdAtMs',
'updatedAtMs',
'recordDigest',
],
[],
'record',
InvalidPluginPackageInstallError,
);
if (
record.schema !== PLUGIN_PACKAGE_INSTALL_SCHEMA ||
!PLAN_OPERATIONS.includes(record.operation as PluginPackagePlanOperation) ||
!PLUGIN_PACKAGE_INSTALL_STATES.includes(
record.state as PluginPackageInstallState,
)
) {
throw new InvalidPluginPackageInstallError('record vocabulary is invalid');
}
const createdAtMs = timestamp(
record.createdAtMs,
'creation time',
InvalidPluginPackageInstallError,
);
const updatedAtMs = timestamp(
record.updatedAtMs,
'update time',
InvalidPluginPackageInstallError,
);
if (updatedAtMs < createdAtMs) {
throw new InvalidPluginPackageInstallError('record timestamps are invalid');
}
const previousActiveLockDigest =
record.previousActiveLockDigest === null
? null
: digest(
record.previousActiveLockDigest,
'previous active lock digest',
InvalidPluginPackageInstallError,
);
const activeLockDigest =
record.activeLockDigest === null
? null
: digest(
record.activeLockDigest,
'active lock digest',
InvalidPluginPackageInstallError,
);
const state = record.state as PluginPackageInstallState;
const lockDigest = digest(
record.lockDigest,
'lock digest',
InvalidPluginPackageInstallError,
);
const targetGeneration = positiveInteger(
record.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
);
if (
(record.operation === 'install' &&
(targetGeneration !== 1 || previousActiveLockDigest !== null)) ||
(record.operation !== 'install' &&
(targetGeneration < 2 || previousActiveLockDigest === null))
) {
throw new InvalidPluginPackageInstallError(
'record operation does not match its generation',
);
}
if (
(state === 'active' && activeLockDigest !== lockDigest) ||
(state !== 'active' && activeLockDigest !== previousActiveLockDigest)
) {
throw new InvalidPluginPackageInstallError(
'active lock pointer does not match install state',
);
}
const stageReceipt =
record.stageReceipt === null
? null
: normalizeStageReceipt(record.stageReceipt);
const activationReceipt =
record.activationReceipt === null
? null
: normalizePluginPackageActivationReceipt(record.activationReceipt);
const failure =
record.failure === null ? null : normalizeFailure(record.failure);
if (
((state === 'queued' || state === 'failed') &&
state !== 'failed' &&
stageReceipt !== null) ||
((state === 'staged' || state === 'activating' || state === 'active') &&
stageReceipt === null) ||
(state === 'active' && activationReceipt === null) ||
(state !== 'active' && activationReceipt !== null) ||
(state === 'failed' ? failure === null : failure !== null)
) {
throw new InvalidPluginPackageInstallError(
'record receipts do not match install state',
);
}
if (
failure &&
((failure.failedFrom === 'queued' && stageReceipt !== null) ||
(failure.failedFrom !== 'queued' && stageReceipt === null))
) {
throw new InvalidPluginPackageInstallError(
'failure receipts do not match the failed state',
);
}
const unsigned = recordWithoutDigest({
schema: PLUGIN_PACKAGE_INSTALL_SCHEMA,
installationId: identifier(
record.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
projectId: boundedText(
record.projectId,
'project id',
128,
InvalidPluginPackageInstallError,
),
packageName: boundedText(
record.packageName,
'package name',
64,
InvalidPluginPackageInstallError,
),
packageVersion: boundedText(
record.packageVersion,
'package version',
128,
InvalidPluginPackageInstallError,
),
operation: record.operation as PluginPackagePlanOperation,
lockDigest,
targetGeneration,
previousActiveLockDigest,
activeLockDigest,
state,
version: positiveInteger(
record.version,
'record version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
lastMutationId: identifier(
record.lastMutationId,
'last mutation id',
InvalidPluginPackageInstallError,
),
lastMutationDigest: digest(
record.lastMutationDigest,
'last mutation digest',
InvalidPluginPackageInstallError,
),
stageReceipt,
activationReceipt,
failure,
createdAtMs,
updatedAtMs,
});
if (
!PACKAGE_NAME_PATTERN.test(unsigned.packageName) ||
semver().valid(unsigned.packageVersion) !== unsigned.packageVersion
) {
throw new InvalidPluginPackageInstallError(
'record package identity is invalid',
);
}
const recordDigest = digest(
record.recordDigest,
'record digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== recordDigest) {
throw new InvalidPluginPackageInstallError('record digest does not match');
}
return Object.freeze({ ...unsigned, recordDigest });
}
export function assertRecordMatchesLock(
record: Readonly<PluginPackageInstallRecord>,
lock: Readonly<PluginPackageLock>,
): void {
if (
record.projectId !== lock.projectId ||
record.packageName !== lock.packageName ||
record.packageVersion !== lock.packageVersion ||
record.operation !== lock.operation ||
record.lockDigest !== lock.lockDigest ||
record.targetGeneration !== lock.targetGeneration ||
record.previousActiveLockDigest !== (lock.previousLockDigest ?? null)
) {
throw new PluginPackageInstallTransitionConflictError();
}
}
export function assertPluginPackageInstallMatchesLock(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): void {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
}
@@ -0,0 +1,295 @@
import {
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
type PluginPackageInstallRecoveryAction,
type PluginPackageLock,
type PluginPackageInstallRecord,
type PluginPackageInstallHeadExpectation,
type PluginPackageInstallCreate,
type PluginPackageInstallRecoveryCursor,
type PluginPackageInstallInventoryCursor,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
exactKeys,
installObject,
identifier,
boundedText,
digest,
positiveInteger,
contentDigest,
} from './codec';
import {
normalizePluginPackageLock,
} from './lock';
import {
initialMutationDigest,
normalizePluginPackageInstallRecord,
assertRecordMatchesLock,
} from './record';
export function normalizePluginPackageInstallHeadExpectation(
value: PluginPackageInstallHeadExpectation,
): Readonly<PluginPackageInstallHeadExpectation> {
const expectation = installObject(value, 'head expectation');
exactKeys(
expectation,
['installationId', 'version', 'recordDigest'],
[],
'head expectation',
InvalidPluginPackageInstallError,
);
return Object.freeze({
installationId: identifier(
value.installationId,
'head installation id',
InvalidPluginPackageInstallError,
),
version: positiveInteger(
value.version,
'head version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
recordDigest: digest(
value.recordDigest,
'head record digest',
InvalidPluginPackageInstallError,
),
});
}
export function normalizePluginPackageInstallCreate(
value: PluginPackageInstallCreate,
): Readonly<PluginPackageInstallCreate> {
const command = installObject(value, 'create command');
exactKeys(
command,
[
'installationId',
'mutationId',
'mutationDigest',
'expectedHead',
'lock',
'record',
],
[],
'create command',
InvalidPluginPackageInstallError,
);
const lock = normalizePluginPackageLock(value.lock);
const record = normalizePluginPackageInstallRecord(value.record);
assertRecordMatchesLock(record, lock);
const expectedHead =
value.expectedHead === null
? null
: normalizePluginPackageInstallHeadExpectation(value.expectedHead);
const installationId = identifier(
value.installationId,
'installation id',
InvalidPluginPackageInstallError,
);
const mutationId = identifier(
value.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
);
const mutationDigest = digest(
value.mutationDigest,
'create mutation digest',
InvalidPluginPackageInstallError,
);
if (
installationId !== record.installationId ||
mutationId !== record.lastMutationId ||
mutationDigest !==
contentDigest({
type: 'install_create_commit',
installationId,
mutationId,
lockDigest: lock.lockDigest,
recordDigest: record.recordDigest,
expectedHead,
})
) {
throw new InvalidPluginPackageInstallError(
'create command is detached from its record or head',
);
}
return Object.freeze({
installationId,
mutationId,
mutationDigest,
expectedHead,
lock,
record,
});
}
export function pluginPackageInstallRecoveryAction(
value: PluginPackageInstallRecord,
): PluginPackageInstallRecoveryAction {
const record = normalizePluginPackageInstallRecord(value);
switch (record.state) {
case 'queued':
return 'resume_stage';
case 'staged':
return 'resume_activation';
case 'activating':
return 'inspect_activation';
case 'active':
case 'failed':
return 'none';
}
}
export function assertPluginPackageInstallRecoveryPageSize(
value: number,
): void {
positiveInteger(
value,
'recovery page size',
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
InvalidPluginPackageInstallError,
);
}
export function assertPluginPackageInstallInventoryPageSize(
value: number,
): void {
positiveInteger(
value,
'inventory page size',
MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE,
InvalidPluginPackageInstallError,
);
}
export function normalizePluginPackageInstallInventoryCursor(
value: PluginPackageInstallInventoryCursor,
): Readonly<PluginPackageInstallInventoryCursor> {
const cursor = installObject(value, 'inventory cursor');
exactKeys(
cursor,
['packageName'],
[],
'inventory cursor',
InvalidPluginPackageInstallError,
);
const normalizedPackageName = boundedText(
value.packageName,
'package name',
253,
InvalidPluginPackageInstallError,
);
if (!PACKAGE_NAME_PATTERN.test(normalizedPackageName)) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({ packageName: normalizedPackageName });
}
export function normalizePluginPackageInstallRecoveryCursor(
value: PluginPackageInstallRecoveryCursor,
): Readonly<PluginPackageInstallRecoveryCursor> {
const cursor = installObject(value, 'recovery cursor');
exactKeys(
cursor,
['packageName', 'installationId'],
[],
'recovery cursor',
InvalidPluginPackageInstallError,
);
const normalizedPackageName = boundedText(
value.packageName,
'package name',
253,
InvalidPluginPackageInstallError,
);
if (!PACKAGE_NAME_PATTERN.test(normalizedPackageName)) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({
packageName: normalizedPackageName,
installationId: identifier(
value.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
});
}
export function pluginPackageInstallCreate(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
previousHeadValue: PluginPackageInstallRecord | null,
): Readonly<PluginPackageInstallCreate> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
const previousHead =
previousHeadValue === null
? null
: normalizePluginPackageInstallRecord(previousHeadValue);
if (
record.state !== 'queued' ||
record.version !== 1 ||
record.createdAtMs !== record.updatedAtMs ||
record.stageReceipt !== null ||
record.activationReceipt !== null ||
record.failure !== null ||
record.activeLockDigest !== record.previousActiveLockDigest ||
record.lastMutationDigest !==
initialMutationDigest(record.lockDigest, {
installationId: record.installationId,
mutationId: record.lastMutationId,
occurredAtMs: record.createdAtMs,
})
) {
throw new InvalidPluginPackageInstallError(
'initial install record is invalid',
);
}
if (previousHead === null) {
if (
record.previousActiveLockDigest !== null ||
record.operation !== 'install' ||
record.targetGeneration !== 1
) {
throw new PluginPackageInstallTransitionConflictError();
}
} else if (
previousHead.projectId !== record.projectId ||
previousHead.packageName !== record.packageName ||
previousHead.installationId === record.installationId ||
!['active', 'failed'].includes(previousHead.state) ||
previousHead.activeLockDigest !== record.previousActiveLockDigest
) {
throw new PluginPackageInstallTransitionConflictError();
}
const expectedHead =
previousHead === null
? null
: Object.freeze({
installationId: previousHead.installationId,
version: previousHead.version,
recordDigest: previousHead.recordDigest,
});
return normalizePluginPackageInstallCreate({
installationId: record.installationId,
mutationId: record.lastMutationId,
mutationDigest: contentDigest({
type: 'install_create_commit',
installationId: record.installationId,
mutationId: record.lastMutationId,
lockDigest: lock.lockDigest,
recordDigest: record.recordDigest,
expectedHead,
}),
expectedHead,
lock,
record,
});
}
@@ -0,0 +1,396 @@
import { createPluginPackageResourceGenerationFromReferences } from '../../pluginPackageResourceGeneration';
import {
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallMutationConflictError,
type PluginPackageInstallState,
type PluginPackageInstallFailureReason,
type PluginPackageLock,
type PluginPackageStageReceipt,
type PluginPackageActivationReceipt,
type PluginPackageInstallFailure,
type PluginPackageInstallRecord,
type PluginPackageInstallEvent,
type PluginPackageInstallCommit,
} from './contracts';
import {
exactKeys,
installObject,
identifier,
digest,
timestamp,
positiveInteger,
contentDigest,
} from './codec';
import { normalizePluginPackageLock } from './lock';
import {
initialMutationDigest,
withRecordDigest,
normalizePluginPackageInstallRecord,
assertRecordMatchesLock,
} from './record';
export function normalizeEvent(
value: PluginPackageInstallEvent,
): Readonly<PluginPackageInstallEvent> {
const event = installObject(value, 'event');
if (
![
'stage_completed',
'activation_started',
'activation_committed',
'failed',
].includes(event.type as string)
) {
throw new InvalidPluginPackageInstallError('event type is invalid');
}
const common = {
type: event.type,
mutationId: identifier(
event.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
),
occurredAtMs: timestamp(
event.occurredAtMs,
'event time',
InvalidPluginPackageInstallError,
),
};
switch (event.type) {
case 'stage_completed':
exactKeys(
event,
[
'type',
'mutationId',
'occurredAtMs',
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
],
[],
'stage event',
InvalidPluginPackageInstallError,
);
return Object.freeze({
...common,
type: 'stage_completed',
stageRef: identifier(
event.stageRef,
'stage reference',
InvalidPluginPackageInstallError,
),
artifactDigest: digest(
event.artifactDigest,
'staged artifact digest',
InvalidPluginPackageInstallError,
),
manifestDigest: digest(
event.manifestDigest,
'staged manifest digest',
InvalidPluginPackageInstallError,
),
contentDigest: digest(
event.contentDigest,
'staged content digest',
InvalidPluginPackageInstallError,
),
evidenceDigest: digest(
event.evidenceDigest,
'staged evidence digest',
InvalidPluginPackageInstallError,
),
});
case 'activation_started':
exactKeys(
event,
['type', 'mutationId', 'occurredAtMs'],
[],
'activation start event',
InvalidPluginPackageInstallError,
);
return Object.freeze({ ...common, type: 'activation_started' });
case 'activation_committed':
exactKeys(
event,
[
'type',
'mutationId',
'occurredAtMs',
'activationRef',
'intentDigest',
'generation',
'contentDigest',
],
[],
'activation commit event',
InvalidPluginPackageInstallError,
);
return Object.freeze({
...common,
type: 'activation_committed',
activationRef: identifier(
event.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
event.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
event.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
event.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
});
case 'failed':
exactKeys(
event,
['type', 'mutationId', 'occurredAtMs', 'reason'],
[],
'failure event',
InvalidPluginPackageInstallError,
);
if (
!PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS.includes(
event.reason as PluginPackageInstallFailureReason,
)
) {
throw new InvalidPluginPackageInstallError('failure reason is invalid');
}
return Object.freeze({
...common,
type: 'failed',
reason: event.reason as PluginPackageInstallFailureReason,
});
default:
throw new InvalidPluginPackageInstallError('event type is invalid');
}
}
export function eventDigest(event: Readonly<PluginPackageInstallEvent>): string {
return contentDigest(event);
}
export function makeStageReceipt(
event: Extract<PluginPackageInstallEvent, { type: 'stage_completed' }>,
): Readonly<PluginPackageStageReceipt> {
const unsigned = Object.freeze({
stageRef: event.stageRef,
artifactDigest: event.artifactDigest,
manifestDigest: event.manifestDigest,
contentDigest: event.contentDigest,
evidenceDigest: event.evidenceDigest,
stagedAtMs: event.occurredAtMs,
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function makeActivationReceipt(
event: Extract<PluginPackageInstallEvent, { type: 'activation_committed' }>,
): Readonly<PluginPackageActivationReceipt> {
const unsigned = Object.freeze({
activationRef: event.activationRef,
intentDigest: event.intentDigest,
generation: event.generation,
contentDigest: event.contentDigest,
activatedAtMs: event.occurredAtMs,
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function activationIntentDigest(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
): string {
if (record.state !== 'activating' || record.stageReceipt === null) {
throw new PluginPackageInstallTransitionConflictError();
}
const resourceGeneration =
createPluginPackageResourceGenerationFromReferences({
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
generation: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
contentDigest: lock.source.contentDigest,
resources: lock.resources,
});
return contentDigest({
type: 'plugin_package_activation_intent',
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
stageRef: record.stageReceipt.stageRef,
stageReceiptDigest: record.stageReceipt.receiptDigest,
stageEvidenceDigest: record.stageReceipt.evidenceDigest,
contentDigest: lock.source.contentDigest,
resourceGenerationDigest: resourceGeneration.generationDigest,
});
}
export function pluginPackageActivationIntentDigest(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): string {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
return activationIntentDigest(lock, record);
}
export function transitionPluginPackageInstall(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
eventValue: PluginPackageInstallEvent,
): Readonly<PluginPackageInstallRecord> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
const event = normalizeEvent(eventValue);
assertRecordMatchesLock(record, lock);
const mutationDigest = eventDigest(event);
if (record.lastMutationId === event.mutationId) {
if (record.lastMutationDigest !== mutationDigest) {
throw new PluginPackageInstallMutationConflictError();
}
return record;
}
if (
event.occurredAtMs < record.updatedAtMs ||
record.version >= MAX_PLUGIN_PACKAGE_INSTALL_VERSION
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'stage_completed' &&
(record.state !== 'queued' ||
event.artifactDigest !== lock.source.artifactDigest ||
event.manifestDigest !== lock.manifestDigest ||
event.contentDigest !== lock.source.contentDigest)
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (event.type === 'activation_started' && record.state !== 'staged') {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'activation_committed' &&
(record.state !== 'activating' ||
event.intentDigest !== activationIntentDigest(lock, record) ||
event.generation !== lock.targetGeneration ||
event.contentDigest !== lock.source.contentDigest)
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'failed' &&
!['queued', 'staged', 'activating'].includes(record.state)
) {
throw new PluginPackageInstallTransitionConflictError();
}
let state: PluginPackageInstallState;
let stageReceipt = record.stageReceipt;
let activationReceipt = record.activationReceipt;
let failure = record.failure;
let activeLockDigest = record.activeLockDigest;
switch (event.type) {
case 'stage_completed':
state = 'staged';
stageReceipt = makeStageReceipt(event);
break;
case 'activation_started':
state = 'activating';
break;
case 'activation_committed':
state = 'active';
activationReceipt = makeActivationReceipt(event);
activeLockDigest = lock.lockDigest;
break;
case 'failed':
state = 'failed';
failure = Object.freeze({
reason: event.reason,
failedFrom: record.state as PluginPackageInstallFailure['failedFrom'],
failedAtMs: event.occurredAtMs,
});
break;
}
const { recordDigest: _previousRecordDigest, ...recordFields } = record;
return withRecordDigest({
...recordFields,
state,
version: record.version + 1,
lastMutationId: event.mutationId,
lastMutationDigest: mutationDigest,
stageReceipt,
activationReceipt,
failure,
activeLockDigest,
updatedAtMs: event.occurredAtMs,
});
}
export function pluginPackageInstallCommit(
previousValue: PluginPackageInstallRecord,
nextValue: PluginPackageInstallRecord,
): Readonly<PluginPackageInstallCommit> {
const previous = normalizePluginPackageInstallRecord(previousValue);
const next = normalizePluginPackageInstallRecord(nextValue);
const validNextStates: Readonly<
Record<PluginPackageInstallState, readonly PluginPackageInstallState[]>
> = {
queued: ['staged', 'failed'],
staged: ['activating', 'failed'],
activating: ['active', 'failed'],
active: [],
failed: [],
};
if (
next.installationId !== previous.installationId ||
next.version !== previous.version + 1 ||
next.createdAtMs !== previous.createdAtMs ||
next.projectId !== previous.projectId ||
next.packageName !== previous.packageName ||
next.packageVersion !== previous.packageVersion ||
next.operation !== previous.operation ||
next.lockDigest !== previous.lockDigest ||
next.targetGeneration !== previous.targetGeneration ||
next.previousActiveLockDigest !== previous.previousActiveLockDigest ||
!validNextStates[previous.state].includes(next.state)
) {
throw new PluginPackageInstallTransitionConflictError();
}
return Object.freeze({
installationId: next.installationId,
expectedVersion: previous.version,
expectedRecordDigest: previous.recordDigest,
mutationId: next.lastMutationId,
mutationDigest: next.lastMutationDigest,
record: next,
});
}
@@ -0,0 +1,615 @@
import {
InvalidPluginPackageInstallError,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallUnavailableError,
assertPluginPackageInstallMatchesLock,
normalizePluginPackageActivationReceipt,
normalizePluginPackageInstallRecord,
normalizePluginPackageLock,
pluginPackageActivationIntentDigest,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
type PluginPackageActivationReceipt,
type PluginPackageInstallRecord,
type PluginPackageInstallRepository,
type PluginPackageLock,
} from './pluginPackageInstall';
import {
createPluginPackageResourceGenerationFromReferences,
normalizePluginPackageResourceGeneration,
type PluginPackageResourceGeneration,
} from '../pluginPackageResourceGeneration';
export const PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA =
'qinglong/plugin-package-activation-intent@v2' as const;
export interface PluginPackageActivationIntent {
readonly schema: typeof PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly targetGeneration: number;
readonly previousActiveLockDigest: string | null;
readonly stageRef: string;
readonly stageReceiptDigest: string;
readonly stageEvidenceDigest: string;
readonly contentDigest: string;
readonly resourceGeneration: Readonly<PluginPackageResourceGeneration>;
readonly intentDigest: string;
}
export type PluginPackageActivationObservation =
| Readonly<{ status: 'not_published' }>
| Readonly<{
status: 'published';
receipt: Readonly<PluginPackageActivationReceipt>;
}>;
export interface PluginPackageActivationPublisher {
inspect(
intent: Readonly<PluginPackageActivationIntent>,
): Promise<Readonly<PluginPackageActivationObservation>>;
publish(
intent: Readonly<PluginPackageActivationIntent>,
): Promise<Readonly<PluginPackageActivationReceipt>>;
}
export interface ActivatePluginPackageOptions {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly activationStartedMutationId: string;
readonly activationCommittedMutationId: string;
readonly startedAtMs: number;
}
export interface InspectPluginPackageActivationOptions {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly activationCommittedMutationId: string;
readonly activationFailedMutationId: string;
readonly observedAtMs: number;
}
export class PluginPackageActivationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ACTIVATION_CONFLICT';
constructor() {
super('Plugin Package activation fact conflicts with durable intent');
this.name = 'PluginPackageActivationConflictError';
}
}
export class PluginPackageActivationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_ACTIVATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package activation authority is unavailable', options);
this.name = 'PluginPackageActivationUnavailableError';
}
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
throw new InvalidPluginPackageInstallError(
`${label} must contain enumerable data properties`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function normalizeIdentity(value: {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
}): Readonly<{
projectId: string;
packageName: string;
installationId: string;
}> {
const projectId = identifier(value.projectId, 'project id');
const packageName = value.packageName;
if (
typeof packageName !== 'string' ||
!PACKAGE_NAME_PATTERN.test(packageName)
) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({
projectId,
packageName,
installationId: identifier(value.installationId, 'installation id'),
});
}
export function createPluginPackageActivationIntent(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): Readonly<PluginPackageActivationIntent> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
const intentDigest = pluginPackageActivationIntentDigest(lock, record);
if (record.stageReceipt === null) {
throw new PluginPackageInstallTransitionConflictError();
}
const resourceGeneration =
createPluginPackageResourceGenerationFromReferences({
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
generation: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
contentDigest: lock.source.contentDigest,
resources: lock.resources,
});
return Object.freeze({
schema: PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA,
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
stageRef: record.stageReceipt.stageRef,
stageReceiptDigest: record.stageReceipt.receiptDigest,
stageEvidenceDigest: record.stageReceipt.evidenceDigest,
contentDigest: lock.source.contentDigest,
resourceGeneration,
intentDigest,
});
}
export function normalizePluginPackageActivationIntent(
value: unknown,
): Readonly<PluginPackageActivationIntent> {
const intent = dataRecord(value, 'activation intent');
exactKeys(
intent,
[
'schema',
'installationId',
'projectId',
'packageName',
'lockDigest',
'targetGeneration',
'previousActiveLockDigest',
'stageRef',
'stageReceiptDigest',
'stageEvidenceDigest',
'contentDigest',
'resourceGeneration',
'intentDigest',
],
'activation intent',
);
if (intent.schema !== PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA) {
throw new InvalidPluginPackageInstallError(
'activation intent schema is invalid',
);
}
const identity = normalizeIdentity({
projectId: intent.projectId as string,
packageName: intent.packageName as string,
installationId: intent.installationId as string,
});
const targetGeneration = timestamp(
intent.targetGeneration,
'activation target generation',
);
if (
targetGeneration < 1 ||
targetGeneration > MAX_PLUGIN_PACKAGE_INSTALL_VERSION
) {
throw new InvalidPluginPackageInstallError(
'activation target generation is invalid',
);
}
const previousActiveLockDigest =
intent.previousActiveLockDigest === null
? null
: digest(
intent.previousActiveLockDigest,
'activation previous lock digest',
);
const lockDigest = digest(intent.lockDigest, 'activation lock digest');
const contentDigest = digest(
intent.contentDigest,
'activation content digest',
);
const resourceGeneration = normalizePluginPackageResourceGeneration(
intent.resourceGeneration,
);
if (
resourceGeneration.installationId !== identity.installationId ||
resourceGeneration.projectId !== identity.projectId ||
resourceGeneration.packageName !== identity.packageName ||
resourceGeneration.lockDigest !== lockDigest ||
resourceGeneration.generation !== targetGeneration ||
resourceGeneration.previousActiveLockDigest !== previousActiveLockDigest ||
resourceGeneration.contentDigest !== contentDigest
) {
throw new InvalidPluginPackageInstallError(
'activation resource generation does not match its intent',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA,
...identity,
lockDigest,
targetGeneration,
previousActiveLockDigest,
stageRef: identifier(intent.stageRef, 'activation stage reference'),
stageReceiptDigest: digest(
intent.stageReceiptDigest,
'activation stage receipt digest',
),
stageEvidenceDigest: digest(
intent.stageEvidenceDigest,
'activation stage evidence digest',
),
contentDigest,
resourceGeneration,
intentDigest: digest(intent.intentDigest, 'activation intent digest'),
});
}
function normalizePublishedReceipt(
intent: Readonly<PluginPackageActivationIntent>,
value: PluginPackageActivationReceipt,
): Readonly<PluginPackageActivationReceipt> {
const receipt = normalizePluginPackageActivationReceipt(value);
if (
receipt.intentDigest !== intent.intentDigest ||
receipt.generation !== intent.targetGeneration ||
receipt.contentDigest !== intent.contentDigest
) {
throw new PluginPackageActivationConflictError();
}
return receipt;
}
function normalizeObservation(
intent: Readonly<PluginPackageActivationIntent>,
value: PluginPackageActivationObservation,
): Readonly<PluginPackageActivationObservation> {
const observation = dataRecord(value, 'activation observation');
if (observation.status === 'not_published') {
exactKeys(observation, ['status'], 'activation observation');
return Object.freeze({ status: 'not_published' });
}
if (observation.status === 'published') {
exactKeys(observation, ['status', 'receipt'], 'activation observation');
return Object.freeze({
status: 'published',
receipt: normalizePublishedReceipt(
intent,
(
value as Extract<
PluginPackageActivationObservation,
{ status: 'published' }
>
).receipt,
),
});
}
throw new InvalidPluginPackageInstallError(
'activation observation status is invalid',
);
}
function unavailable(error: unknown): PluginPackageActivationUnavailableError {
if (error instanceof PluginPackageActivationUnavailableError) return error;
return new PluginPackageActivationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
export class PluginPackageActivationCoordinator {
readonly #repository: PluginPackageInstallRepository;
readonly #publisher: PluginPackageActivationPublisher;
constructor(options: {
readonly repository: PluginPackageInstallRepository;
readonly publisher: PluginPackageActivationPublisher;
}) {
const value = dataRecord(options, 'activation coordinator options');
exactKeys(
value,
['repository', 'publisher'],
'activation coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.commit !== 'function' ||
!options.publisher ||
typeof options.publisher.inspect !== 'function' ||
typeof options.publisher.publish !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'activation coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#publisher = options.publisher;
}
async #load(
identity: Readonly<{
projectId: string;
packageName: string;
installationId: string;
}>,
): Promise<
Readonly<{
lock: Readonly<PluginPackageLock>;
record: Readonly<PluginPackageInstallRecord>;
}>
> {
const record = await this.#repository.find(
identity.projectId,
identity.packageName,
);
if (!record || record.installationId !== identity.installationId) {
throw new PluginPackageInstallTransitionConflictError();
}
const lock = await this.#repository.findLock(record.lockDigest);
if (!lock) throw new PluginPackageInstallUnavailableError();
assertPluginPackageInstallMatchesLock(lock, record);
return Object.freeze({ lock, record });
}
async #commitPublished(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
receipt: Readonly<PluginPackageActivationReceipt>,
mutationId: string,
): Promise<Readonly<PluginPackageInstallRecord>> {
const next = transitionPluginPackageInstall(lock, record, {
type: 'activation_committed',
mutationId,
occurredAtMs: receipt.activatedAtMs,
activationRef: receipt.activationRef,
intentDigest: receipt.intentDigest,
generation: receipt.generation,
contentDigest: receipt.contentDigest,
});
return (
await this.#repository.commit(pluginPackageInstallCommit(record, next))
).record;
}
async #commitFailure(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
mutationId: string,
occurredAtMs: number,
reason: 'activation_failed' | 'activation_fact_conflict',
): Promise<Readonly<PluginPackageInstallRecord>> {
const next = transitionPluginPackageInstall(lock, record, {
type: 'failed',
mutationId,
occurredAtMs,
reason,
});
return (
await this.#repository.commit(pluginPackageInstallCommit(record, next))
).record;
}
async activate(
options: ActivatePluginPackageOptions,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'activation options');
exactKeys(
value,
[
'projectId',
'packageName',
'installationId',
'activationStartedMutationId',
'activationCommittedMutationId',
'startedAtMs',
],
'activation options',
);
const identity = normalizeIdentity(options);
const activationStartedMutationId = identifier(
options.activationStartedMutationId,
'activation started mutation id',
);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const startedAtMs = timestamp(options.startedAtMs, 'activation start time');
const loaded = await this.#load(identity);
if (loaded.record.state !== 'staged') {
if (
loaded.record.state === 'active' ||
loaded.record.state === 'failed'
) {
return loaded.record;
}
throw new PluginPackageInstallTransitionConflictError();
}
const activating = transitionPluginPackageInstall(
loaded.lock,
loaded.record,
{
type: 'activation_started',
mutationId: activationStartedMutationId,
occurredAtMs: startedAtMs,
},
);
const durable = (
await this.#repository.commit(
pluginPackageInstallCommit(loaded.record, activating),
)
).record;
if (durable.state === 'active' || durable.state === 'failed')
return durable;
if (durable.state !== 'activating') {
throw new PluginPackageInstallTransitionConflictError();
}
const intent = createPluginPackageActivationIntent(loaded.lock, durable);
let receipt: Readonly<PluginPackageActivationReceipt>;
try {
receipt = normalizePublishedReceipt(
intent,
await this.#publisher.publish(intent),
);
} catch (error) {
if (error instanceof PluginPackageActivationConflictError) {
return this.#commitFailure(
loaded.lock,
durable,
activationCommittedMutationId,
startedAtMs,
'activation_fact_conflict',
);
}
throw unavailable(error);
}
return this.#commitPublished(
loaded.lock,
durable,
receipt,
activationCommittedMutationId,
);
}
async inspect(
options: InspectPluginPackageActivationOptions,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'activation inspection options');
exactKeys(
value,
[
'projectId',
'packageName',
'installationId',
'activationCommittedMutationId',
'activationFailedMutationId',
'observedAtMs',
],
'activation inspection options',
);
const identity = normalizeIdentity(options);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const activationFailedMutationId = identifier(
options.activationFailedMutationId,
'activation failed mutation id',
);
const observedAtMs = timestamp(options.observedAtMs, 'observation time');
const loaded = await this.#load(identity);
if (loaded.record.state === 'active' || loaded.record.state === 'failed') {
return loaded.record;
}
if (loaded.record.state !== 'activating') {
throw new PluginPackageInstallTransitionConflictError();
}
const intent = createPluginPackageActivationIntent(
loaded.lock,
loaded.record,
);
let observation: Readonly<PluginPackageActivationObservation>;
try {
observation = normalizeObservation(
intent,
await this.#publisher.inspect(intent),
);
} catch (error) {
if (error instanceof PluginPackageActivationConflictError) {
return this.#commitFailure(
loaded.lock,
loaded.record,
activationFailedMutationId,
observedAtMs,
'activation_fact_conflict',
);
}
throw unavailable(error);
}
if (observation.status === 'not_published') {
return this.#commitFailure(
loaded.lock,
loaded.record,
activationFailedMutationId,
observedAtMs,
'activation_failed',
);
}
return this.#commitPublished(
loaded.lock,
loaded.record,
observation.receipt,
activationCommittedMutationId,
);
}
}
@@ -0,0 +1,524 @@
import { createHash } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import {
approvedActionDispatchDigest,
normalizeApprovedActionDispatchRecord,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
normalizeApprovedActionExecutionRecord,
type ApprovedActionExecutionRecord,
} from '../../approved-action/approvedActionExecution';
import {
createPluginPackageInstall,
normalizePluginPackageInstallCreate,
normalizePluginPackageInstallRecord,
normalizePluginPackageLock,
pluginPackageInstallCreate,
type PluginPackageInstallCreate,
type PluginPackageInstallRecord,
type PluginPackageInstallRepository,
type PluginPackageLock,
} from './pluginPackageInstall';
import {
normalizePluginPackageInstallProposal,
resolvePluginPackageInstallProposal,
type PluginPackageInstallProposal,
} from '../pluginPackageProposal';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_INSTALL_ACTION_TYPE =
'plugin_package.install' as const;
export const PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA =
'qinglong/plugin-package-admission-receipt@v1' as const;
export const PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION =
'plugin_package.admit' as const;
export const PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON =
'approved_action' as const;
export interface PluginPackageAdmissionRequest {
readonly lock: PluginPackageLock;
readonly proposalDigest: string;
readonly execution: ApprovedActionExecutionRecord;
readonly installationId: string;
readonly mutationId: string;
readonly admittedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageAdmissionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA;
readonly dispatchId: string;
readonly dispatchDigest: string;
readonly approvalRequestId: string;
readonly actionRef: string;
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly recordDigest: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly auditEventId: string;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface BoundPluginPackageAdmission {
readonly create: Readonly<PluginPackageInstallCreate>;
readonly receipt: Readonly<PluginPackageAdmissionReceipt>;
}
export interface PluginPackageAdmissionResult {
readonly status: 'admitted' | 'existing';
readonly record: Readonly<PluginPackageInstallRecord>;
readonly receipt: Readonly<PluginPackageAdmissionReceipt>;
}
export interface PluginPackageAdmissionRepository
extends PluginPackageInstallRepository {
findAdmissionReceipt(
dispatchId: string,
): Promise<Readonly<PluginPackageAdmissionReceipt> | null>;
admit(
request: PluginPackageAdmissionRequest,
): Promise<Readonly<PluginPackageAdmissionResult>>;
}
export class InvalidPluginPackageAdmissionError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_INVALID';
constructor(message: string) {
super(`Plugin Package admission is invalid: ${message}`);
this.name = 'InvalidPluginPackageAdmissionError';
}
}
export class PluginPackageAdmissionBindingConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_BINDING_CONFLICT';
constructor() {
super('Plugin Package admission does not match its approved dispatch');
this.name = 'PluginPackageAdmissionBindingConflictError';
}
}
export class PluginPackageAdmissionReceiptConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_RECEIPT_CONFLICT';
constructor() {
super('Plugin Package admission conflicts with its durable receipt');
this.name = 'PluginPackageAdmissionReceiptConflictError';
}
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageAdmissionError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageAdmissionError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value;
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(
'approved action reference is invalid',
);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError('package name is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value as number;
}
function same(left: unknown, right: unknown): boolean {
return isDeepStrictEqual(left, right);
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function receiptWithoutDigest(
value: Omit<PluginPackageAdmissionReceipt, 'receiptDigest'>,
): Omit<PluginPackageAdmissionReceipt, 'receiptDigest'> {
return Object.freeze(value);
}
function withReceiptDigest(
value: Omit<PluginPackageAdmissionReceipt, 'receiptDigest'>,
): Readonly<PluginPackageAdmissionReceipt> {
const normalized = receiptWithoutDigest(value);
return Object.freeze({
...normalized,
receiptDigest: contractDigest(
'qinglong/plugin-package-admission-receipt-digest@v1',
normalized,
),
});
}
function assertAuditBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
audit: Readonly<SecurityAuditRecord>,
admittedAtMs: number,
): void {
if (
audit.requestId !== dispatch.id ||
audit.operationId !== PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION ||
audit.projectId !== dispatch.projectId ||
audit.subject?.type !== dispatch.consumedBy.type ||
audit.subject.id !== dispatch.consumedBy.id ||
audit.authenticationId === null ||
audit.outcome !== 'allowed' ||
!same(audit.reasons, [PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON]) ||
audit.fence?.projectVersion !== dispatch.approvalFence.projectVersion ||
audit.fence.bindingVersion !== dispatch.approvalFence.bindingVersion ||
audit.occurredAtMs !== admittedAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertDispatchBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
lock: Readonly<PluginPackageLock>,
admittedAtMs: number,
): void {
const approval = lock.approval;
if (
dispatch.id !== approval.dispatchId ||
dispatch.approvalRequestId !== approval.requestId ||
approval.requestVersion !== 3 ||
dispatch.projectId !== lock.projectId ||
dispatch.action.permission !== 'package.manage' ||
dispatch.action.actionType !== PLUGIN_PACKAGE_INSTALL_ACTION_TYPE ||
dispatch.action.actionDigest !== lock.actionDigest ||
dispatch.action.previewDigest !== lock.planDigest ||
dispatch.action.actionDigest !== approval.actionDigest ||
dispatch.action.previewDigest !== approval.previewDigest ||
dispatch.approvedBy.type !== approval.approvedBy.type ||
dispatch.approvedBy.id !== approval.approvedBy.id ||
dispatch.approvedAtMs !== approval.approvedAtMs ||
dispatch.expiresAtMs !== approval.expiresAtMs ||
dispatch.approvalFence.projectVersion !==
approval.fence.projectVersion ||
dispatch.approvalFence.bindingVersion !==
approval.fence.bindingVersion ||
admittedAtMs < dispatch.createdAtMs ||
admittedAtMs < lock.createdAtMs ||
admittedAtMs >= dispatch.expiresAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertProposalBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
proposalValue: PluginPackageInstallProposal,
request: Readonly<PluginPackageAdmissionRequest>,
): void {
const proposal = normalizePluginPackageInstallProposal(proposalValue);
let resolved: Readonly<PluginPackageLock>;
try {
resolved = resolvePluginPackageInstallProposal(
proposal,
dispatch,
request.lock.createdAtMs,
);
} catch {
throw new PluginPackageAdmissionBindingConflictError();
}
if (
proposal.proposalDigest !== request.proposalDigest ||
!same(resolved, request.lock)
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertExecutionBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
currentExecutionValue: ApprovedActionExecutionRecord,
request: Readonly<PluginPackageAdmissionRequest>,
observedAtMs: number,
): void {
const currentExecution = normalizeApprovedActionExecutionRecord(
currentExecutionValue,
);
const expectedExecution = request.execution;
if (
!same(currentExecution, expectedExecution) ||
currentExecution.dispatchId !== dispatch.id ||
currentExecution.dispatchDigest !== approvedActionDispatchDigest(dispatch) ||
currentExecution.projectId !== dispatch.projectId ||
currentExecution.status !== 'executing' ||
currentExecution.startedAtMs === null ||
currentExecution.leaseOwner === null ||
currentExecution.leaseToken === null ||
currentExecution.leaseExpiresAtMs === null ||
request.admittedAtMs < currentExecution.startedAtMs ||
request.admittedAtMs >= currentExecution.leaseExpiresAtMs ||
observedAtMs < currentExecution.startedAtMs ||
observedAtMs >= currentExecution.leaseExpiresAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
export function normalizePluginPackageAdmissionRequest(
value: PluginPackageAdmissionRequest,
): Readonly<PluginPackageAdmissionRequest> {
const request = dataRecord(value, 'request');
exactKeys(
request,
[
'lock',
'proposalDigest',
'execution',
'installationId',
'mutationId',
'admittedAtMs',
'audit',
],
'request',
);
const execution = normalizeApprovedActionExecutionRecord(value.execution);
if (execution.status !== 'executing') {
throw new InvalidPluginPackageAdmissionError(
'execution has not crossed the start barrier',
);
}
return Object.freeze({
lock: normalizePluginPackageLock(value.lock),
proposalDigest: digest(value.proposalDigest, 'proposal digest'),
execution,
installationId: identifier(value.installationId, 'installation id'),
mutationId: identifier(value.mutationId, 'mutation id'),
admittedAtMs: timestamp(value.admittedAtMs, 'admission time'),
audit: normalizeSecurityAuditRecord(value.audit),
});
}
export function bindPluginPackageAdmission(
dispatchValue: ApprovedActionDispatchRecord,
proposalValue: PluginPackageInstallProposal,
currentExecutionValue: ApprovedActionExecutionRecord,
requestValue: PluginPackageAdmissionRequest,
previousHeadValue: PluginPackageInstallRecord | null,
observedAtMsValue: number,
): Readonly<BoundPluginPackageAdmission> {
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const request = normalizePluginPackageAdmissionRequest(requestValue);
const observedAtMs = timestamp(observedAtMsValue, 'observed admission time');
const previousHead =
previousHeadValue === null
? null
: normalizePluginPackageInstallRecord(previousHeadValue);
assertDispatchBinding(dispatch, request.lock, request.admittedAtMs);
assertProposalBinding(dispatch, proposalValue, request);
assertExecutionBinding(
dispatch,
currentExecutionValue,
request,
observedAtMs,
);
assertAuditBinding(dispatch, request.audit, request.admittedAtMs);
const record = createPluginPackageInstall(request.lock, {
installationId: request.installationId,
mutationId: request.mutationId,
occurredAtMs: request.admittedAtMs,
});
const create = pluginPackageInstallCreate(
request.lock,
record,
previousHead,
);
return Object.freeze({
create,
receipt: withReceiptDigest({
schema: PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA,
dispatchId: dispatch.id,
dispatchDigest: approvedActionDispatchDigest(dispatch),
approvalRequestId: dispatch.approvalRequestId,
actionRef: dispatch.action.actionRef,
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
lockDigest: record.lockDigest,
recordDigest: record.recordDigest,
mutationId: create.mutationId,
mutationDigest: create.mutationDigest,
auditEventId: request.audit.eventId,
admittedAtMs: request.admittedAtMs,
}),
});
}
export function normalizePluginPackageAdmissionReceipt(
value: PluginPackageAdmissionReceipt,
): Readonly<PluginPackageAdmissionReceipt> {
const receipt = dataRecord(value, 'receipt');
exactKeys(
receipt,
[
'schema',
'dispatchId',
'dispatchDigest',
'approvalRequestId',
'actionRef',
'projectId',
'packageName',
'installationId',
'lockDigest',
'recordDigest',
'mutationId',
'mutationDigest',
'auditEventId',
'admittedAtMs',
'receiptDigest',
],
'receipt',
);
if (value.schema !== PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA) {
throw new InvalidPluginPackageAdmissionError(
'receipt schema is invalid',
);
}
const normalized = withReceiptDigest({
schema: PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA,
dispatchId: identifier(value.dispatchId, 'dispatch id'),
dispatchDigest: digest(value.dispatchDigest, 'dispatch digest'),
approvalRequestId: identifier(
value.approvalRequestId,
'approval request id',
),
actionRef: actionRef(value.actionRef),
projectId: identifier(value.projectId, 'project id'),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installation id'),
lockDigest: digest(value.lockDigest, 'lock digest'),
recordDigest: digest(value.recordDigest, 'record digest'),
mutationId: identifier(value.mutationId, 'mutation id'),
mutationDigest: digest(value.mutationDigest, 'mutation digest'),
auditEventId: identifier(value.auditEventId, 'audit event id'),
admittedAtMs: timestamp(value.admittedAtMs, 'admission time'),
});
if (normalized.receiptDigest !== value.receiptDigest) {
throw new InvalidPluginPackageAdmissionError(
'receipt digest does not match',
);
}
return normalized;
}
export function pluginPackageAdmissionReceiptDigest(
value: PluginPackageAdmissionReceipt,
): string {
return normalizePluginPackageAdmissionReceipt(value).receiptDigest;
}
export function assertPluginPackageAdmissionReplay(
dispatchValue: ApprovedActionDispatchRecord,
proposalValue: PluginPackageInstallProposal,
requestValue: PluginPackageAdmissionRequest,
receiptValue: PluginPackageAdmissionReceipt,
durableRecordValue: PluginPackageInstallRecord,
): void {
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const request = normalizePluginPackageAdmissionRequest(requestValue);
const receipt = normalizePluginPackageAdmissionReceipt(receiptValue);
const durableRecord = normalizePluginPackageInstallRecord(
durableRecordValue,
);
assertDispatchBinding(dispatch, request.lock, receipt.admittedAtMs);
assertProposalBinding(dispatch, proposalValue, request);
assertAuditBinding(dispatch, request.audit, receipt.admittedAtMs);
if (
receipt.dispatchId !== dispatch.id ||
receipt.dispatchDigest !== approvedActionDispatchDigest(dispatch) ||
receipt.approvalRequestId !== dispatch.approvalRequestId ||
receipt.actionRef !== dispatch.action.actionRef ||
receipt.projectId !== request.lock.projectId ||
receipt.packageName !== request.lock.packageName ||
receipt.installationId !== request.installationId ||
receipt.lockDigest !== request.lock.lockDigest ||
receipt.mutationId !== request.mutationId ||
receipt.auditEventId !== request.audit.eventId ||
receipt.admittedAtMs !== request.admittedAtMs ||
durableRecord.installationId !== receipt.installationId ||
durableRecord.projectId !== receipt.projectId ||
durableRecord.packageName !== receipt.packageName ||
durableRecord.lockDigest !== receipt.lockDigest ||
durableRecord.createdAtMs !== receipt.admittedAtMs
) {
throw new PluginPackageAdmissionReceiptConflictError();
}
const initial = createPluginPackageInstall(request.lock, {
installationId: request.installationId,
mutationId: request.mutationId,
occurredAtMs: request.admittedAtMs,
});
if (initial.recordDigest !== receipt.recordDigest) {
throw new PluginPackageAdmissionReceiptConflictError();
}
}
@@ -0,0 +1,32 @@
export * from './plugin-package-install/contracts';
export {
createPluginPackageLock,
normalizePluginPackageInstallActionInput,
normalizePluginPackageLock,
pluginPackageInstallActionDigest,
pluginPackageInstallPlanDigest,
pluginPackageManifestDigest,
serializePluginPackageManifest,
} from './plugin-package-install/lock';
export {
assertPluginPackageInstallMatchesLock,
createPluginPackageActivationReceipt,
createPluginPackageInstall,
normalizePluginPackageActivationReceipt,
normalizePluginPackageInstallRecord,
} from './plugin-package-install/record';
export {
pluginPackageActivationIntentDigest,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
} from './plugin-package-install/transition';
export {
assertPluginPackageInstallInventoryPageSize,
assertPluginPackageInstallRecoveryPageSize,
normalizePluginPackageInstallCreate,
normalizePluginPackageInstallInventoryCursor,
normalizePluginPackageInstallRecoveryCursor,
pluginPackageInstallCreate,
pluginPackageInstallRecoveryAction,
} from './plugin-package-install/repository';
@@ -0,0 +1,311 @@
import {
PluginPackageActivationCoordinator,
type PluginPackageActivationPublisher,
} from './pluginPackageActivation';
import {
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
normalizePluginPackageLock,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
type PluginPackageInstallRecord,
type PluginPackageLock,
} from './pluginPackageInstall';
import type { PluginPackageAdmissionRepository } from './pluginPackageAdmission';
import type { ApprovedActionExecutionRecord } from '../../approved-action/approvedActionExecution';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export interface PluginPackageStageEvidence {
readonly stageRef: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly evidenceDigest: string;
}
export interface PluginPackageStageProvider {
/**
* Produces or re-opens one exact content-addressed stage. A thrown
* availability error leaves the durable install queued for explicit retry.
*/
stage(
lock: Readonly<PluginPackageLock>,
): Promise<Readonly<PluginPackageStageEvidence>>;
}
export interface InstallPluginPackageOptions {
readonly lock: PluginPackageLock;
readonly proposalDigest: string;
readonly execution: ApprovedActionExecutionRecord;
readonly installationId: string;
readonly createMutationId: string;
readonly createdAtMs: number;
readonly stageMutationId: string;
readonly stagedAtMs: number;
readonly activationStartedMutationId: string;
readonly activationCommittedMutationId: string;
readonly activationFailedMutationId: string;
readonly activationStartedAtMs: number;
readonly activationObservedAtMs: number;
readonly admissionAudit: SecurityAuditRecord;
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function normalizeStageEvidence(
value: PluginPackageStageEvidence,
): Readonly<PluginPackageStageEvidence> {
const evidence = dataRecord(value, 'stage evidence');
exactKeys(
evidence,
[
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
],
'stage evidence',
);
const stageRef = identifier(value.stageRef, 'stage reference');
for (const [label, candidate] of [
['artifact digest', value.artifactDigest],
['manifest digest', value.manifestDigest],
['content digest', value.contentDigest],
['evidence digest', value.evidenceDigest],
] as const) {
if (typeof candidate !== 'string' || !DIGEST_PATTERN.test(candidate)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
}
return Object.freeze({
stageRef,
artifactDigest: value.artifactDigest,
manifestDigest: value.manifestDigest,
contentDigest: value.contentDigest,
evidenceDigest: value.evidenceDigest,
});
}
export function normalizePluginPackageStageEvidence(
value: PluginPackageStageEvidence,
): Readonly<PluginPackageStageEvidence> {
return normalizeStageEvidence(value);
}
export class PluginPackageInstallationCoordinator {
readonly #repository: PluginPackageAdmissionRepository;
readonly #activation: PluginPackageActivationCoordinator;
constructor(options: {
readonly repository: PluginPackageAdmissionRepository;
readonly publisher: PluginPackageActivationPublisher;
}) {
const value = dataRecord(options, 'installation coordinator options');
exactKeys(
value,
['repository', 'publisher'],
'installation coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.create !== 'function' ||
typeof options.repository.commit !== 'function' ||
typeof options.repository.admit !== 'function' ||
typeof options.repository.findAdmissionReceipt !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'installation coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#activation = new PluginPackageActivationCoordinator({
repository: options.repository,
publisher: options.publisher,
});
}
async #convergeActivation(
record: Readonly<PluginPackageInstallRecord>,
options: Readonly<{
activationStartedMutationId: string;
activationCommittedMutationId: string;
activationFailedMutationId: string;
activationStartedAtMs: number;
activationObservedAtMs: number;
}>,
): Promise<Readonly<PluginPackageInstallRecord>> {
const identity = {
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
};
if (record.state === 'staged') {
return this.#activation.activate({
...identity,
activationStartedMutationId: options.activationStartedMutationId,
activationCommittedMutationId: options.activationCommittedMutationId,
startedAtMs: options.activationStartedAtMs,
});
}
if (record.state === 'activating') {
return this.#activation.inspect({
...identity,
activationCommittedMutationId: options.activationCommittedMutationId,
activationFailedMutationId: options.activationFailedMutationId,
observedAtMs: options.activationObservedAtMs,
});
}
if (record.state === 'active' || record.state === 'failed') return record;
throw new PluginPackageInstallTransitionConflictError();
}
async install(
options: InstallPluginPackageOptions,
stageProvider: PluginPackageStageProvider,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'installation options');
exactKeys(
value,
[
'lock',
'proposalDigest',
'execution',
'installationId',
'createMutationId',
'createdAtMs',
'stageMutationId',
'stagedAtMs',
'activationStartedMutationId',
'activationCommittedMutationId',
'activationFailedMutationId',
'activationStartedAtMs',
'activationObservedAtMs',
'admissionAudit',
],
'installation options',
);
if (!stageProvider || typeof stageProvider.stage !== 'function') {
throw new InvalidPluginPackageInstallError('stage provider is invalid');
}
const lock = normalizePluginPackageLock(options.lock);
const installationId = identifier(
options.installationId,
'installation id',
);
const createMutationId = identifier(
options.createMutationId,
'create mutation id',
);
const stageMutationId = identifier(
options.stageMutationId,
'stage mutation id',
);
const activationStartedMutationId = identifier(
options.activationStartedMutationId,
'activation started mutation id',
);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const activationFailedMutationId = identifier(
options.activationFailedMutationId,
'activation failed mutation id',
);
const createdAtMs = timestamp(options.createdAtMs, 'creation time');
const stagedAtMs = timestamp(options.stagedAtMs, 'staged time');
const activationStartedAtMs = timestamp(
options.activationStartedAtMs,
'activation start time',
);
const activationObservedAtMs = timestamp(
options.activationObservedAtMs,
'activation observation time',
);
let record: Readonly<PluginPackageInstallRecord> = (
await this.#repository.admit({
lock,
proposalDigest: options.proposalDigest,
execution: options.execution,
installationId,
mutationId: createMutationId,
admittedAtMs: createdAtMs,
audit: options.admissionAudit,
})
).record;
if (record.state !== 'queued') {
return this.#convergeActivation(record, {
activationStartedMutationId,
activationCommittedMutationId,
activationFailedMutationId,
activationStartedAtMs,
activationObservedAtMs,
});
}
const evidence = normalizeStageEvidence(await stageProvider.stage(lock));
const staged = transitionPluginPackageInstall(lock, record, {
type: 'stage_completed',
mutationId: stageMutationId,
occurredAtMs: stagedAtMs,
...evidence,
});
record = (
await this.#repository.commit(pluginPackageInstallCommit(record, staged))
).record;
return this.#convergeActivation(record, {
activationStartedMutationId,
activationCommittedMutationId,
activationFailedMutationId,
activationStartedAtMs,
activationObservedAtMs,
});
}
}
@@ -0,0 +1,523 @@
import { createHash } from 'node:crypto';
import {
PluginPackageActivationCoordinator,
PluginPackageActivationUnavailableError,
type PluginPackageActivationPublisher,
} from './pluginPackageActivation';
import {
InvalidPluginPackageInstallError,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
PluginPackageInstallMutationConflictError,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallUnavailableError,
assertPluginPackageInstallMatchesLock,
assertPluginPackageInstallRecoveryPageSize,
normalizePluginPackageInstallRecord,
normalizePluginPackageInstallRecoveryCursor,
pluginPackageInstallCommit,
pluginPackageInstallRecoveryAction,
transitionPluginPackageInstall,
type PluginPackageInstallRecord,
type PluginPackageInstallRecoveryAction,
type PluginPackageInstallRecoveryCursor,
type PluginPackageInstallRecoveryPage,
type PluginPackageInstallRepository,
} from './pluginPackageInstall';
import {
normalizePluginPackageStageEvidence,
type PluginPackageStageProvider,
} from './pluginPackageInstallation';
/** Bounds one recovery cycle independently of the deployment profile. */
export const MAX_PLUGIN_PACKAGE_RECOVERY_PAGES = 64;
export const PLUGIN_PACKAGE_RECOVERY_ITEM_STATUSES = [
'settled',
'retry',
'manual_required',
'superseded',
] as const;
export type PluginPackageRecoveryItemStatus =
(typeof PLUGIN_PACKAGE_RECOVERY_ITEM_STATUSES)[number];
export interface PluginPackageRecoveryItemResult {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly action: Exclude<PluginPackageInstallRecoveryAction, 'none'>;
readonly status: PluginPackageRecoveryItemStatus;
readonly state: PluginPackageInstallRecord['state'];
}
export interface PluginPackageRecoveryPageResult {
readonly items: readonly Readonly<PluginPackageRecoveryItemResult>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallRecoveryCursor>;
}
export interface PluginPackageRecoveryCycleResult {
readonly pages: number;
readonly scanned: number;
readonly settled: number;
readonly retry: number;
readonly manualRequired: number;
readonly superseded: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
const RECOVERABLE_STATES = new Set(['queued', 'staged', 'activating']);
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
throw new InvalidPluginPackageInstallError(
`${label} must contain enumerable data properties`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const actual = Object.keys(value);
if (
required.some((key) => !actual.includes(key)) ||
actual.some((key) => !required.includes(key) && !optional.includes(key))
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function positiveInteger(
value: unknown,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new PluginPackageInstallUnavailableError();
}
return value as number;
}
function compareRecords(
left: Readonly<PluginPackageInstallRecord>,
right: Readonly<PluginPackageInstallRecord>,
): number {
return (
left.packageName.localeCompare(right.packageName) ||
left.installationId.localeCompare(right.installationId)
);
}
function normalizePage(
value: PluginPackageInstallRecoveryPage,
limit: number,
): Readonly<PluginPackageInstallRecoveryPage> {
const page = dataRecord(value, 'recovery page');
exactKeys(page, ['records', 'truncated'], ['next'], 'recovery page');
if (
!Array.isArray(value.records) ||
value.records.length > limit ||
typeof value.truncated !== 'boolean'
) {
throw new InvalidPluginPackageInstallError('recovery page is invalid');
}
const records = Object.freeze(
value.records.map((record) => normalizePluginPackageInstallRecord(record)),
);
if (
records.some((record) => !RECOVERABLE_STATES.has(record.state)) ||
records.some(
(record, index) =>
index > 0 && compareRecords(records[index - 1]!, record) >= 0,
)
) {
throw new InvalidPluginPackageInstallError(
'recovery page records are invalid',
);
}
const next =
value.next === undefined
? undefined
: normalizePluginPackageInstallRecoveryCursor(value.next);
const last = records.at(-1);
if (
value.truncated !== (next !== undefined) ||
(next &&
(!last ||
next.packageName !== last.packageName ||
next.installationId !== last.installationId))
) {
throw new InvalidPluginPackageInstallError(
'recovery page continuation is invalid',
);
}
return Object.freeze({
records,
truncated: value.truncated,
...(next ? { next } : {}),
});
}
function mutationId(
kind: string,
record: Readonly<PluginPackageInstallRecord>,
occurredAtMs: number,
): string {
const digest = createHash('sha256')
.update('qinglong/plugin-package-recovery-mutation@v1\0', 'utf8')
.update(
JSON.stringify({
kind,
installationId: record.installationId,
version: record.version,
recordDigest: record.recordDigest,
occurredAtMs,
}),
'utf8',
)
.digest('hex');
return `recovery-${kind}:${digest}`;
}
function result(
source: Readonly<PluginPackageInstallRecord>,
action: Exclude<PluginPackageInstallRecoveryAction, 'none'>,
status: PluginPackageRecoveryItemStatus,
current: Readonly<PluginPackageInstallRecord> = source,
): Readonly<PluginPackageRecoveryItemResult> {
return Object.freeze({
projectId: source.projectId,
packageName: source.packageName,
installationId: source.installationId,
action,
status,
state: current.state,
});
}
export class PluginPackageRecoveryCoordinator {
readonly #repository: PluginPackageInstallRepository;
readonly #stageProvider: PluginPackageStageProvider;
readonly #activation: PluginPackageActivationCoordinator;
readonly #now: () => number | Promise<number>;
constructor(options: {
readonly repository: PluginPackageInstallRepository;
readonly stageProvider: PluginPackageStageProvider;
readonly publisher: PluginPackageActivationPublisher;
readonly now: () => number | Promise<number>;
}) {
const value = dataRecord(options, 'recovery coordinator options');
exactKeys(
value,
['repository', 'stageProvider', 'publisher', 'now'],
[],
'recovery coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.commit !== 'function' ||
typeof options.repository.listRecoveryPage !== 'function' ||
!options.stageProvider ||
typeof options.stageProvider.stage !== 'function' ||
typeof options.now !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'recovery coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#stageProvider = options.stageProvider;
this.#activation = new PluginPackageActivationCoordinator({
repository: options.repository,
publisher: options.publisher,
});
this.#now = options.now;
}
async #current(
source: Readonly<PluginPackageInstallRecord>,
): Promise<Readonly<PluginPackageInstallRecord> | null> {
const record = await this.#repository.find(
source.projectId,
source.packageName,
);
return record ? normalizePluginPackageInstallRecord(record) : null;
}
async #convergeActivation(
record: Readonly<PluginPackageInstallRecord>,
occurredAtMs: number,
): Promise<Readonly<PluginPackageInstallRecord>> {
const identity = {
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
};
if (record.state === 'staged') {
return this.#activation.activate({
...identity,
activationStartedMutationId: mutationId(
'activation-start',
record,
occurredAtMs,
),
activationCommittedMutationId: mutationId(
'activation-commit',
record,
occurredAtMs,
),
startedAtMs: occurredAtMs,
});
}
if (record.state === 'activating') {
return this.#activation.inspect({
...identity,
activationCommittedMutationId: mutationId(
'activation-observed',
record,
occurredAtMs,
),
activationFailedMutationId: mutationId(
'activation-failed',
record,
occurredAtMs,
),
observedAtMs: occurredAtMs,
});
}
return record;
}
async #recoverRecord(
sourceValue: Readonly<PluginPackageInstallRecord>,
): Promise<Readonly<PluginPackageRecoveryItemResult>> {
const source = normalizePluginPackageInstallRecord(sourceValue);
const action = pluginPackageInstallRecoveryAction(source);
if (action === 'none') {
throw new InvalidPluginPackageInstallError(
'terminal record appeared in recovery page',
);
}
let current = source;
try {
const occurredAtMs = timestamp(await this.#now());
if (source.state === 'queued') {
const lock = await this.#repository.findLock(source.lockDigest);
if (!lock) throw new PluginPackageInstallUnavailableError();
assertPluginPackageInstallMatchesLock(lock, source);
const evidence = normalizePluginPackageStageEvidence(
await this.#stageProvider.stage(lock),
);
const staged = transitionPluginPackageInstall(lock, source, {
type: 'stage_completed',
mutationId: mutationId('stage', source, occurredAtMs),
occurredAtMs,
...evidence,
});
const committed = normalizePluginPackageInstallRecord(
(
await this.#repository.commit(
pluginPackageInstallCommit(source, staged),
)
).record,
);
if (committed.installationId !== source.installationId) {
return result(source, action, 'superseded', committed);
}
if (committed.state === 'active' || committed.state === 'failed') {
return result(source, action, 'settled', committed);
}
if (
committed.state !== 'staged' ||
committed.recordDigest !== staged.recordDigest
) {
return result(source, action, 'retry', committed);
}
current = committed;
}
current = await this.#convergeActivation(current, occurredAtMs);
if (current.state === 'active' || current.state === 'failed') {
return result(source, action, 'settled', current);
}
return result(source, action, 'retry', current);
} catch (error) {
if (
error instanceof InvalidPluginPackageInstallError ||
error instanceof PluginPackageInstallMutationConflictError
) {
return result(source, action, 'manual_required', current);
}
if (error instanceof PluginPackageInstallTransitionConflictError) {
try {
const durable = await this.#current(source);
if (!durable || durable.installationId !== source.installationId) {
return result(source, action, 'superseded');
}
if (durable.state === 'active' || durable.state === 'failed') {
return result(source, action, 'settled', durable);
}
if (durable.recordDigest !== source.recordDigest) {
return result(source, action, 'retry', durable);
}
} catch {
return result(source, action, 'retry', current);
}
return result(source, action, 'manual_required', current);
}
if (
error instanceof PluginPackageInstallUnavailableError ||
error instanceof PluginPackageActivationUnavailableError
) {
try {
const durable = await this.#current(source);
if (!durable || durable.installationId !== source.installationId) {
return result(source, action, 'superseded');
}
if (durable.state === 'active' || durable.state === 'failed') {
return result(source, action, 'settled', durable);
}
return result(source, action, 'retry', durable);
} catch {
return result(source, action, 'retry', current);
}
}
return result(source, action, 'retry', current);
}
}
async recoverPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallRecoveryCursor>;
}): Promise<Readonly<PluginPackageRecoveryPageResult>> {
const value = dataRecord(options, 'recovery page options');
exactKeys(value, ['limit'], ['after'], 'recovery page options');
assertPluginPackageInstallRecoveryPageSize(options.limit);
const after =
options.after === undefined
? undefined
: normalizePluginPackageInstallRecoveryCursor(options.after);
const page = normalizePage(
await this.#repository.listRecoveryPage({
limit: options.limit,
...(after ? { after } : {}),
}),
options.limit,
);
const items: Readonly<PluginPackageRecoveryItemResult>[] = [];
for (const record of page.records) {
items.push(await this.#recoverRecord(record));
}
return Object.freeze({
items: Object.freeze(items),
truncated: page.truncated,
...(page.next ? { next: page.next } : {}),
});
}
async recover(
options: {
readonly pageSize?: number;
readonly maxPages?: number;
} = {},
): Promise<Readonly<PluginPackageRecoveryCycleResult>> {
const value = dataRecord(options, 'recovery cycle options');
exactKeys(value, [], ['pageSize', 'maxPages'], 'recovery cycle options');
const pageSize = positiveInteger(
options.pageSize ?? 16,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
'recovery page size',
);
const maxPages = positiveInteger(
options.maxPages ?? 16,
MAX_PLUGIN_PACKAGE_RECOVERY_PAGES,
'recovery page count',
);
const counts = {
pages: 0,
scanned: 0,
settled: 0,
retry: 0,
manualRequired: 0,
superseded: 0,
};
let after: Readonly<PluginPackageInstallRecoveryCursor> | undefined;
let exhausted = false;
while (counts.pages < maxPages) {
const page = await this.recoverPage({
limit: pageSize,
...(after ? { after } : {}),
});
counts.pages += 1;
counts.scanned += page.items.length;
for (const item of page.items) {
switch (item.status) {
case 'settled':
counts.settled += 1;
break;
case 'retry':
counts.retry += 1;
break;
case 'manual_required':
counts.manualRequired += 1;
break;
case 'superseded':
counts.superseded += 1;
break;
}
}
if (!page.truncated) {
exhausted = true;
break;
}
after = page.next;
}
const probe = normalizePage(
await this.#repository.listRecoveryPage({ limit: 1 }),
1,
);
const remaining = !exhausted || probe.records.length > 0;
return Object.freeze({
...counts,
remaining,
safeToAdmit: !remaining && counts.manualRequired === 0,
});
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,268 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageLifecycleImpact,
type PluginPackageLifecycleImpact,
} from './pluginPackageLifecycle';
import type { SecuritySubject } from '../../security/security';
export const PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA =
'qinglong/plugin-package-lifecycle-plan@v1' as const;
export const MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_LIFETIME_MS = 15 * 60 * 1000;
export const MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_BYTES = 96 * 1024;
export interface PluginPackageLifecyclePlan {
readonly schema: typeof PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA;
readonly actionRef: string;
readonly impact: Readonly<PluginPackageLifecycleImpact>;
readonly requestedBy: Readonly<SecuritySubject>;
readonly plannedAtMs: number;
readonly expiresAtMs: number;
readonly planDigest: string;
}
export interface CreatePluginPackageLifecyclePlanInput {
readonly actionRef: string;
readonly impact: PluginPackageLifecycleImpact;
readonly requestedBy: SecuritySubject;
readonly plannedAtMs: number;
readonly expiresAtMs: number;
}
export interface CreatePluginPackageLifecyclePlanResult {
readonly status: 'created' | 'existing';
readonly plan: Readonly<PluginPackageLifecyclePlan>;
}
export interface PluginPackageLifecyclePlanRepository {
create(
plan: Readonly<PluginPackageLifecyclePlan>,
): Promise<Readonly<CreatePluginPackageLifecyclePlanResult>>;
findByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackageLifecyclePlan> | null>;
}
export class InvalidPluginPackageLifecyclePlanError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_INVALID';
constructor(message: string) {
super(`Plugin Package lifecycle plan is invalid: ${message}`);
this.name = 'InvalidPluginPackageLifecyclePlanError';
}
}
export class PluginPackageLifecyclePlanConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_CONFLICT';
constructor(message: string) {
super(
`Plugin Package lifecycle plan conflicts with durable state: ${message}`,
);
this.name = 'PluginPackageLifecyclePlanConflictError';
}
}
export class PluginPackageLifecyclePlanUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package lifecycle plan is unavailable', options);
this.name = 'PluginPackageLifecyclePlanUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PLAN_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const PLAN_DIGEST_DOMAIN =
'qinglong/plugin-package-lifecycle-plan-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackageLifecyclePlanError(message);
}
function record(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
keys.some((key) => typeof key !== 'string') ||
keys.length !== canonical.length ||
keys
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function userSubject(value: SecuritySubject): Readonly<SecuritySubject> {
const candidate = record(value, 'requestedBy');
exactKeys(candidate, ['id', 'type'], 'requestedBy');
if (
value.type !== 'user' ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid('requestedBy must be a User subject');
}
return Object.freeze({ type: 'user', id: value.id });
}
function fields(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): object {
return {
schema: value.schema,
actionRef: value.actionRef,
impact: value.impact,
requestedBy: value.requestedBy,
plannedAtMs: value.plannedAtMs,
expiresAtMs: value.expiresAtMs,
};
}
export function pluginPackageLifecyclePlanDigest(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): string {
return createHash('sha256')
.update(PLAN_DIGEST_DOMAIN)
.update(JSON.stringify(fields(value)))
.digest('hex');
}
function normalizedWithoutDigest(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): Omit<PluginPackageLifecyclePlan, 'planDigest'> {
if (value.schema !== PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA) {
return invalid('schema is invalid');
}
const plannedAtMs = timestamp(value.plannedAtMs, 'plannedAtMs');
const expiresAtMs = timestamp(value.expiresAtMs, 'expiresAtMs');
if (
expiresAtMs <= plannedAtMs ||
expiresAtMs - plannedAtMs >
MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_LIFETIME_MS
) {
return invalid('lifetime is invalid');
}
return Object.freeze({
schema: PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA,
actionRef: actionRef(value.actionRef),
impact: normalizePluginPackageLifecycleImpact(value.impact),
requestedBy: userSubject(value.requestedBy),
plannedAtMs,
expiresAtMs,
});
}
function boundedPlan(
value: Readonly<PluginPackageLifecyclePlan>,
): Readonly<PluginPackageLifecyclePlan> {
if (
Buffer.byteLength(JSON.stringify(value), 'utf8') >
MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_BYTES
) {
return invalid('encoded plan exceeds the size limit');
}
return value;
}
export function createPluginPackageLifecyclePlan(
input: CreatePluginPackageLifecyclePlanInput,
): Readonly<PluginPackageLifecyclePlan> {
const value = record(input, 'lifecycle plan input');
exactKeys(
value,
['actionRef', 'expiresAtMs', 'impact', 'plannedAtMs', 'requestedBy'],
'lifecycle plan input',
);
const unsigned = normalizedWithoutDigest({
schema: PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA,
actionRef: input.actionRef,
impact: input.impact,
requestedBy: input.requestedBy,
plannedAtMs: input.plannedAtMs,
expiresAtMs: input.expiresAtMs,
});
return boundedPlan(
Object.freeze({
...unsigned,
planDigest: pluginPackageLifecyclePlanDigest(unsigned),
}),
);
}
export function normalizePluginPackageLifecyclePlan(
value: PluginPackageLifecyclePlan,
): Readonly<PluginPackageLifecyclePlan> {
const candidate = record(value, 'lifecycle plan');
exactKeys(
candidate,
[
'actionRef',
'expiresAtMs',
'impact',
'planDigest',
'plannedAtMs',
'requestedBy',
'schema',
],
'lifecycle plan',
);
const unsigned = normalizedWithoutDigest(value);
const planDigest = pluginPackageLifecyclePlanDigest(unsigned);
if (
typeof value.planDigest !== 'string' ||
!PLAN_DIGEST_PATTERN.test(value.planDigest) ||
value.planDigest !== planDigest
) {
return invalid('planDigest does not match lifecycle plan');
}
return boundedPlan(Object.freeze({ ...unsigned, planDigest }));
}
@@ -0,0 +1,709 @@
import { createHash } from 'node:crypto';
import { SECURITY_SUBJECT_TYPES, type SecuritySubject } from '../../security/security';
export const PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA =
'qinglong/plugin-package-quarantine-event@v1' as const;
export const PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA =
'qinglong/plugin-package-withdrawal-receipt@v1' as const;
export const MAX_PLUGIN_PACKAGE_QUARANTINE_TASK_WITHDRAWALS = 128;
export const MAX_PLUGIN_PACKAGE_QUARANTINE_RETAINED_SOURCES = 128;
export type PluginPackageQuarantineInstallState =
| 'queued'
| 'staged'
| 'activating'
| 'active';
export type PluginPackageQuarantineAuthorizationMode =
| 'dual_control'
| 'break_glass';
export type PluginPackageQuarantineReason =
| 'suspected_key_compromise'
| 'confirmed_key_compromise';
export interface PluginPackageQuarantineTarget {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly installState: PluginPackageQuarantineInstallState;
readonly installVersion: number;
readonly installRecordDigest: string;
readonly activeLockDigest: string | null;
}
export interface PluginPackageQuarantineEvent {
readonly schema: typeof PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA;
readonly mutationId: string;
readonly revocationReceiptDigest: string;
readonly impactDigest: string;
readonly target: Readonly<PluginPackageQuarantineTarget>;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly authorizationMode: PluginPackageQuarantineAuthorizationMode;
readonly reasonCode: PluginPackageQuarantineReason;
readonly occurredAtMs: number;
readonly eventDigest: string;
}
export type CreatePluginPackageQuarantineEventInput = Omit<
PluginPackageQuarantineEvent,
'eventDigest' | 'schema'
>;
export interface PluginPackageQuarantineTaskWithdrawal {
readonly taskId: string;
readonly previousRevision: number;
readonly disabledRevision: number;
readonly previousContentDigest: string;
readonly disabledContentDigest: string;
}
export interface PluginPackageQuarantineInactiveCapabilityDisposition {
readonly status: 'not_active';
readonly taskWithdrawals: readonly [];
readonly previousActiveVectorDigest: null;
readonly currentActiveVectorDigest: null;
readonly currentToolSnapshotDigest: null;
readonly retainedSourceCount: 0;
}
export interface PluginPackageQuarantineWithdrawnCapabilityDisposition {
readonly status: 'withdrawn';
readonly taskWithdrawals: readonly Readonly<PluginPackageQuarantineTaskWithdrawal>[];
readonly previousActiveVectorDigest: string;
readonly currentActiveVectorDigest: string;
readonly currentToolSnapshotDigest: string;
readonly retainedSourceCount: number;
}
export type PluginPackageQuarantineCapabilityDisposition =
| Readonly<PluginPackageQuarantineInactiveCapabilityDisposition>
| Readonly<PluginPackageQuarantineWithdrawnCapabilityDisposition>;
export interface PluginPackageWithdrawalReceipt {
readonly schema: typeof PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA;
readonly eventDigest: string;
readonly target: Readonly<PluginPackageQuarantineTarget>;
readonly capability: PluginPackageQuarantineCapabilityDisposition;
readonly committedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackageWithdrawalReceiptInput = Omit<
PluginPackageWithdrawalReceipt,
'receiptDigest' | 'schema'
>;
export interface PluginPackageQuarantineRepository {
findTargetsByLockDigest(
lockDigest: string,
): Promise<readonly Readonly<PluginPackageQuarantineTarget>[]>;
findByEventDigest(
eventDigest: string,
): Promise<Readonly<PluginPackageWithdrawalReceipt> | null>;
quarantine(
event: Readonly<PluginPackageQuarantineEvent>,
confirmAuthorization: () => void | Promise<void>,
): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWithdrawalReceipt>;
}>
>;
}
export class InvalidPluginPackageQuarantineError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_INVALID';
constructor(message: string) {
super(`Plugin Package quarantine is invalid: ${message}`);
this.name = 'InvalidPluginPackageQuarantineError';
}
}
export class PluginPackageQuarantineConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_CONFLICT';
constructor(message: string) {
super(`Plugin Package quarantine conflicts with durable state: ${message}`);
this.name = 'PluginPackageQuarantineConflictError';
}
}
export class PluginPackageQuarantineUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package quarantine is unavailable', options);
this.name = 'PluginPackageQuarantineUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const EVENT_DIGEST_DOMAIN =
'qinglong/plugin-package-quarantine-event-digest@v1\0';
const RECEIPT_DIGEST_DOMAIN =
'qinglong/plugin-package-withdrawal-receipt-digest@v1\0';
const TASK_MUTATION_ID_DOMAIN =
'qinglong/plugin-package-quarantine-task-mutation-id@v1\0';
const QUARANTINE_MUTATION_ID_DOMAIN =
'qinglong/plugin-package-quarantine-mutation-id@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackageQuarantineError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const sorted = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== sorted.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== sorted[index])
) {
invalid(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveVersion(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function subject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const record = dataRecord(value, label);
exactKeys(record, ['id', 'type'], label);
if (
typeof value.type !== 'string' ||
!SECURITY_SUBJECT_TYPES.includes(
value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
) ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid(`${label} is invalid`);
}
return Object.freeze({
type: value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
id: value.id,
});
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function normalizeTarget(
value: PluginPackageQuarantineTarget,
): Readonly<PluginPackageQuarantineTarget> {
const target = dataRecord(value, 'target');
exactKeys(
target,
[
'activeLockDigest',
'installationId',
'installRecordDigest',
'installState',
'installVersion',
'lockDigest',
'packageName',
'projectId',
],
'target',
);
if (
typeof value.projectId !== 'string' ||
value.projectId.length < 1 ||
Buffer.byteLength(value.projectId, 'utf8') > 128 ||
value.projectId.includes('\0') ||
typeof value.packageName !== 'string' ||
!PACKAGE_NAME_PATTERN.test(value.packageName) ||
!['queued', 'staged', 'activating', 'active'].includes(value.installState)
) {
return invalid('target identity or state is invalid');
}
const lockDigest = digest(value.lockDigest, 'target lockDigest');
const activeLockDigest =
value.activeLockDigest === null
? null
: digest(value.activeLockDigest, 'target activeLockDigest');
if (
(value.installState === 'active' && activeLockDigest !== lockDigest) ||
(value.installState !== 'active' && activeLockDigest === lockDigest)
) {
return invalid('target active lock does not match install state');
}
return Object.freeze({
projectId: value.projectId,
packageName: value.packageName,
installationId: identifier(value.installationId, 'target installationId'),
lockDigest,
installState: value.installState,
installVersion: positiveVersion(
value.installVersion,
'target installVersion',
),
installRecordDigest: digest(
value.installRecordDigest,
'target installRecordDigest',
),
activeLockDigest,
});
}
function eventFields(
value: Omit<PluginPackageQuarantineEvent, 'eventDigest'>,
): object {
return {
schema: value.schema,
mutationId: value.mutationId,
revocationReceiptDigest: value.revocationReceiptDigest,
impactDigest: value.impactDigest,
target: value.target,
proposer: value.proposer,
confirmer: value.confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
occurredAtMs: value.occurredAtMs,
};
}
export function pluginPackageQuarantineEventDigest(
value: Omit<PluginPackageQuarantineEvent, 'eventDigest'>,
): string {
return createHash('sha256')
.update(EVENT_DIGEST_DOMAIN)
.update(JSON.stringify(eventFields(value)))
.digest('hex');
}
export function normalizePluginPackageQuarantineEvent(
value: PluginPackageQuarantineEvent,
): Readonly<PluginPackageQuarantineEvent> {
const event = dataRecord(value, 'event');
exactKeys(
event,
[
'authorizationMode',
'confirmer',
'eventDigest',
'impactDigest',
'mutationId',
'occurredAtMs',
'proposer',
'reasonCode',
'revocationReceiptDigest',
'schema',
'target',
],
'event',
);
if (
value.schema !== PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA ||
(value.authorizationMode !== 'dual_control' &&
value.authorizationMode !== 'break_glass') ||
(value.reasonCode !== 'suspected_key_compromise' &&
value.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('event schema or classification is invalid');
}
const proposer = subject(value.proposer, 'proposer');
const confirmer = subject(value.confirmer, 'confirmer');
if (
value.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
revocationReceiptDigest: digest(
value.revocationReceiptDigest,
'revocationReceiptDigest',
),
impactDigest: digest(value.impactDigest, 'impactDigest'),
target: normalizeTarget(value.target),
proposer,
confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
occurredAtMs: timestamp(value.occurredAtMs, 'occurredAtMs'),
});
const eventDigest = pluginPackageQuarantineEventDigest(normalized);
if (value.eventDigest !== eventDigest) {
return invalid('eventDigest does not match event');
}
return Object.freeze({ ...normalized, eventDigest });
}
export function createPluginPackageQuarantineEvent(
input: CreatePluginPackageQuarantineEventInput,
): Readonly<PluginPackageQuarantineEvent> {
const value = dataRecord(input, 'event input');
exactKeys(
value,
[
'authorizationMode',
'confirmer',
'impactDigest',
'mutationId',
'occurredAtMs',
'proposer',
'reasonCode',
'revocationReceiptDigest',
'target',
],
'event input',
);
if (
(input.authorizationMode !== 'dual_control' &&
input.authorizationMode !== 'break_glass') ||
(input.reasonCode !== 'suspected_key_compromise' &&
input.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('event classification is invalid');
}
const proposer = subject(input.proposer, 'proposer');
const confirmer = subject(input.confirmer, 'confirmer');
if (
input.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const unsigned: Omit<PluginPackageQuarantineEvent, 'eventDigest'> = {
schema: PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA,
mutationId: identifier(input.mutationId, 'mutationId'),
revocationReceiptDigest: digest(
input.revocationReceiptDigest,
'revocationReceiptDigest',
),
impactDigest: digest(input.impactDigest, 'impactDigest'),
target: normalizeTarget(input.target),
proposer,
confirmer,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
occurredAtMs: timestamp(input.occurredAtMs, 'occurredAtMs'),
};
return normalizePluginPackageQuarantineEvent({
...unsigned,
eventDigest: pluginPackageQuarantineEventDigest(unsigned),
});
}
function normalizeTaskWithdrawal(
value: PluginPackageQuarantineTaskWithdrawal,
): Readonly<PluginPackageQuarantineTaskWithdrawal> {
const task = dataRecord(value, 'task withdrawal');
exactKeys(
task,
[
'disabledContentDigest',
'disabledRevision',
'previousContentDigest',
'previousRevision',
'taskId',
],
'task withdrawal',
);
const previousRevision = positiveVersion(
value.previousRevision,
'task previousRevision',
);
const disabledRevision = positiveVersion(
value.disabledRevision,
'task disabledRevision',
);
if (disabledRevision !== previousRevision + 1) {
return invalid('task disabled revision is not consecutive');
}
return Object.freeze({
taskId: identifier(value.taskId, 'taskId'),
previousRevision,
disabledRevision,
previousContentDigest: digest(
value.previousContentDigest,
'task previousContentDigest',
),
disabledContentDigest: digest(
value.disabledContentDigest,
'task disabledContentDigest',
),
});
}
function normalizeCapability(
value: PluginPackageQuarantineCapabilityDisposition,
target: Readonly<PluginPackageQuarantineTarget>,
): PluginPackageQuarantineCapabilityDisposition {
const capability = dataRecord(value, 'capability');
exactKeys(
capability,
[
'currentActiveVectorDigest',
'currentToolSnapshotDigest',
'previousActiveVectorDigest',
'retainedSourceCount',
'status',
'taskWithdrawals',
],
'capability',
);
if (!Array.isArray(value.taskWithdrawals)) {
return invalid('task withdrawals must be an array');
}
if (value.status === 'not_active') {
if (
target.installState === 'active' ||
value.taskWithdrawals.length !== 0 ||
value.previousActiveVectorDigest !== null ||
value.currentActiveVectorDigest !== null ||
value.currentToolSnapshotDigest !== null ||
value.retainedSourceCount !== 0
) {
return invalid('inactive capability disposition is inconsistent');
}
return Object.freeze({
status: 'not_active',
taskWithdrawals: Object.freeze([]) as readonly [],
previousActiveVectorDigest: null,
currentActiveVectorDigest: null,
currentToolSnapshotDigest: null,
retainedSourceCount: 0,
});
}
if (
value.status !== 'withdrawn' ||
target.installState !== 'active' ||
value.taskWithdrawals.length >
MAX_PLUGIN_PACKAGE_QUARANTINE_TASK_WITHDRAWALS ||
!Number.isSafeInteger(value.retainedSourceCount) ||
value.retainedSourceCount < 0 ||
value.retainedSourceCount > MAX_PLUGIN_PACKAGE_QUARANTINE_RETAINED_SOURCES
) {
return invalid('withdrawn capability disposition is invalid');
}
const taskWithdrawals = Object.freeze(
value.taskWithdrawals.map(normalizeTaskWithdrawal),
);
if (
taskWithdrawals.some(
(task, index) =>
index > 0 &&
Buffer.compare(
Buffer.from(taskWithdrawals[index - 1]!.taskId, 'utf8'),
Buffer.from(task.taskId, 'utf8'),
) >= 0,
)
) {
return invalid('task withdrawals must be unique and sorted');
}
const previousActiveVectorDigest = digest(
value.previousActiveVectorDigest,
'previousActiveVectorDigest',
);
const currentActiveVectorDigest = digest(
value.currentActiveVectorDigest,
'currentActiveVectorDigest',
);
if (previousActiveVectorDigest === currentActiveVectorDigest) {
return invalid('active vector did not change');
}
return Object.freeze({
status: 'withdrawn',
taskWithdrawals,
previousActiveVectorDigest,
currentActiveVectorDigest,
currentToolSnapshotDigest: digest(
value.currentToolSnapshotDigest,
'currentToolSnapshotDigest',
),
retainedSourceCount: value.retainedSourceCount,
});
}
function receiptFields(
value: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
eventDigest: value.eventDigest,
target: value.target,
capability: value.capability,
committedAtMs: value.committedAtMs,
};
}
export function pluginPackageWithdrawalReceiptDigest(
value: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(receiptFields(value)))
.digest('hex');
}
export function normalizePluginPackageWithdrawalReceipt(
value: PluginPackageWithdrawalReceipt,
): Readonly<PluginPackageWithdrawalReceipt> {
const receipt = dataRecord(value, 'withdrawal receipt');
exactKeys(
receipt,
[
'capability',
'committedAtMs',
'eventDigest',
'receiptDigest',
'schema',
'target',
],
'withdrawal receipt',
);
if (value.schema !== PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA) {
return invalid('withdrawal receipt schema is invalid');
}
const target = normalizeTarget(value.target);
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA,
eventDigest: digest(value.eventDigest, 'eventDigest'),
target,
capability: normalizeCapability(value.capability, target),
committedAtMs: timestamp(value.committedAtMs, 'committedAtMs'),
});
const receiptDigest = pluginPackageWithdrawalReceiptDigest(normalized);
if (value.receiptDigest !== receiptDigest) {
return invalid('receiptDigest does not match withdrawal receipt');
}
return Object.freeze({ ...normalized, receiptDigest });
}
export function createPluginPackageWithdrawalReceipt(
input: CreatePluginPackageWithdrawalReceiptInput,
): Readonly<PluginPackageWithdrawalReceipt> {
const value = dataRecord(input, 'withdrawal receipt input');
exactKeys(
value,
['capability', 'committedAtMs', 'eventDigest', 'target'],
'withdrawal receipt input',
);
const target = normalizeTarget(input.target);
const unsigned: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'> = {
schema: PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA,
eventDigest: digest(input.eventDigest, 'eventDigest'),
target,
capability: normalizeCapability(input.capability, target),
committedAtMs: timestamp(input.committedAtMs, 'committedAtMs'),
};
return normalizePluginPackageWithdrawalReceipt({
...unsigned,
receiptDigest: pluginPackageWithdrawalReceiptDigest(unsigned),
});
}
export function assertPluginPackageWithdrawalMatchesEvent(
eventValue: PluginPackageQuarantineEvent,
receiptValue: PluginPackageWithdrawalReceipt,
): void {
const event = normalizePluginPackageQuarantineEvent(eventValue);
const receipt = normalizePluginPackageWithdrawalReceipt(receiptValue);
if (
receipt.eventDigest !== event.eventDigest ||
JSON.stringify(receipt.target) !== JSON.stringify(event.target) ||
receipt.committedAtMs < event.occurredAtMs
) {
invalid('withdrawal receipt does not match quarantine event');
}
}
export function pluginPackageQuarantineTaskMutationId(
eventDigestValue: string,
taskIdValue: string,
): string {
const eventDigest = digest(eventDigestValue, 'eventDigest');
const taskId = identifier(taskIdValue, 'taskId');
const value = createHash('sha256')
.update(TASK_MUTATION_ID_DOMAIN)
.update(eventDigest)
.update('\0')
.update(taskId)
.digest('hex');
return `${value.slice(0, 8)}-${value.slice(8, 12)}-4${value.slice(
13,
16,
)}-a${value.slice(17, 20)}-${value.slice(20, 32)}`;
}
export function pluginPackageQuarantineMutationId(
revocationReceiptDigestValue: string,
targetValue: PluginPackageQuarantineTarget,
): string {
const revocationReceiptDigest = digest(
revocationReceiptDigestValue,
'revocationReceiptDigest',
);
const target = normalizeTarget(targetValue);
const value = createHash('sha256')
.update(QUARANTINE_MUTATION_ID_DOMAIN)
.update(revocationReceiptDigest)
.update('\0')
.update(JSON.stringify(target))
.digest('hex');
return `quarantine:${value}`;
}
@@ -0,0 +1,851 @@
import { semver } from '../versioning/pinnedSemver';
export const PLUGIN_PACKAGE_API_VERSION = 'qinglong.io/v1alpha1';
export const PLUGIN_PACKAGE_KIND = 'Package';
export const MAX_PLUGIN_PACKAGE_MANIFEST_BYTES = 64 * 1024;
export const MAX_PLUGIN_PACKAGE_RUNTIMES = 8;
export const MAX_PLUGIN_PACKAGE_NETWORK_HOSTS = 32;
export const MAX_PLUGIN_PACKAGE_SECRETS = 64;
export const MAX_PLUGIN_PACKAGE_TOOL_PERMISSIONS = 64;
export const MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES = 256;
export const MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES = 255;
export const MAX_PLUGIN_PACKAGE_RESOURCE_BYTES = 1024 ** 4;
export const PLUGIN_PACKAGE_ARCHITECTURES = [
'amd64',
'arm64',
'arm/v7',
'ppc64le',
's390x',
] as const;
export const PLUGIN_PACKAGE_DEPLOYMENT_PROFILES = [
'edge',
'standalone',
'cluster-control',
'worker',
] as const;
export const PLUGIN_PACKAGE_TOOL_PERMISSIONS = [
'artifact.read',
'dependency.install',
'filesystem.read',
'filesystem.write',
'mcp.tool.call',
'model.invoke',
'network.connect',
'notification.send',
'run.read',
'run.start',
'run.stop',
'run.retry',
'secret.use',
'system.command',
'task.read',
'task.update',
'background.service',
] as const;
export type PluginPackageArchitecture =
(typeof PLUGIN_PACKAGE_ARCHITECTURES)[number];
export type PluginPackageDeploymentProfile =
(typeof PLUGIN_PACKAGE_DEPLOYMENT_PROFILES)[number];
export type PluginPackageToolPermission =
(typeof PLUGIN_PACKAGE_TOOL_PERMISSIONS)[number];
export type PluginPackageRisk = 'low' | 'medium' | 'high';
export type PluginPackagePlanOperation =
| 'install'
| 'reinstall'
| 'upgrade'
| 'rollback';
export type PluginPackageFindingSeverity = 'warning' | 'error';
export interface PluginPackageManifestMetadata {
readonly name: string;
readonly displayName: string;
readonly version: string;
readonly description: string;
readonly license: string;
}
export interface PluginPackageRuntimeRequirement {
readonly name: string;
readonly version: string;
}
export interface PluginPackageSecretRequirement {
readonly name: string;
readonly required: boolean;
}
export interface PluginPackageContents {
readonly tasks: readonly string[];
readonly workflows: readonly string[];
readonly prompts: readonly string[];
readonly tools: readonly string[];
}
export interface PluginPackageManifest {
readonly apiVersion: typeof PLUGIN_PACKAGE_API_VERSION;
readonly kind: typeof PLUGIN_PACKAGE_KIND;
readonly metadata: Readonly<PluginPackageManifestMetadata>;
readonly spec: Readonly<{
compatibility: Readonly<{
qinglong: string;
architectures: readonly PluginPackageArchitecture[];
deploymentProfiles: readonly PluginPackageDeploymentProfile[];
}>;
runtimes: readonly Readonly<PluginPackageRuntimeRequirement>[];
resources: Readonly<{
memory: Readonly<{ recommended: string }>;
disk: Readonly<{ install: string; working: string }>;
}>;
permissions: Readonly<{
network: Readonly<{ allowedHosts: readonly string[] }>;
secrets: readonly Readonly<PluginPackageSecretRequirement>[];
tools: readonly PluginPackageToolPermission[];
}>;
contents: Readonly<PluginPackageContents>;
}>;
}
export interface PluginPackageRuntimeEnvironment {
readonly name: string;
readonly version: string;
}
export interface PluginPackageInstallEnvironment {
readonly qinglongVersion: string;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly runtimes: readonly Readonly<PluginPackageRuntimeEnvironment>[];
readonly availableMemoryBytes: number;
readonly availableDiskBytes: number;
}
export interface PluginPackagePlanFinding {
readonly code:
| 'architecture_unsupported'
| 'deployment_profile_unsupported'
| 'disk_insufficient'
| 'memory_below_recommendation'
| 'qinglong_version_unsupported'
| 'runtime_missing'
| 'runtime_version_unsupported';
readonly severity: PluginPackageFindingSeverity;
readonly subject: string;
}
export interface PluginPackageInstallPlan {
readonly package: Readonly<{
name: string;
fromVersion?: string;
toVersion: string;
}>;
readonly operation: PluginPackagePlanOperation;
readonly compatible: boolean;
readonly risk: PluginPackageRisk;
readonly approvalRequired: true;
readonly permissionReapprovalRequired: boolean;
readonly permissionDelta: Readonly<{
added: readonly string[];
removed: readonly string[];
}>;
readonly resources: Readonly<{
memoryRecommendedBytes: number;
diskInstallBytes: number;
diskWorkingBytes: number;
}>;
readonly contents: Readonly<{
tasks: number;
workflows: number;
prompts: number;
tools: number;
}>;
readonly findings: readonly Readonly<PluginPackagePlanFinding>[];
}
export class InvalidPluginPackageManifestError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANIFEST_INVALID';
constructor(message: string) {
super(`Plugin Package manifest is invalid: ${message}`);
this.name = 'InvalidPluginPackageManifestError';
}
}
export class InvalidPluginPackageInstallEnvironmentError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_ENVIRONMENT_INVALID';
constructor(message: string) {
super(`Plugin Package install environment is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallEnvironmentError';
}
}
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RUNTIME_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
const SECRET_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,127}$/;
const RESOURCE_PATTERN = /^([1-9][0-9]{0,6})(Ki|Mi|Gi)$/;
const HOST_PATTERN =
/^(?=.{1,253}$)[a-z0-9](?:(?:[a-z0-9-]{0,61})?[a-z0-9])?(?:\.[a-z0-9](?:(?:[a-z0-9-]{0,61})?[a-z0-9])?)*$/;
function record(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageManifestError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageManifestError(`${label} shape is invalid`);
}
}
function boundedText(
value: unknown,
label: string,
maximumBytes: number,
): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
CONTROL_PATTERN.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return value;
}
function canonicalVersion(value: unknown, label: string): string {
const version = boundedText(value, label, 128);
if (semver().valid(version) !== version) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return version;
}
function versionRange(value: unknown, label: string): string {
const range = boundedText(value, label, 256);
if (!semver().validRange(range)) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return range;
}
function uniqueSortedAllowed<T extends string>(
value: unknown,
allowed: readonly T[],
maximum: number,
label: string,
allowEmpty = false,
): readonly T[] {
if (
!Array.isArray(value) ||
value.length > maximum ||
(!allowEmpty && value.length === 0)
) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
const entries = new Set<T>();
for (const item of value) {
if (
typeof item !== 'string' ||
!allowed.includes(item as T) ||
entries.has(item as T)
) {
throw new InvalidPluginPackageManifestError(
`${label} contains an invalid or duplicate value`,
);
}
entries.add(item as T);
}
return Object.freeze([...entries].sort());
}
function normalizeRuntimes(
value: unknown,
): readonly Readonly<PluginPackageRuntimeRequirement>[] {
if (!Array.isArray(value) || value.length > MAX_PLUGIN_PACKAGE_RUNTIMES) {
throw new InvalidPluginPackageManifestError('runtimes are invalid');
}
const names = new Set<string>();
const runtimes = value.map((item) => {
const runtime = record(item, 'runtime');
exactKeys(runtime, ['name', 'version'], 'runtime');
const name = boundedText(runtime.name, 'runtime name', 32);
if (!RUNTIME_NAME_PATTERN.test(name) || names.has(name)) {
throw new InvalidPluginPackageManifestError(
'runtime name is invalid or duplicated',
);
}
names.add(name);
return Object.freeze({
name,
version: versionRange(runtime.version, 'runtime version range'),
});
});
runtimes.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze(runtimes);
}
function resourceBytes(value: unknown, label: string): number {
const quantity = boundedText(value, label, 16);
const match = RESOURCE_PATTERN.exec(quantity);
if (!match) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
const amount = Number(match[1]);
const unit = match[2];
const multiplier =
unit === 'Ki' ? 1024 : unit === 'Mi' ? 1024 ** 2 : 1024 ** 3;
const bytes = amount * multiplier;
if (
!Number.isSafeInteger(bytes) ||
bytes > MAX_PLUGIN_PACKAGE_RESOURCE_BYTES
) {
throw new InvalidPluginPackageManifestError(`${label} is out of range`);
}
return bytes;
}
function normalizeResourceQuantity(value: unknown, label: string): string {
const quantity = boundedText(value, label, 16);
resourceBytes(quantity, label);
return quantity;
}
function normalizeHosts(value: unknown): readonly string[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_NETWORK_HOSTS
) {
throw new InvalidPluginPackageManifestError(
'network allowedHosts are invalid',
);
}
const hosts = new Set<string>();
for (const item of value) {
const host = boundedText(item, 'network host', 253);
if (!HOST_PATTERN.test(host) || host.includes('*') || hosts.has(host)) {
throw new InvalidPluginPackageManifestError(
'network host is invalid or duplicated',
);
}
hosts.add(host);
}
return Object.freeze([...hosts].sort());
}
function normalizeSecrets(
value: unknown,
): readonly Readonly<PluginPackageSecretRequirement>[] {
if (!Array.isArray(value) || value.length > MAX_PLUGIN_PACKAGE_SECRETS) {
throw new InvalidPluginPackageManifestError(
'secret requirements are invalid',
);
}
const names = new Set<string>();
const secrets = value.map((item) => {
const secret = record(item, 'secret requirement');
exactKeys(secret, ['name', 'required'], 'secret requirement');
const name = boundedText(secret.name, 'secret name', 128);
if (
!SECRET_NAME_PATTERN.test(name) ||
names.has(name) ||
typeof secret.required !== 'boolean'
) {
throw new InvalidPluginPackageManifestError(
'secret requirement is invalid or duplicated',
);
}
names.add(name);
return Object.freeze({ name, required: secret.required });
});
secrets.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze(secrets);
}
function normalizeContentPath(value: unknown, directory: string): string {
const path = boundedText(
value,
`${directory} content path`,
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES,
);
const segments = path.split('/');
if (
path.startsWith('/') ||
path.includes('\\') ||
segments.length < 2 ||
segments[0] !== directory ||
segments.some(
(segment) => segment.length === 0 || segment === '.' || segment === '..',
)
) {
throw new InvalidPluginPackageManifestError(
`${directory} content path is invalid`,
);
}
return path;
}
function normalizeContents(value: unknown): Readonly<PluginPackageContents> {
const contents = record(value, 'contents');
exactKeys(contents, ['prompts', 'tasks', 'tools', 'workflows'], 'contents');
const seen = new Set<string>();
let total = 0;
const normalize = (
directory: string,
entries: unknown,
): readonly string[] => {
if (
!Array.isArray(entries) ||
entries.length > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
throw new InvalidPluginPackageManifestError(
`${directory} contents are invalid`,
);
}
total += entries.length;
if (total > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES) {
throw new InvalidPluginPackageManifestError(
'content entry budget exceeded',
);
}
const paths = entries.map((entry) => {
const path = normalizeContentPath(entry, directory);
if (seen.has(path)) {
throw new InvalidPluginPackageManifestError(
'content path is duplicated',
);
}
seen.add(path);
return path;
});
paths.sort();
return Object.freeze(paths);
};
return Object.freeze({
tasks: normalize('tasks', contents.tasks),
workflows: normalize('workflows', contents.workflows),
prompts: normalize('prompts', contents.prompts),
tools: normalize('tools', contents.tools),
});
}
export function normalizePluginPackageManifest(
value: unknown,
): Readonly<PluginPackageManifest> {
const manifest = record(value, 'manifest');
exactKeys(manifest, ['apiVersion', 'kind', 'metadata', 'spec'], 'manifest');
if (
manifest.apiVersion !== PLUGIN_PACKAGE_API_VERSION ||
manifest.kind !== PLUGIN_PACKAGE_KIND
) {
throw new InvalidPluginPackageManifestError(
'apiVersion or kind is unsupported',
);
}
const metadata = record(manifest.metadata, 'metadata');
exactKeys(
metadata,
['description', 'displayName', 'license', 'name', 'version'],
'metadata',
);
const name = boundedText(metadata.name, 'metadata name', 63);
if (!PACKAGE_NAME_PATTERN.test(name)) {
throw new InvalidPluginPackageManifestError(
'metadata name must be a lowercase DNS label',
);
}
const spec = record(manifest.spec, 'spec');
exactKeys(
spec,
['compatibility', 'contents', 'permissions', 'resources', 'runtimes'],
'spec',
);
const compatibility = record(spec.compatibility, 'compatibility');
exactKeys(
compatibility,
['architectures', 'deploymentProfiles', 'qinglong'],
'compatibility',
);
const resources = record(spec.resources, 'resources');
exactKeys(resources, ['disk', 'memory'], 'resources');
const memory = record(resources.memory, 'memory resources');
exactKeys(memory, ['recommended'], 'memory resources');
const disk = record(resources.disk, 'disk resources');
exactKeys(disk, ['install', 'working'], 'disk resources');
const permissions = record(spec.permissions, 'permissions');
exactKeys(permissions, ['network', 'secrets', 'tools'], 'permissions');
const network = record(permissions.network, 'network permissions');
exactKeys(network, ['allowedHosts'], 'network permissions');
const normalized: PluginPackageManifest = Object.freeze({
apiVersion: PLUGIN_PACKAGE_API_VERSION,
kind: PLUGIN_PACKAGE_KIND,
metadata: Object.freeze({
name,
displayName: boundedText(metadata.displayName, 'displayName', 128),
version: canonicalVersion(metadata.version, 'metadata version'),
description: boundedText(metadata.description, 'description', 4096),
license: boundedText(metadata.license, 'license', 128),
}),
spec: Object.freeze({
compatibility: Object.freeze({
qinglong: versionRange(
compatibility.qinglong,
'QingLong compatibility range',
),
architectures: uniqueSortedAllowed(
compatibility.architectures,
PLUGIN_PACKAGE_ARCHITECTURES,
PLUGIN_PACKAGE_ARCHITECTURES.length,
'architectures',
),
deploymentProfiles: uniqueSortedAllowed(
compatibility.deploymentProfiles,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.length,
'deployment profiles',
),
}),
runtimes: normalizeRuntimes(spec.runtimes),
resources: Object.freeze({
memory: Object.freeze({
recommended: normalizeResourceQuantity(
memory.recommended,
'recommended memory',
),
}),
disk: Object.freeze({
install: normalizeResourceQuantity(disk.install, 'install disk'),
working: normalizeResourceQuantity(disk.working, 'working disk'),
}),
}),
permissions: Object.freeze({
network: Object.freeze({
allowedHosts: normalizeHosts(network.allowedHosts),
}),
secrets: normalizeSecrets(permissions.secrets),
tools: uniqueSortedAllowed(
permissions.tools,
PLUGIN_PACKAGE_TOOL_PERMISSIONS,
MAX_PLUGIN_PACKAGE_TOOL_PERMISSIONS,
'tool permissions',
true,
),
}),
contents: normalizeContents(spec.contents),
}),
});
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_PLUGIN_PACKAGE_MANIFEST_BYTES
) {
throw new InvalidPluginPackageManifestError(
'canonical manifest byte budget exceeded',
);
}
return normalized;
}
export function normalizePluginPackageInstallEnvironment(
value: PluginPackageInstallEnvironment,
): Readonly<PluginPackageInstallEnvironment> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment must be an object',
);
}
const raw = value as unknown as Record<string, unknown>;
const expected = [
'architecture',
'availableDiskBytes',
'availableMemoryBytes',
'deploymentProfile',
'qinglongVersion',
'runtimes',
];
const actual = Object.keys(raw).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment shape is invalid',
);
}
if (
typeof value.qinglongVersion !== 'string' ||
semver().valid(value.qinglongVersion) !== value.qinglongVersion ||
!PLUGIN_PACKAGE_ARCHITECTURES.includes(value.architecture) ||
!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(value.deploymentProfile) ||
!Number.isSafeInteger(value.availableMemoryBytes) ||
value.availableMemoryBytes < 0 ||
!Number.isSafeInteger(value.availableDiskBytes) ||
value.availableDiskBytes < 0 ||
!Array.isArray(value.runtimes) ||
value.runtimes.length > MAX_PLUGIN_PACKAGE_RUNTIMES
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment value is invalid',
);
}
const names = new Set<string>();
const runtimes = value.runtimes.map((item) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
throw new InvalidPluginPackageInstallEnvironmentError(
'runtime is invalid',
);
}
const runtime = item as unknown as Record<string, unknown>;
if (
Object.keys(runtime).sort().join(',') !== 'name,version' ||
typeof item.name !== 'string' ||
!RUNTIME_NAME_PATTERN.test(item.name) ||
names.has(item.name) ||
typeof item.version !== 'string' ||
semver().valid(item.version) !== item.version
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'runtime is invalid or duplicated',
);
}
names.add(item.name);
return Object.freeze({ name: item.name, version: item.version });
});
runtimes.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze({
qinglongVersion: value.qinglongVersion,
architecture: value.architecture,
deploymentProfile: value.deploymentProfile,
runtimes: Object.freeze(runtimes),
availableMemoryBytes: value.availableMemoryBytes,
availableDiskBytes: value.availableDiskBytes,
});
}
function permissionSet(
manifest: Readonly<PluginPackageManifest>,
): ReadonlySet<string> {
const permissions = new Set<string>();
for (const host of manifest.spec.permissions.network.allowedHosts) {
permissions.add(`network:${host}`);
}
for (const secret of manifest.spec.permissions.secrets) {
permissions.add(
`secret:${secret.name}:${secret.required ? 'required' : 'optional'}`,
);
}
for (const permission of manifest.spec.permissions.tools) {
permissions.add(`tool:${permission}`);
}
return permissions;
}
function packageRisk(
manifest: Readonly<PluginPackageManifest>,
): PluginPackageRisk {
const tools = new Set(manifest.spec.permissions.tools);
if (
tools.has('background.service') ||
tools.has('dependency.install') ||
tools.has('system.command')
) {
return 'high';
}
if (
manifest.spec.permissions.network.allowedHosts.length > 0 ||
manifest.spec.permissions.secrets.length > 0 ||
tools.has('filesystem.write') ||
tools.has('model.invoke') ||
tools.has('mcp.tool.call') ||
tools.has('run.start') ||
tools.has('run.stop') ||
tools.has('run.retry') ||
tools.has('task.update')
) {
return 'medium';
}
return 'low';
}
export function planPluginPackageInstall(
manifestValue: unknown,
environmentValue: PluginPackageInstallEnvironment,
previousManifestValue?: unknown,
): Readonly<PluginPackageInstallPlan> {
const manifest = normalizePluginPackageManifest(manifestValue);
const environment =
normalizePluginPackageInstallEnvironment(environmentValue);
const previous =
previousManifestValue === undefined
? undefined
: normalizePluginPackageManifest(previousManifestValue);
if (previous && previous.metadata.name !== manifest.metadata.name) {
throw new InvalidPluginPackageManifestError(
'previous and candidate package names differ',
);
}
const findings: PluginPackagePlanFinding[] = [];
const addFinding = (
code: PluginPackagePlanFinding['code'],
severity: PluginPackageFindingSeverity,
subject: string,
): void => {
findings.push(Object.freeze({ code, severity, subject }));
};
if (
!semver().satisfies(
environment.qinglongVersion,
manifest.spec.compatibility.qinglong,
{ includePrerelease: true },
)
) {
addFinding(
'qinglong_version_unsupported',
'error',
environment.qinglongVersion,
);
}
if (
!manifest.spec.compatibility.architectures.includes(
environment.architecture,
)
) {
addFinding('architecture_unsupported', 'error', environment.architecture);
}
if (
!manifest.spec.compatibility.deploymentProfiles.includes(
environment.deploymentProfile,
)
) {
addFinding(
'deployment_profile_unsupported',
'error',
environment.deploymentProfile,
);
}
const availableRuntimes = new Map(
environment.runtimes.map((runtime) => [runtime.name, runtime.version]),
);
for (const requirement of manifest.spec.runtimes) {
const actual = availableRuntimes.get(requirement.name);
if (!actual) {
addFinding('runtime_missing', 'error', requirement.name);
} else if (
!semver().satisfies(actual, requirement.version, {
includePrerelease: true,
})
) {
addFinding(
'runtime_version_unsupported',
'error',
`${requirement.name}@${actual}`,
);
}
}
const memoryRecommendedBytes = resourceBytes(
manifest.spec.resources.memory.recommended,
'recommended memory',
);
const diskInstallBytes = resourceBytes(
manifest.spec.resources.disk.install,
'install disk',
);
const diskWorkingBytes = resourceBytes(
manifest.spec.resources.disk.working,
'working disk',
);
if (environment.availableMemoryBytes < memoryRecommendedBytes) {
addFinding(
'memory_below_recommendation',
'warning',
String(environment.availableMemoryBytes),
);
}
if (environment.availableDiskBytes < diskInstallBytes + diskWorkingBytes) {
addFinding(
'disk_insufficient',
'error',
String(environment.availableDiskBytes),
);
}
const candidatePermissions = permissionSet(manifest);
const previousPermissions = previous
? permissionSet(previous)
: new Set<string>();
const added = [...candidatePermissions]
.filter((permission) => !previousPermissions.has(permission))
.sort();
const removed = [...previousPermissions]
.filter((permission) => !candidatePermissions.has(permission))
.sort();
let operation: PluginPackagePlanOperation = 'install';
if (previous) {
const comparison = semver().compare(
manifest.metadata.version,
previous.metadata.version,
);
operation =
comparison > 0 ? 'upgrade' : comparison < 0 ? 'rollback' : 'reinstall';
}
findings.sort(
(left, right) =>
left.severity.localeCompare(right.severity) ||
left.code.localeCompare(right.code) ||
left.subject.localeCompare(right.subject),
);
return Object.freeze({
package: Object.freeze({
name: manifest.metadata.name,
...(previous ? { fromVersion: previous.metadata.version } : {}),
toVersion: manifest.metadata.version,
}),
operation,
compatible: findings.every((finding) => finding.severity !== 'error'),
risk: packageRisk(manifest),
approvalRequired: true,
permissionReapprovalRequired: previous ? added.length > 0 : true,
permissionDelta: Object.freeze({
added: Object.freeze(added),
removed: Object.freeze(removed),
}),
resources: Object.freeze({
memoryRecommendedBytes,
diskInstallBytes,
diskWorkingBytes,
}),
contents: Object.freeze({
tasks: manifest.spec.contents.tasks.length,
workflows: manifest.spec.contents.workflows.length,
prompts: manifest.spec.contents.prompts.length,
tools: manifest.spec.contents.tools.length,
}),
findings: Object.freeze(findings),
});
}
@@ -0,0 +1,226 @@
import { createHash } from 'node:crypto';
import {
PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION,
PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON,
PLUGIN_PACKAGE_INSTALL_ACTION_TYPE,
PluginPackageAdmissionBindingConflictError,
PluginPackageAdmissionReceiptConflictError,
assertPluginPackageAdmissionReplay,
type PluginPackageAdmissionRepository,
type PluginPackageAdmissionRequest,
} from './installation/pluginPackageAdmission';
import type {
ApprovedActionHandler,
ApprovedActionHandlerExecutionContext,
ApprovedActionHandlerInspection,
ApprovedActionHandlerResult,
} from '../approved-action/approvedActionDispatcher';
import {
PluginPackageInstallProposalBindingConflictError,
normalizePluginPackageInstallProposal,
resolvePluginPackageInstallProposal,
type PluginPackageInstallProposalRepository,
} from './pluginPackageProposal';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
function stableDigest(domain: string, dispatchId: string): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(dispatchId)
.digest('hex');
}
function stableIdentifier(domain: string, dispatchId: string): string {
return `ppa-${stableDigest(domain, dispatchId)}`;
}
function stableAuditEventId(dispatchId: string): string {
const bytes = Buffer.from(
stableDigest('qinglong/plugin-package-admission-audit-id@v1', dispatchId),
'hex',
);
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = bytes.toString('hex');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(
12,
16,
)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
export class PluginPackageApprovedActionHandler
implements ApprovedActionHandler
{
readonly actionType = PLUGIN_PACKAGE_INSTALL_ACTION_TYPE;
constructor(
readonly proposals: PluginPackageInstallProposalRepository,
readonly admissions: PluginPackageAdmissionRepository,
) {
if (
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
!admissions ||
typeof admissions.admit !== 'function' ||
typeof admissions.findAdmissionReceipt !== 'function' ||
typeof admissions.find !== 'function'
) {
throw new TypeError('Plugin Package Approved Action authority is invalid');
}
}
async inspect(
dispatch: ApprovedActionHandlerExecutionContext['dispatch'],
): Promise<ApprovedActionHandlerInspection> {
let proposal;
try {
proposal = await this.proposals.findProposalByActionRef(
dispatch.action.actionRef,
);
} catch {
return Object.freeze({
status: 'retry',
resultCode: 'package_proposal_unavailable',
});
}
if (!proposal) {
return Object.freeze({
status: 'blocked',
resultCode: 'package_proposal_missing',
});
}
try {
const normalized = normalizePluginPackageInstallProposal(proposal);
resolvePluginPackageInstallProposal(
normalized,
dispatch,
dispatch.createdAtMs,
);
return Object.freeze({
status: 'ready',
actionDigest: normalized.actionDigest,
});
} catch {
return Object.freeze({
status: 'blocked',
resultCode: 'package_proposal_rejected',
});
}
}
async execute(
context: Readonly<ApprovedActionHandlerExecutionContext>,
): Promise<Readonly<ApprovedActionHandlerResult>> {
const startedAtMs = context.execution.startedAtMs;
if (
context.execution.status !== 'executing' ||
startedAtMs === null ||
context.execution.leaseOwner !== context.fence.owner ||
context.execution.leaseToken !== context.fence.leaseToken ||
context.execution.version !== context.fence.version
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_execution_rejected',
});
}
const proposal = await this.proposals.findProposalByActionRef(
context.dispatch.action.actionRef,
);
if (!proposal) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_proposal_missing',
});
}
let lock;
try {
lock = resolvePluginPackageInstallProposal(
proposal,
context.dispatch,
startedAtMs,
);
} catch (error) {
if (error instanceof PluginPackageInstallProposalBindingConflictError) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_proposal_rejected',
});
}
throw error;
}
const installationId = stableIdentifier(
'qinglong/plugin-package-admission-installation-id@v1',
context.dispatch.id,
);
const mutationId = stableIdentifier(
'qinglong/plugin-package-admission-mutation-id@v1',
context.dispatch.id,
);
const audit: SecurityAuditRecord = Object.freeze({
eventId: stableAuditEventId(context.dispatch.id),
requestId: context.dispatch.id,
operationId: PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION,
projectId: context.dispatch.projectId,
subject: context.dispatch.consumedBy,
authenticationId: context.dispatch.approvalAuthenticationId,
outcome: 'allowed',
reasons: Object.freeze([PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON]),
fence: context.dispatch.approvalFence,
occurredAtMs: startedAtMs,
});
const request: PluginPackageAdmissionRequest = Object.freeze({
lock,
proposalDigest: proposal.proposalDigest,
execution: context.execution,
installationId,
mutationId,
admittedAtMs: startedAtMs,
audit,
});
try {
const result = await this.admissions.admit(request);
return Object.freeze({
outcome: 'succeeded',
resultCode: 'package_admitted',
resultDigest: result.receipt.receiptDigest,
});
} catch (error) {
if (
error instanceof PluginPackageAdmissionBindingConflictError ||
error instanceof PluginPackageAdmissionReceiptConflictError
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_admission_rejected',
});
}
const receipt = await this.admissions.findAdmissionReceipt(
context.dispatch.id,
);
if (!receipt) throw error;
const record = await this.admissions.find(
lock.projectId,
lock.packageName,
);
if (!record || record.installationId !== installationId) throw error;
assertPluginPackageAdmissionReplay(
context.dispatch,
proposal,
request,
receipt,
record,
);
return Object.freeze({
outcome: 'succeeded',
resultCode: 'package_admitted',
resultDigest: receipt.receiptDigest,
});
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,874 @@
import {
MAX_APPROVAL_LIFETIME_MS,
createApprovalRequest,
normalizeApprovalRequestRecord,
type ApprovalDecision,
type ApprovalDecisionMode,
type ApprovalRequestRecord,
type ApprovalRequestRepository,
type ApprovalRisk,
type CreateApprovalRequestResult,
type DecideApprovalRequestResult,
type ConsumeDurableApprovalRequestResult,
} from '../approved-action/approvedAction';
import type { ApprovedActionDispatchBatchSummary } from '../approved-action/approvedActionDispatcher';
import {
createPluginPackageInstallProposal,
normalizePluginPackageInstallProposal,
type CreatePluginPackageInstallProposalResult,
type PluginPackageInstallProposal,
type PluginPackageInstallProposalRepository,
} from './pluginPackageProposal';
import {
normalizePluginPackageInstallActionInput,
type PluginPackageInstallActionInput,
} from './installation/pluginPackageInstall';
import {
ProjectPolicyEngine,
type ProjectPolicyRequest,
} from '../security/project-policy/projectPolicy';
import {
normalizeSecurityPrincipal,
type SecurityPrincipal,
type SecuritySubject,
} from '../security/security';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
const DEFAULT_APPROVAL_LIFETIME_MS = 15 * 60 * 1000;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const AUTHENTICATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export interface PluginPackageManagementDispatchPort {
dispatchBatch(
options?: Readonly<{ limit?: number }>,
): Promise<Readonly<ApprovedActionDispatchBatchSummary>>;
}
export const PLUGIN_PACKAGE_MANAGEMENT_QUOTA_OPERATIONS = [
'plugin-package.propose',
'plugin-package.decide',
'plugin-package.inspect',
] as const;
export type PluginPackageManagementQuotaOperation =
(typeof PLUGIN_PACKAGE_MANAGEMENT_QUOTA_OPERATIONS)[number];
export interface ConsumePluginPackageManagementQuotaCommand {
readonly projectId: string;
readonly subject: SecuritySubject;
readonly operation: PluginPackageManagementQuotaOperation;
readonly idempotencyKey: string;
}
export interface PluginPackageManagementQuotaResult {
readonly remaining: number;
readonly resetAtMs: number;
readonly observedAtMs: number;
}
export interface PluginPackageManagementQuotaPort {
consume(
command: ConsumePluginPackageManagementQuotaCommand,
): Promise<Readonly<PluginPackageManagementQuotaResult>>;
}
export interface PluginPackageManagementOptions {
readonly decisionMode: ApprovalDecisionMode;
readonly consumer: Readonly<{
subject: SecuritySubject;
authenticationId: string;
}>;
readonly approvalLifetimeMs?: number;
readonly risk?: ApprovalRisk;
readonly now?: () => number;
readonly quota?: PluginPackageManagementQuotaPort;
}
export interface ProposePluginPackageInstallRequest {
readonly actionRef: string;
readonly approvalRequestId: string;
readonly proposalAuditEventId: string;
readonly approvalAuditEventId: string;
readonly requestedAtMs: number;
readonly actionInput: PluginPackageInstallActionInput;
readonly principal: SecurityPrincipal;
}
export interface ProposePluginPackageInstallResult {
readonly proposalStatus: CreatePluginPackageInstallProposalResult['status'];
readonly approvalStatus: CreateApprovalRequestResult['status'];
readonly proposal: Readonly<PluginPackageInstallProposal>;
readonly approvalRequest: Readonly<ApprovalRequestRecord>;
}
export interface DecidePluginPackageInstallRequest {
readonly approvalRequestId: string;
readonly expectedVersion: number;
readonly decisionId: string;
readonly auditEventId: string;
readonly decision: ApprovalDecision;
readonly reasonCode: string;
readonly decidedAtMs: number;
readonly principal: SecurityPrincipal;
}
export interface ConsumePluginPackageInstallRequest {
readonly approvalRequestId: string;
readonly expectedVersion: number;
readonly consumptionId: string;
readonly dispatchId: string;
readonly auditEventId: string;
readonly consumedAtMs: number;
}
export interface InspectPluginPackageInstallResult {
readonly proposal: Readonly<PluginPackageInstallProposal> | null;
readonly approvalRequest: Readonly<ApprovalRequestRecord> | null;
}
export interface PluginPackageManagementService {
propose(
request: ProposePluginPackageInstallRequest,
): Promise<Readonly<ProposePluginPackageInstallResult>>;
decide(
request: DecidePluginPackageInstallRequest,
): Promise<Readonly<DecideApprovalRequestResult>>;
consume(
request: ConsumePluginPackageInstallRequest,
): Promise<Readonly<ConsumeDurableApprovalRequestResult>>;
inspect(
actionRef: string,
approvalRequestId: string,
): Promise<Readonly<InspectPluginPackageInstallResult>>;
dispatch(
limit?: number,
): Promise<Readonly<ApprovedActionDispatchBatchSummary>>;
}
export class PluginPackageManagementConfigurationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_CONFIGURATION_INVALID';
constructor(message: string) {
super(`Plugin Package management configuration is invalid: ${message}`);
this.name = 'PluginPackageManagementConfigurationError';
}
}
export class PluginPackageManagementRequestError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_REQUEST_INVALID';
constructor(message: string) {
super(`Plugin Package management request is invalid: ${message}`);
this.name = 'PluginPackageManagementRequestError';
}
}
export class PluginPackageManagementAuthorizationError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_FORBIDDEN';
constructor() {
super('Plugin Package management is not authorized');
this.name = 'PluginPackageManagementAuthorizationError';
}
}
export class PluginPackageManagementConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_CONFLICT';
constructor(message = 'Plugin Package management state conflicts') {
super(message);
this.name = 'PluginPackageManagementConflictError';
}
}
export class PluginPackageManagementUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package management is unavailable', options);
this.name = 'PluginPackageManagementUnavailableError';
}
}
export class PluginPackageManagementQuotaExceededError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_QUOTA_EXCEEDED';
constructor(readonly retryAfterMs: number) {
if (
!Number.isSafeInteger(retryAfterMs) ||
retryAfterMs < 1 ||
retryAfterMs > 5 * 60_000
) {
throw new TypeError(
'Plugin Package management quota retry delay is invalid',
);
}
super('Plugin Package management quota is exhausted');
this.name = 'PluginPackageManagementQuotaExceededError';
}
}
function exactObject(
value: unknown,
expectedKeys: readonly string[],
label: string,
): asserts value is Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new PluginPackageManagementRequestError(`${label} must be an object`);
}
const actual = Object.keys(value).sort();
const expected = [...expectedKeys].sort();
if (
actual.length !== expected.length ||
actual.some((key, index) => key !== expected[index])
) {
throw new PluginPackageManagementRequestError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value;
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new PluginPackageManagementRequestError(
'action reference is invalid',
);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(
value: unknown,
label: string,
maximum: number,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value as number;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function sameProposal(
stored: Readonly<PluginPackageInstallProposal>,
expected: Readonly<PluginPackageInstallProposal>,
): boolean {
return stored.proposalDigest === expected.proposalDigest;
}
function sameApprovalRequest(
stored: Readonly<ApprovalRequestRecord>,
expected: Readonly<ApprovalRequestRecord>,
): boolean {
return (
stored.id === expected.id &&
stored.projectId === expected.projectId &&
stored.action.actionRef === expected.action.actionRef &&
stored.action.actionType === expected.action.actionType &&
stored.action.permission === expected.action.permission &&
stored.action.actionDigest === expected.action.actionDigest &&
stored.action.previewDigest === expected.action.previewDigest &&
stored.risk === expected.risk &&
stored.decisionMode === expected.decisionMode &&
sameSubject(stored.requestedBy, expected.requestedBy) &&
stored.requestedAtMs === expected.requestedAtMs &&
stored.expiresAtMs === expected.expiresAtMs
);
}
function allowedPolicy(
effect: 'allow' | 'deny' | 'require_approval',
allowApproval: boolean,
): boolean {
return effect === 'allow' || (allowApproval && effect === 'require_approval');
}
function audit(
eventId: string,
requestId: string,
operationId: string,
projectId: string,
subject: Readonly<SecuritySubject>,
authenticationId: string,
outcome: 'allowed' | 'approval_required',
reasons: readonly string[],
fence: Readonly<{ projectVersion: number; bindingVersion: number | null }>,
occurredAtMs: number,
): SecurityAuditRecord {
return {
eventId,
requestId,
operationId,
projectId,
subject,
authenticationId,
outcome,
reasons,
fence,
occurredAtMs,
};
}
export function createPluginPackageManagementService(
policy: ProjectPolicyEngine,
proposals: PluginPackageInstallProposalRepository,
approvals: ApprovalRequestRepository,
dispatcher: PluginPackageManagementDispatchPort,
options: PluginPackageManagementOptions,
): PluginPackageManagementService {
if (
!policy ||
typeof policy.authorize !== 'function' ||
typeof policy.decide !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'Project policy is invalid',
);
}
if (
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
typeof proposals.createProposal !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'proposal repository is invalid',
);
}
if (
!approvals ||
typeof approvals.findById !== 'function' ||
typeof approvals.create !== 'function' ||
typeof approvals.decide !== 'function' ||
typeof approvals.consume !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'approval repository is invalid',
);
}
if (!dispatcher || typeof dispatcher.dispatchBatch !== 'function') {
throw new PluginPackageManagementConfigurationError(
'dispatcher is invalid',
);
}
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new PluginPackageManagementConfigurationError('options are invalid');
}
const optionKeys = Object.keys(options);
if (
optionKeys.some(
(key) =>
key !== 'decisionMode' &&
key !== 'consumer' &&
key !== 'approvalLifetimeMs' &&
key !== 'risk' &&
key !== 'now' &&
key !== 'quota',
)
) {
throw new PluginPackageManagementConfigurationError(
'options shape is invalid',
);
}
if (
options.decisionMode !== 'human_confirmation' &&
options.decisionMode !== 'separation_of_duty'
) {
throw new PluginPackageManagementConfigurationError(
'decision mode is invalid',
);
}
if (
!options.consumer ||
typeof options.consumer !== 'object' ||
Array.isArray(options.consumer) ||
Object.keys(options.consumer).length !== 2 ||
!Object.hasOwn(options.consumer, 'subject') ||
!Object.hasOwn(options.consumer, 'authenticationId') ||
options.consumer.subject?.type !== 'system' ||
typeof options.consumer.subject.id !== 'string' ||
options.consumer.subject.id.length < 1 ||
options.consumer.subject.id.length > 255 ||
!AUTHENTICATION_ID_PATTERN.test(options.consumer.authenticationId)
) {
throw new PluginPackageManagementConfigurationError(
'consumer authority is invalid',
);
}
const approvalLifetimeMs =
options.approvalLifetimeMs ?? DEFAULT_APPROVAL_LIFETIME_MS;
if (
!Number.isSafeInteger(approvalLifetimeMs) ||
approvalLifetimeMs < 1_000 ||
approvalLifetimeMs > MAX_APPROVAL_LIFETIME_MS
) {
throw new PluginPackageManagementConfigurationError(
'approval lifetime is invalid',
);
}
const risk = options.risk ?? 'high';
if (!['low', 'medium', 'high', 'critical'].includes(risk)) {
throw new PluginPackageManagementConfigurationError('risk is invalid');
}
if (options.now !== undefined && typeof options.now !== 'function') {
throw new PluginPackageManagementConfigurationError('clock is invalid');
}
if (
options.quota !== undefined &&
(!options.quota ||
typeof options.quota !== 'object' ||
Array.isArray(options.quota) ||
typeof options.quota.consume !== 'function')
) {
throw new PluginPackageManagementConfigurationError('quota is invalid');
}
const now = options.now ?? Date.now;
const consumer = Object.freeze({
subject: Object.freeze({
type: 'system' as const,
id: options.consumer.subject.id,
}),
authenticationId: options.consumer.authenticationId,
});
const currentTime = (): number => {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new PluginPackageManagementUnavailableError();
}
return value;
};
const authorizePrincipal = async (
principalValue: SecurityPrincipal,
projectId: string,
permission: 'package.manage' | 'approval.decide',
observedAtMs: number,
allowApproval: boolean,
) => {
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(principalValue, observedAtMs);
} catch {
throw new PluginPackageManagementAuthorizationError();
}
let decision;
try {
decision = await policy.authorize(principal, projectId, permission);
} catch (error) {
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (
!allowedPolicy(decision.effect, allowApproval) ||
decision.fence === null
) {
throw new PluginPackageManagementAuthorizationError();
}
return Object.freeze({ principal, fence: decision.fence });
};
const consumeQuota = async (
projectId: string,
principal: Readonly<SecurityPrincipal>,
operation: PluginPackageManagementQuotaOperation,
idempotencyKey: string,
): Promise<void> => {
if (!options.quota) return;
try {
await options.quota.consume({
projectId,
subject: principal.subject,
operation,
idempotencyKey,
});
} catch (error) {
if (error instanceof PluginPackageManagementQuotaExceededError) {
throw error;
}
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
};
const propose = async (
request: ProposePluginPackageInstallRequest,
): Promise<Readonly<ProposePluginPackageInstallResult>> => {
exactObject(
request,
[
'actionRef',
'approvalRequestId',
'proposalAuditEventId',
'approvalAuditEventId',
'requestedAtMs',
'actionInput',
'principal',
],
'proposal request',
);
const requestedActionRef = actionRef(request.actionRef);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const requestedAtMs = timestamp(request.requestedAtMs, 'request time');
const observedAtMs = currentTime();
if (
requestedAtMs > observedAtMs ||
observedAtMs >= requestedAtMs + approvalLifetimeMs
) {
throw new PluginPackageManagementRequestError(
'request time is outside the approval lifetime',
);
}
let normalizedActionInput: Readonly<PluginPackageInstallActionInput>;
try {
normalizedActionInput = normalizePluginPackageInstallActionInput(
request.actionInput,
);
} catch {
throw new PluginPackageManagementRequestError(
'install action input is invalid',
);
}
const { principal, fence } = await authorizePrincipal(
request.principal,
normalizedActionInput.projectId,
'package.manage',
observedAtMs,
true,
);
await consumeQuota(
normalizedActionInput.projectId,
principal,
'plugin-package.propose',
requestedActionRef,
);
const expectedProposal = createPluginPackageInstallProposal({
actionRef: requestedActionRef,
actionInput: normalizedActionInput,
proposedBy: principal.subject,
proposalFence: fence,
createdAtMs: requestedAtMs,
});
let proposalResult: Readonly<CreatePluginPackageInstallProposalResult>;
const existingProposal = await proposals.findProposalByActionRef(
requestedActionRef,
);
if (existingProposal) {
const normalized =
normalizePluginPackageInstallProposal(existingProposal);
if (!sameProposal(normalized, expectedProposal)) {
throw new PluginPackageManagementConflictError(
'Plugin Package proposal identity already has different content',
);
}
proposalResult = Object.freeze({
status: 'existing' as const,
proposal: normalized,
});
} else {
proposalResult = await proposals.createProposal({
proposal: expectedProposal,
audit: audit(
identifier(request.proposalAuditEventId, 'proposal audit event id'),
requestedActionRef,
'plugin_package.propose',
expectedProposal.projectId,
principal.subject,
principal.authenticationId,
'allowed',
['package_proposal'],
fence,
requestedAtMs,
),
});
}
const proposal = normalizePluginPackageInstallProposal(
proposalResult.proposal,
);
const approval = createApprovalRequest({
id: approvalRequestId,
projectId: proposal.projectId,
action: {
permission: proposal.permission,
actionType: proposal.actionType,
actionRef: proposal.actionRef,
actionDigest: proposal.actionDigest,
previewDigest: proposal.previewDigest,
},
risk,
decisionMode: options.decisionMode,
requestedBy: principal.subject,
requestedAtMs,
expiresAtMs: requestedAtMs + approvalLifetimeMs,
requestFence: fence,
});
let approvalResult: Readonly<CreateApprovalRequestResult>;
const existingApproval = await approvals.findById(approvalRequestId);
if (existingApproval) {
const normalized = normalizeApprovalRequestRecord(existingApproval);
if (!sameApprovalRequest(normalized, approval)) {
throw new PluginPackageManagementConflictError(
'Approval request identity already has different content',
);
}
approvalResult = Object.freeze({
status: 'existing' as const,
request: normalized,
});
} else {
approvalResult = await approvals.create({
request: approval,
audit: audit(
identifier(request.approvalAuditEventId, 'approval audit event id'),
approvalRequestId,
'approval.request',
proposal.projectId,
principal.subject,
principal.authenticationId,
'approval_required',
['package_review'],
fence,
requestedAtMs,
),
});
}
return Object.freeze({
proposalStatus: proposalResult.status,
approvalStatus: approvalResult.status,
proposal,
approvalRequest: approvalResult.request,
});
};
const decide = async (
request: DecidePluginPackageInstallRequest,
): Promise<Readonly<DecideApprovalRequestResult>> => {
exactObject(
request,
[
'approvalRequestId',
'expectedVersion',
'decisionId',
'auditEventId',
'decision',
'reasonCode',
'decidedAtMs',
'principal',
],
'decision request',
);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const expectedVersion = positiveInteger(
request.expectedVersion,
'expected version',
2_147_483_647,
);
const decisionId = identifier(request.decisionId, 'decision id');
if (request.decision !== 'approved' && request.decision !== 'rejected') {
throw new PluginPackageManagementRequestError('decision is invalid');
}
if (
typeof request.reasonCode !== 'string' ||
!REASON_PATTERN.test(request.reasonCode)
) {
throw new PluginPackageManagementRequestError(
'decision reason is invalid',
);
}
const decidedAtMs = timestamp(request.decidedAtMs, 'decision time');
const observedAtMs = currentTime();
if (decidedAtMs > observedAtMs) {
throw new PluginPackageManagementRequestError(
'decision time is in the future',
);
}
const current = await approvals.findById(approvalRequestId);
if (!current) {
throw new PluginPackageManagementConflictError(
'Approval request does not exist',
);
}
const approval = normalizeApprovalRequestRecord(current);
const { principal, fence } = await authorizePrincipal(
request.principal,
approval.projectId,
'approval.decide',
observedAtMs,
false,
);
await consumeQuota(
approval.projectId,
principal,
'plugin-package.decide',
decisionId,
);
return approvals.decide({
requestId: approvalRequestId,
expectedVersion,
decisionId,
decision: request.decision,
reasonCode: request.reasonCode,
principal,
decidedAtMs,
authorizationFence: fence,
audit: audit(
identifier(request.auditEventId, 'decision audit event id'),
approvalRequestId,
'approval.decide',
approval.projectId,
principal.subject,
principal.authenticationId,
'allowed',
['package_review'],
fence,
decidedAtMs,
),
});
};
const consume = async (
request: ConsumePluginPackageInstallRequest,
): Promise<Readonly<ConsumeDurableApprovalRequestResult>> => {
exactObject(
request,
[
'approvalRequestId',
'expectedVersion',
'consumptionId',
'dispatchId',
'auditEventId',
'consumedAtMs',
],
'consumption request',
);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const expectedVersion = positiveInteger(
request.expectedVersion,
'expected version',
2_147_483_647,
);
const consumptionId = identifier(request.consumptionId, 'consumption id');
const dispatchId = identifier(request.dispatchId, 'dispatch id');
const consumedAtMs = timestamp(request.consumedAtMs, 'consumption time');
const observedAtMs = currentTime();
if (consumedAtMs > observedAtMs) {
throw new PluginPackageManagementRequestError(
'consumption time is in the future',
);
}
const current = await approvals.findById(approvalRequestId);
if (!current) {
throw new PluginPackageManagementConflictError(
'Approval request does not exist',
);
}
const approval = normalizeApprovalRequestRecord(current);
let policyDecision;
try {
const policyRequest: ProjectPolicyRequest = {
subject: approval.requestedBy,
projectId: approval.projectId,
permission: 'package.manage',
};
policyDecision = await policy.decide(policyRequest);
} catch (error) {
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (!allowedPolicy(policyDecision.effect, true) || !policyDecision.fence) {
throw new PluginPackageManagementAuthorizationError();
}
const fence = policyDecision.fence;
return approvals.consume({
requestId: approvalRequestId,
expectedVersion,
consumptionId,
dispatchId,
action: approval.action,
requestedBy: approval.requestedBy,
consumedBy: consumer.subject,
consumedAtMs,
authorizationFence: fence,
audit: audit(
identifier(request.auditEventId, 'consumption audit event id'),
approvalRequestId,
'approval.consume',
approval.projectId,
consumer.subject,
consumer.authenticationId,
'allowed',
['package_review'],
fence,
consumedAtMs,
),
});
};
return Object.freeze({
propose,
decide,
consume,
async inspect(requestedActionRef: string, approvalRequestIdValue: string) {
const normalizedActionRef = actionRef(requestedActionRef);
const approvalRequestId = identifier(
approvalRequestIdValue,
'approval request id',
);
const [proposal, approvalRequest] = await Promise.all([
proposals.findProposalByActionRef(normalizedActionRef),
approvals.findById(approvalRequestId),
]);
return Object.freeze({
proposal: proposal
? normalizePluginPackageInstallProposal(proposal)
: null,
approvalRequest: approvalRequest
? normalizeApprovalRequestRecord(approvalRequest)
: null,
});
},
dispatch(limit?: number) {
return dispatcher.dispatchBatch(
limit === undefined
? undefined
: { limit: positiveInteger(limit, 'dispatch limit', 64) },
);
},
});
}
@@ -0,0 +1,318 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../approved-action/approvedAction';
import {
createPluginPackageLock,
normalizePluginPackageInstallActionInput,
pluginPackageInstallActionDigest,
pluginPackageInstallPlanDigest,
type PluginPackageInstallActionInput,
type PluginPackageLock,
} from './installation/pluginPackageInstall';
import {
normalizeProjectPolicySubject,
} from '../security/project-policy/projectPolicy';
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../security/security';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
export const PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA =
'qinglong/plugin-package-install-proposal@v1' as const;
export const PLUGIN_PACKAGE_INSTALL_ACTION_TYPE =
'plugin_package.install' as const;
export const PLUGIN_PACKAGE_INSTALL_PERMISSION = 'package.manage' as const;
export interface PluginPackageInstallProposal {
readonly schema: typeof PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: typeof PLUGIN_PACKAGE_INSTALL_ACTION_TYPE;
readonly permission: typeof PLUGIN_PACKAGE_INSTALL_PERMISSION;
readonly actionInput: Readonly<PluginPackageInstallActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface CreatePluginPackageInstallProposalInput {
readonly actionRef: string;
readonly actionInput: PluginPackageInstallActionInput;
readonly proposedBy: SecuritySubject;
readonly proposalFence: SecurityPolicyFence;
readonly createdAtMs: number;
}
export interface PluginPackageInstallProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackageInstallProposal> | null>;
createProposal(
command: CreatePluginPackageInstallProposalCommand,
): Promise<Readonly<CreatePluginPackageInstallProposalResult>>;
}
export interface CreatePluginPackageInstallProposalCommand {
readonly proposal: PluginPackageInstallProposal;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackageInstallProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackageInstallProposal>;
}
export class InvalidPluginPackageInstallProposalError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_INVALID';
constructor(message: string) {
super(`Plugin Package install proposal is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallProposalError';
}
}
export class PluginPackageInstallProposalBindingConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_BINDING_CONFLICT';
constructor() {
super('Plugin Package install proposal does not match its dispatch');
this.name = 'PluginPackageInstallProposalBindingConflictError';
}
}
export class PluginPackageInstallProposalConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_CONFLICT';
constructor() {
super('Plugin Package install proposal conflicts with durable authority');
this.name = 'PluginPackageInstallProposalConflictError';
}
}
export class PluginPackageInstallProposalUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package install proposal authority is unavailable', options);
this.name = 'PluginPackageInstallProposalUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallProposalError(
`${label} must be an object`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallProposalError(
`${label} shape is invalid`,
);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallProposalError(
'action reference is invalid',
);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallProposalError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallProposalError(`${label} is invalid`);
}
return value as number;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function withoutProposalDigest(
value: Omit<PluginPackageInstallProposal, 'proposalDigest'>,
): Omit<PluginPackageInstallProposal, 'proposalDigest'> {
return Object.freeze(value);
}
function withProposalDigest(
value: Omit<PluginPackageInstallProposal, 'proposalDigest'>,
): Readonly<PluginPackageInstallProposal> {
const normalized = withoutProposalDigest(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-install-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackageInstallProposal(
inputValue: CreatePluginPackageInstallProposalInput,
): Readonly<PluginPackageInstallProposal> {
const input = dataRecord(inputValue, 'proposal input');
exactKeys(
input,
[
'actionRef',
'actionInput',
'proposedBy',
'proposalFence',
'createdAtMs',
],
'proposal input',
);
const actionInput = normalizePluginPackageInstallActionInput(
inputValue.actionInput,
);
const proposedBy = normalizeProjectPolicySubject(inputValue.proposedBy);
return withProposalDigest({
schema: PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.projectId,
actionType: PLUGIN_PACKAGE_INSTALL_ACTION_TYPE,
permission: PLUGIN_PACKAGE_INSTALL_PERMISSION,
actionInput,
actionDigest: pluginPackageInstallActionDigest(actionInput),
previewDigest: pluginPackageInstallPlanDigest(actionInput.plan),
proposedBy,
proposalFence: normalizeApprovedActionFence(inputValue.proposalFence),
createdAtMs: timestamp(inputValue.createdAtMs, 'creation time'),
});
}
export function normalizePluginPackageInstallProposal(
value: PluginPackageInstallProposal,
): Readonly<PluginPackageInstallProposal> {
const proposal = dataRecord(value, 'proposal');
exactKeys(
proposal,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
if (
value.schema !== PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA ||
value.actionType !== PLUGIN_PACKAGE_INSTALL_ACTION_TYPE ||
value.permission !== PLUGIN_PACKAGE_INSTALL_PERMISSION
) {
throw new InvalidPluginPackageInstallProposalError(
'schema or action authority is invalid',
);
}
const normalized = createPluginPackageInstallProposal({
actionRef: actionRef(value.actionRef),
actionInput: value.actionInput,
proposedBy: value.proposedBy,
proposalFence: value.proposalFence,
createdAtMs: timestamp(value.createdAtMs, 'creation time'),
});
const proposalDigest = digest(value.proposalDigest, 'proposal digest');
if (
value.projectId !== normalized.projectId ||
value.actionDigest !== normalized.actionDigest ||
value.previewDigest !== normalized.previewDigest ||
proposalDigest !== normalized.proposalDigest
) {
throw new InvalidPluginPackageInstallProposalError(
'proposal digest or derived binding is invalid',
);
}
return normalized;
}
export function resolvePluginPackageInstallProposal(
proposalValue: PluginPackageInstallProposal,
dispatchValue: ApprovedActionDispatchRecord,
createdAtMsValue: number,
): Readonly<PluginPackageLock> {
const proposal = normalizePluginPackageInstallProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const createdAtMs = timestamp(createdAtMsValue, 'lock creation time');
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
dispatch.requestedBy.type !== proposal.proposedBy.type ||
dispatch.requestedBy.id !== proposal.proposedBy.id ||
dispatch.createdAtMs < proposal.createdAtMs ||
createdAtMs < dispatch.createdAtMs ||
createdAtMs >= dispatch.expiresAtMs
) {
throw new PluginPackageInstallProposalBindingConflictError();
}
return createPluginPackageLock({
...proposal.actionInput,
approval: {
requestId: dispatch.approvalRequestId,
requestVersion: dispatch.approvalRequestVersion,
dispatchId: dispatch.id,
actionDigest: dispatch.action.actionDigest,
previewDigest: dispatch.action.previewDigest,
approvedBy: dispatch.approvedBy,
approvedAtMs: dispatch.approvedAtMs,
expiresAtMs: dispatch.expiresAtMs,
fence: dispatch.approvalFence,
},
createdAtMs,
});
}
@@ -0,0 +1,445 @@
import { createHash } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES,
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES,
type PluginPackageContents,
} from './pluginPackage';
export const PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA =
'qinglong/plugin-package-resource-generation@v1' as const;
export const PLUGIN_PACKAGE_RESOURCE_KINDS = [
'prompt',
'task',
'tool',
'workflow',
] as const;
export const MAX_PLUGIN_PACKAGE_RESOURCE_PATH_BYTES =
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES;
export const MAX_PLUGIN_PACKAGE_RESOURCE_GENERATION = 2_147_483_647;
export type PluginPackageResourceKind =
(typeof PLUGIN_PACKAGE_RESOURCE_KINDS)[number];
export interface PluginPackageResourceReference {
readonly kind: PluginPackageResourceKind;
readonly path: string;
}
export interface PluginPackageResourceGeneration {
readonly schema: typeof PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
readonly generationDigest: string;
}
export interface CreatePluginPackageResourceGenerationInput {
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly contents: Readonly<PluginPackageContents>;
}
export interface CreatePluginPackageResourceGenerationFromReferencesInput {
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
}
export interface PluginPackageResourceGenerationSource {
findActiveResourceGeneration(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageResourceGeneration> | null>;
}
export class InvalidPluginPackageResourceGenerationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_RESOURCE_GENERATION_INVALID';
constructor(message: string) {
super(`Plugin Package resource generation is invalid: ${message}`);
this.name = 'InvalidPluginPackageResourceGenerationError';
}
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST = /^[0-9a-f]{64}$/;
const RESOURCE_DIRECTORY = Object.freeze({
prompt: 'prompts',
task: 'tasks',
tool: 'tools',
workflow: 'workflows',
} satisfies Readonly<Record<PluginPackageResourceKind, string>>);
const GENERATION_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-resource-generation-digest@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageResourceGenerationError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const stringKeys = actual.filter(
(key): key is string => typeof key === 'string',
);
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
stringKeys.length !== canonical.length ||
stringKeys.sort().some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function boundedDenseArray(value: unknown, label: string): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
return invalid(`${label} is invalid`);
}
const keys = Object.keys(value);
const ownKeys = Reflect.ownKeys(value);
if (
ownKeys.length !== value.length + 1 ||
!ownKeys.includes('length') ||
keys.length !== value.length ||
keys.some((key, index) => key !== String(index))
) {
return invalid(`${label} must be a dense data array`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
keys.some((key) => {
const descriptor = descriptors[key];
return (
descriptor === undefined ||
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true
);
})
) {
return invalid(`${label} must be a dense data array`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('package name is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function generation(value: unknown): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > MAX_PLUGIN_PACKAGE_RESOURCE_GENERATION
) {
return invalid('generation is invalid');
}
return value as number;
}
function resourcePath(value: unknown, kind: PluginPackageResourceKind): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
Buffer.byteLength(value, 'utf8') > MAX_PLUGIN_PACKAGE_RESOURCE_PATH_BYTES ||
value.startsWith('/') ||
value.includes('\\') ||
value.includes('\0')
) {
return invalid('resource path is invalid');
}
const segments = value.split('/');
if (
segments.length < 2 ||
segments[0] !== RESOURCE_DIRECTORY[kind] ||
segments.some(
(segment) => segment.length === 0 || segment === '.' || segment === '..',
)
) {
return invalid('resource path is invalid');
}
return value;
}
function compareResourceReferences(
left: Readonly<PluginPackageResourceReference>,
right: Readonly<PluginPackageResourceReference>,
): number {
const kind = left.kind.localeCompare(right.kind);
return kind === 0 ? left.path.localeCompare(right.path) : kind;
}
export function normalizePluginPackageResourceReferences(
value: unknown,
): readonly Readonly<PluginPackageResourceReference>[] {
const entries = boundedDenseArray(value, 'resources');
const seen = new Set<string>();
const resources = entries.map((entryValue) => {
const entry = dataRecord(entryValue, 'resource reference');
exactKeys(entry, ['kind', 'path'], 'resource reference');
if (
!PLUGIN_PACKAGE_RESOURCE_KINDS.includes(
entry.kind as PluginPackageResourceKind,
)
) {
return invalid('resource kind is invalid');
}
const kind = entry.kind as PluginPackageResourceKind;
const path = resourcePath(entry.path, kind);
if (seen.has(path)) return invalid('resource path is duplicated');
seen.add(path);
return Object.freeze({ kind, path });
});
const sorted = [...resources].sort(compareResourceReferences);
if (
resources.some(
(resource, index) =>
resource.kind !== sorted[index]?.kind ||
resource.path !== sorted[index]?.path,
)
) {
return invalid('resources are not in canonical order');
}
return Object.freeze(resources);
}
export function pluginPackageResourceReferencesFromContents(
value: Readonly<PluginPackageContents>,
): readonly Readonly<PluginPackageResourceReference>[] {
const contents = dataRecord(value, 'contents');
exactKeys(contents, ['prompts', 'tasks', 'tools', 'workflows'], 'contents');
const references: PluginPackageResourceReference[] = [];
const append = (kind: PluginPackageResourceKind, paths: unknown): void => {
const entries = boundedDenseArray(paths, `${kind} contents`);
if (
references.length + entries.length >
MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
return invalid('resource budget is exceeded');
}
for (const path of entries) {
references.push(Object.freeze({ kind, path: resourcePath(path, kind) }));
}
};
append('prompt', contents.prompts);
append('task', contents.tasks);
append('tool', contents.tools);
append('workflow', contents.workflows);
references.sort(compareResourceReferences);
return normalizePluginPackageResourceReferences(references);
}
function unsignedGeneration(
value: Omit<PluginPackageResourceGeneration, 'generationDigest'>,
): Omit<PluginPackageResourceGeneration, 'generationDigest'> {
return value;
}
function resourceGenerationDigest(
value: Omit<PluginPackageResourceGeneration, 'generationDigest'>,
): string {
return createHash('sha256')
.update(GENERATION_DIGEST_DOMAIN)
.update(JSON.stringify(value), 'utf8')
.digest('hex');
}
function createWithResources(
input: Record<string, unknown>,
resources: readonly Readonly<PluginPackageResourceReference>[],
): Readonly<PluginPackageResourceGeneration> {
const previousActiveLockDigest =
input.previousActiveLockDigest === null
? null
: digest(input.previousActiveLockDigest, 'previous active lock digest');
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA,
installationId: identifier(input.installationId, 'installation id'),
projectId: identifier(input.projectId, 'project id'),
packageName: packageName(input.packageName),
lockDigest: digest(input.lockDigest, 'lock digest'),
generation: generation(input.generation),
previousActiveLockDigest,
contentDigest: digest(input.contentDigest, 'content digest'),
resources,
});
return Object.freeze({
...unsigned,
generationDigest: resourceGenerationDigest(unsignedGeneration(unsigned)),
});
}
export function createPluginPackageResourceGeneration(
value: CreatePluginPackageResourceGenerationInput,
): Readonly<PluginPackageResourceGeneration> {
const input = dataRecord(value, 'generation input');
exactKeys(
input,
[
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'contents',
],
'generation input',
);
return createWithResources(
input,
pluginPackageResourceReferencesFromContents(
input.contents as Readonly<PluginPackageContents>,
),
);
}
export function createPluginPackageResourceGenerationFromReferences(
value: CreatePluginPackageResourceGenerationFromReferencesInput,
): Readonly<PluginPackageResourceGeneration> {
const input = dataRecord(value, 'generation input');
exactKeys(
input,
[
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'resources',
],
'generation input',
);
return createWithResources(
input,
normalizePluginPackageResourceReferences(input.resources),
);
}
export function normalizePluginPackageResourceGeneration(
value: unknown,
): Readonly<PluginPackageResourceGeneration> {
const generationValue = dataRecord(value, 'generation');
exactKeys(
generationValue,
[
'schema',
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'resources',
'generationDigest',
],
'generation',
);
if (generationValue.schema !== PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA) {
return invalid('schema is invalid');
}
const previousActiveLockDigest =
generationValue.previousActiveLockDigest === null
? null
: digest(
generationValue.previousActiveLockDigest,
'previous active lock digest',
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA,
installationId: identifier(
generationValue.installationId,
'installation id',
),
projectId: identifier(generationValue.projectId, 'project id'),
packageName: packageName(generationValue.packageName),
lockDigest: digest(generationValue.lockDigest, 'lock digest'),
generation: generation(generationValue.generation),
previousActiveLockDigest,
contentDigest: digest(generationValue.contentDigest, 'content digest'),
resources: normalizePluginPackageResourceReferences(
generationValue.resources,
),
});
const generationDigest = digest(
generationValue.generationDigest,
'generation digest',
);
if (
generationDigest !== resourceGenerationDigest(unsignedGeneration(unsigned))
) {
return invalid('generation digest does not match its payload');
}
return Object.freeze({ ...unsigned, generationDigest });
}
@@ -0,0 +1,612 @@
import {
InvalidPluginPackageResourceMaterializationError,
PluginPackageResourceMaterializationConflictError,
PluginPackageResourceMaterializationUnavailableError,
materializeActivePluginPackageResources,
normalizePluginPackageMaterializedRevision,
type PluginPackageMaterializedRevisionRepository,
type PluginPackageResourceByteSource,
type PluginPackageResourceLockSource,
} from './pluginPackageResourceMaterialization';
import type { PluginPackageResourceGenerationSource } from './pluginPackageResourceGeneration';
import {
InvalidPluginPackageTaskReconciliationError,
PluginPackageTaskReconciliationConflictError,
PluginPackageTaskReconciliationUnavailableError,
type PluginPackageTaskReconciliationReceipt,
type PluginPackageTaskReconciliationRepository,
} from './pluginPackageTaskReconciliation';
import { TaskSpecSemanticRegistry } from '../task-definition/taskSpecSemantic';
export const MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGES = 64;
export interface PluginPackageTaskPublicationPendingCandidate {
readonly projectId: string;
readonly packageName: string;
}
export interface PluginPackageTaskPublicationRecoveryCursor {
readonly projectId: string;
readonly packageName: string;
}
export interface PluginPackageTaskPublicationRecoveryPage {
readonly candidates: readonly Readonly<PluginPackageTaskPublicationPendingCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}
export interface PluginPackageTaskPublicationRecoverySource {
listPendingPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}): Promise<Readonly<PluginPackageTaskPublicationRecoveryPage>>;
}
export interface PluginPackageTaskPublicationCurrentResult {
readonly status: 'current';
readonly materialized: 'created' | 'existing';
readonly reconciled: 'created' | 'existing';
readonly generationDigest: string;
readonly revisionDigest: string;
readonly receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
}
export interface PluginPackageTaskPublicationAbsentResult {
readonly status: 'absent';
}
export interface PluginPackageTaskPublicationSupersededResult {
readonly status: 'superseded';
readonly generationDigest: string;
}
export type PluginPackageTaskPublicationResult =
| Readonly<PluginPackageTaskPublicationCurrentResult>
| Readonly<PluginPackageTaskPublicationAbsentResult>
| Readonly<PluginPackageTaskPublicationSupersededResult>;
export type PluginPackageTaskPublicationRecoveryItemStatus =
| 'manual_required'
| 'retry'
| 'settled'
| 'superseded';
export interface PluginPackageTaskPublicationRecoveryItem {
readonly projectId: string;
readonly packageName: string;
readonly status: PluginPackageTaskPublicationRecoveryItemStatus;
}
export interface PluginPackageTaskPublicationRecoveryCycleResult {
readonly pages: number;
readonly scanned: number;
readonly settled: number;
readonly retry: number;
readonly manualRequired: number;
readonly superseded: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
export class InvalidPluginPackageTaskPublicationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_INVALID';
constructor(message: string) {
super(`Plugin Package Task publication is invalid: ${message}`);
this.name = 'InvalidPluginPackageTaskPublicationError';
}
}
export class PluginPackageTaskPublicationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_CONFLICT';
constructor(message: string, options?: ErrorOptions) {
super(`Plugin Package Task publication conflicts with state: ${message}`, options);
this.name = 'PluginPackageTaskPublicationConflictError';
}
}
export class PluginPackageTaskPublicationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Task publication is unavailable', options);
this.name = 'PluginPackageTaskPublicationUnavailableError';
}
}
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
function invalid(message: string): never {
throw new InvalidPluginPackageTaskPublicationError(message);
}
function record(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > 128
) {
return invalid('projectId is invalid');
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function positiveInteger(value: unknown, maximum: number, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function normalizeCandidate(
value: PluginPackageTaskPublicationPendingCandidate,
): Readonly<PluginPackageTaskPublicationPendingCandidate> {
const candidate = record(value, 'pending candidate');
exactKeys(candidate, ['packageName', 'projectId'], [], 'pending candidate');
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
});
}
export function normalizePluginPackageTaskPublicationRecoveryCursor(
value: PluginPackageTaskPublicationRecoveryCursor,
): Readonly<PluginPackageTaskPublicationRecoveryCursor> {
const cursor = record(value, 'recovery cursor');
exactKeys(cursor, ['packageName', 'projectId'], [], 'recovery cursor');
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
});
}
export function assertPluginPackageTaskPublicationRecoveryPageSize(
value: number,
): void {
positiveInteger(
value,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE,
'recovery page size',
);
}
function compareCandidates(
left: Readonly<PluginPackageTaskPublicationPendingCandidate>,
right: Readonly<PluginPackageTaskPublicationPendingCandidate>,
): number {
return (
left.projectId.localeCompare(right.projectId) ||
left.packageName.localeCompare(right.packageName)
);
}
function normalizePage(
value: PluginPackageTaskPublicationRecoveryPage,
limit: number,
): Readonly<PluginPackageTaskPublicationRecoveryPage> {
const page = record(value, 'recovery page');
exactKeys(page, ['candidates', 'truncated'], ['next'], 'recovery page');
if (
!Array.isArray(value.candidates) ||
value.candidates.length > limit ||
typeof value.truncated !== 'boolean'
) {
return invalid('recovery page is invalid');
}
const candidates = Object.freeze(value.candidates.map(normalizeCandidate));
if (
candidates.some(
(candidate, index) =>
index > 0 &&
compareCandidates(candidates[index - 1]!, candidate) >= 0,
)
) {
return invalid('recovery candidates must be uniquely sorted');
}
const next =
value.next === undefined
? undefined
: normalizePluginPackageTaskPublicationRecoveryCursor(value.next);
const last = candidates.at(-1);
if (
value.truncated !== (next !== undefined) ||
(next &&
(!last ||
next.projectId !== last.projectId ||
next.packageName !== last.packageName))
) {
return invalid('recovery continuation is invalid');
}
return Object.freeze({
candidates,
truncated: value.truncated,
...(next ? { next } : {}),
});
}
function publicationAuthorities(options: {
readonly generationSource: PluginPackageResourceGenerationSource;
readonly lockSource: PluginPackageResourceLockSource;
readonly byteSource: PluginPackageResourceByteSource;
readonly materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}): void {
const value = record(options, 'publication coordinator options');
exactKeys(
value,
[
'byteSource',
'generationSource',
'lockSource',
'materializedRepository',
'reconciliationRepository',
'taskSpecSemanticRegistry',
],
[],
'publication coordinator options',
);
if (
!options.generationSource ||
typeof options.generationSource.findActiveResourceGeneration !== 'function' ||
!options.lockSource ||
typeof options.lockSource.findLock !== 'function' ||
!options.byteSource ||
typeof options.byteSource.open !== 'function' ||
!options.materializedRepository ||
typeof options.materializedRepository.find !== 'function' ||
typeof options.materializedRepository.publish !== 'function' ||
!options.reconciliationRepository ||
typeof options.reconciliationRepository.find !== 'function' ||
typeof options.reconciliationRepository.reconcile !== 'function' ||
!(options.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)
) {
invalid('publication coordinator authority is invalid');
}
}
export class PluginPackageTaskPublicationCoordinator {
readonly #generationSource: PluginPackageResourceGenerationSource;
readonly #lockSource: PluginPackageResourceLockSource;
readonly #byteSource: PluginPackageResourceByteSource;
readonly #materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly #reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly #registry: TaskSpecSemanticRegistry;
constructor(options: {
readonly generationSource: PluginPackageResourceGenerationSource;
readonly lockSource: PluginPackageResourceLockSource;
readonly byteSource: PluginPackageResourceByteSource;
readonly materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}) {
publicationAuthorities(options);
this.#generationSource = options.generationSource;
this.#lockSource = options.lockSource;
this.#byteSource = options.byteSource;
this.#materializedRepository = options.materializedRepository;
this.#reconciliationRepository = options.reconciliationRepository;
this.#registry = options.taskSpecSemanticRegistry;
}
async publishActive(
projectIdValue: string,
packageNameValue: string,
): Promise<Readonly<PluginPackageTaskPublicationResult>> {
const identity = {
projectId: projectId(projectIdValue),
packageName: packageName(packageNameValue),
};
try {
const first = await this.#generationSource.findActiveResourceGeneration(
identity.projectId,
identity.packageName,
);
if (first === null) return Object.freeze({ status: 'absent' });
if (
first.projectId !== identity.projectId ||
first.packageName !== identity.packageName
) {
throw new PluginPackageTaskPublicationConflictError(
'generation source returned another Package identity',
);
}
let revision = await this.#materializedRepository.find(
first.generationDigest,
);
let materialized: 'created' | 'existing' = 'existing';
if (revision === null) {
const materializedValue = await materializeActivePluginPackageResources({
...identity,
generationSource: this.#generationSource,
lockSource: this.#lockSource,
byteSource: this.#byteSource,
taskSpecSemanticRegistry: this.#registry,
});
if (materializedValue === null) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
if (materializedValue.generation.generationDigest !== first.generationDigest) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
const publication = await this.#materializedRepository.publish(
materializedValue,
);
materialized = publication.status;
revision = publication.revision;
}
const normalizedRevision = normalizePluginPackageMaterializedRevision(
revision,
this.#registry,
);
if (
normalizedRevision.generation.generationDigest !==
first.generationDigest ||
normalizedRevision.generation.projectId !== identity.projectId ||
normalizedRevision.generation.packageName !== identity.packageName
) {
throw new PluginPackageTaskPublicationConflictError(
'durable materialized revision does not match the active generation',
);
}
const reconciliation = await this.#reconciliationRepository.reconcile(
normalizedRevision,
this.#generationSource,
);
const finalGeneration =
await this.#generationSource.findActiveResourceGeneration(
identity.projectId,
identity.packageName,
);
if (
finalGeneration === null ||
finalGeneration.generationDigest !== first.generationDigest
) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
return Object.freeze({
status: 'current',
materialized,
reconciled: reconciliation.status,
generationDigest: first.generationDigest,
revisionDigest: normalizedRevision.revisionDigest,
receipt: reconciliation.receipt,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageTaskPublicationError ||
error instanceof PluginPackageTaskPublicationConflictError ||
error instanceof PluginPackageTaskPublicationUnavailableError
) {
throw error;
}
if (
error instanceof InvalidPluginPackageResourceMaterializationError ||
error instanceof InvalidPluginPackageTaskReconciliationError
) {
throw new InvalidPluginPackageTaskPublicationError(error.message);
}
if (
error instanceof PluginPackageResourceMaterializationConflictError ||
error instanceof PluginPackageTaskReconciliationConflictError
) {
throw new PluginPackageTaskPublicationConflictError(
'active generation publication fence changed',
{ cause: error },
);
}
if (
error instanceof PluginPackageResourceMaterializationUnavailableError ||
error instanceof PluginPackageTaskReconciliationUnavailableError
) {
throw new PluginPackageTaskPublicationUnavailableError({ cause: error });
}
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
}
}
export class PluginPackageTaskPublicationRecoveryCoordinator {
readonly #source: PluginPackageTaskPublicationRecoverySource;
readonly #publisher: PluginPackageTaskPublicationCoordinator;
constructor(options: {
readonly source: PluginPackageTaskPublicationRecoverySource;
readonly publisher: PluginPackageTaskPublicationCoordinator;
}) {
const value = record(options, 'recovery coordinator options');
exactKeys(value, ['publisher', 'source'], [], 'recovery coordinator options');
if (
!options.source ||
typeof options.source.listPendingPage !== 'function' ||
!(options.publisher instanceof PluginPackageTaskPublicationCoordinator)
) {
invalid('recovery coordinator authority is invalid');
}
this.#source = options.source;
this.#publisher = options.publisher;
}
async recoverPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}): Promise<
Readonly<{
items: readonly Readonly<PluginPackageTaskPublicationRecoveryItem>[];
truncated: boolean;
next?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}>
> {
const value = record(options, 'recovery page options');
exactKeys(value, ['limit'], ['after'], 'recovery page options');
assertPluginPackageTaskPublicationRecoveryPageSize(options.limit);
const after =
options.after === undefined
? undefined
: normalizePluginPackageTaskPublicationRecoveryCursor(options.after);
let page: Readonly<PluginPackageTaskPublicationRecoveryPage>;
try {
page = normalizePage(
await this.#source.listPendingPage({
limit: options.limit,
...(after ? { after } : {}),
}),
options.limit,
);
} catch (error) {
if (error instanceof InvalidPluginPackageTaskPublicationError) throw error;
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
const items: Readonly<PluginPackageTaskPublicationRecoveryItem>[] = [];
for (const candidate of page.candidates) {
let status: PluginPackageTaskPublicationRecoveryItemStatus;
try {
const published = await this.#publisher.publishActive(
candidate.projectId,
candidate.packageName,
);
status =
published.status === 'current'
? 'settled'
: published.status === 'superseded'
? 'superseded'
: 'manual_required';
} catch (error) {
status =
error instanceof InvalidPluginPackageTaskPublicationError ||
error instanceof PluginPackageTaskPublicationConflictError
? 'manual_required'
: 'retry';
}
items.push(Object.freeze({ ...candidate, status }));
}
return Object.freeze({
items: Object.freeze(items),
truncated: page.truncated,
...(page.next ? { next: page.next } : {}),
});
}
async recover(
options: {
readonly pageSize?: number;
readonly maxPages?: number;
} = {},
): Promise<Readonly<PluginPackageTaskPublicationRecoveryCycleResult>> {
const value = record(options, 'recovery cycle options');
exactKeys(value, [], ['maxPages', 'pageSize'], 'recovery cycle options');
const pageSize = positiveInteger(
options.pageSize ?? 8,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE,
'recovery page size',
);
const maxPages = positiveInteger(
options.maxPages ?? 8,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGES,
'recovery page count',
);
const counts = {
pages: 0,
scanned: 0,
settled: 0,
retry: 0,
manualRequired: 0,
superseded: 0,
};
let after: Readonly<PluginPackageTaskPublicationRecoveryCursor> | undefined;
let exhausted = false;
while (counts.pages < maxPages) {
const page = await this.recoverPage({
limit: pageSize,
...(after ? { after } : {}),
});
counts.pages += 1;
counts.scanned += page.items.length;
for (const item of page.items) {
if (item.status === 'settled') counts.settled += 1;
else if (item.status === 'retry') counts.retry += 1;
else if (item.status === 'manual_required') counts.manualRequired += 1;
else counts.superseded += 1;
}
if (!page.truncated) {
exhausted = true;
break;
}
after = page.next;
}
let probe: Readonly<PluginPackageTaskPublicationRecoveryPage>;
try {
probe = normalizePage(await this.#source.listPendingPage({ limit: 1 }), 1);
} catch (error) {
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
const remaining = !exhausted || probe.candidates.length > 0;
return Object.freeze({
...counts,
remaining,
safeToAdmit:
!remaining && counts.retry === 0 && counts.manualRequired === 0,
});
}
}
@@ -0,0 +1,611 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageMaterializedRevision,
pluginPackageTaskDefinitionDrafts,
type PluginPackageMaterializedRevision,
type PluginPackageTaskDefinitionDraft,
} from './pluginPackageResourceMaterialization';
import type { PluginPackageResourceGenerationSource } from './pluginPackageResourceGeneration';
import {
createTaskDefinitionRecord,
normalizeTaskDefinitionRecord,
taskDefinitionContentDigest,
type AppendTaskDefinitionRevisionCommand,
type TaskDefinitionRecord,
} from '../task-definition/taskDefinition';
import { TaskSpecSemanticRegistry } from '../task-definition/taskSpecSemantic';
export const PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA =
'qinglong/plugin-package-task-reconciliation@v1' as const;
export const MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS = 512;
export type PluginPackageTaskReconciliationDisposition =
| 'already_disabled'
| 'created'
| 'disabled'
| 'retained'
| 'updated';
export interface PluginPackageTaskOwnershipFact {
readonly taskId: string;
readonly packageName: string | null;
readonly current: Readonly<TaskDefinitionRecord> | null;
}
export interface PluginPackageTaskReconciliationItem {
readonly taskId: string;
readonly revision: number;
readonly disposition: PluginPackageTaskReconciliationDisposition;
readonly contentDigest: string;
}
export interface PluginPackageTaskReconciliationReceipt {
readonly schema: typeof PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly generation: number;
readonly generationDigest: string;
readonly materializedRevisionDigest: string;
readonly lockDigest: string;
readonly previousLockDigest: string | null;
readonly committedAtMs: number;
readonly items: readonly Readonly<PluginPackageTaskReconciliationItem>[];
readonly receiptDigest: string;
}
export interface PluginPackageTaskReconciliationWrite {
readonly command: Readonly<AppendTaskDefinitionRevisionCommand>;
readonly definition: Readonly<TaskDefinitionRecord>;
}
export interface PluginPackageTaskReconciliationPlan {
readonly receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
readonly writes: readonly Readonly<PluginPackageTaskReconciliationWrite>[];
}
export interface PlanPluginPackageTaskReconciliationInput {
readonly revision: Readonly<PluginPackageMaterializedRevision>;
readonly previousReceipt: Readonly<PluginPackageTaskReconciliationReceipt> | null;
readonly facts: readonly Readonly<PluginPackageTaskOwnershipFact>[];
readonly committedAtMs: number;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}
export interface PluginPackageTaskReconciliationRepository {
find(
generationDigest: string,
): Promise<Readonly<PluginPackageTaskReconciliationReceipt> | null>;
reconcile(
revision: Readonly<PluginPackageMaterializedRevision>,
activeGenerationSource: PluginPackageResourceGenerationSource,
): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
}>
>;
}
export class InvalidPluginPackageTaskReconciliationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_INVALID';
constructor(message: string) {
super(`Plugin Package Task reconciliation is invalid: ${message}`);
this.name = 'InvalidPluginPackageTaskReconciliationError';
}
}
export class PluginPackageTaskReconciliationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_CONFLICT';
constructor(message: string) {
super(`Plugin Package Task reconciliation conflicts with state: ${message}`);
this.name = 'PluginPackageTaskReconciliationConflictError';
}
}
export class PluginPackageTaskReconciliationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Task reconciliation is unavailable', options);
this.name = 'PluginPackageTaskReconciliationUnavailableError';
}
}
const DIGEST = /^[0-9a-f]{64}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const ITEM_DISPOSITIONS = Object.freeze([
'already_disabled',
'created',
'disabled',
'retained',
'updated',
] as const);
const RECEIPT_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-task-reconciliation-receipt@v1\0',
'utf8',
);
const MUTATION_ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-task-reconciliation-mutation@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageTaskReconciliationError(message);
}
function conflict(message: string): never {
throw new PluginPackageTaskReconciliationConflictError(message);
}
function identifier(value: unknown, label: string): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > 128
) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function integer(value: unknown, label: string, minimum: number): number {
if (!Number.isSafeInteger(value) || (value as number) < minimum) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function denseItems(value: unknown): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS ||
Object.keys(value).some((key, index) => key !== String(index))
) {
return invalid('items are invalid');
}
return value;
}
function unsignedReceipt(
value: Omit<PluginPackageTaskReconciliationReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
projectId: value.projectId,
packageName: value.packageName,
generation: value.generation,
generationDigest: value.generationDigest,
materializedRevisionDigest: value.materializedRevisionDigest,
lockDigest: value.lockDigest,
previousLockDigest: value.previousLockDigest,
committedAtMs: value.committedAtMs,
items: value.items,
};
}
export function pluginPackageTaskReconciliationReceiptDigest(
value: Omit<PluginPackageTaskReconciliationReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(unsignedReceipt(value)))
.digest('hex');
}
function mutationId(
generationDigest: string,
taskId: string,
disposition: 'created' | 'disabled' | 'updated',
): string {
const value = createHash('sha256')
.update(MUTATION_ID_DOMAIN)
.update(generationDigest)
.update('\0')
.update(taskId)
.update('\0')
.update(disposition)
.digest('hex')
.slice(0, 32);
return `${value.slice(0, 8)}-${value.slice(8, 12)}-4${value.slice(13, 16)}-a${value.slice(17, 20)}-${value.slice(20)}`;
}
function normalizeItem(
value: PluginPackageTaskReconciliationItem,
): Readonly<PluginPackageTaskReconciliationItem> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('item must be an object');
}
exactKeys(
value,
['contentDigest', 'disposition', 'revision', 'taskId'],
[],
'item',
);
if (!ITEM_DISPOSITIONS.includes(value.disposition)) {
return invalid('item disposition is invalid');
}
return Object.freeze({
taskId: identifier(value.taskId, 'item.taskId'),
revision: integer(value.revision, 'item.revision', 1),
disposition: value.disposition,
contentDigest: digest(value.contentDigest, 'item.contentDigest'),
});
}
export function normalizePluginPackageTaskReconciliationReceipt(
value: PluginPackageTaskReconciliationReceipt,
): Readonly<PluginPackageTaskReconciliationReceipt> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('receipt must be an object');
}
exactKeys(
value,
[
'committedAtMs',
'generation',
'generationDigest',
'items',
'lockDigest',
'materializedRevisionDigest',
'packageName',
'previousLockDigest',
'projectId',
'receiptDigest',
'schema',
],
[],
'receipt',
);
if (value.schema !== PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA) {
return invalid('receipt schema is invalid');
}
if (typeof value.packageName !== 'string' || !PACKAGE_NAME.test(value.packageName)) {
return invalid('packageName is invalid');
}
const items = denseItems(value.items).map((item) =>
normalizeItem(item as PluginPackageTaskReconciliationItem),
);
if (
items.some(
(item, index) =>
index > 0 && items[index - 1]!.taskId.localeCompare(item.taskId) >= 0,
)
) {
return invalid('items must be uniquely sorted by taskId');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA,
projectId: identifier(value.projectId, 'projectId'),
packageName: value.packageName,
generation: integer(value.generation, 'generation', 1),
generationDigest: digest(value.generationDigest, 'generationDigest'),
materializedRevisionDigest: digest(
value.materializedRevisionDigest,
'materializedRevisionDigest',
),
lockDigest: digest(value.lockDigest, 'lockDigest'),
previousLockDigest:
value.previousLockDigest === null
? null
: digest(value.previousLockDigest, 'previousLockDigest'),
committedAtMs: integer(value.committedAtMs, 'committedAtMs', 0),
items: Object.freeze(items),
receiptDigest: digest(value.receiptDigest, 'receiptDigest'),
});
if (
normalized.receiptDigest !==
pluginPackageTaskReconciliationReceiptDigest(normalized)
) {
return invalid('receipt digest did not match');
}
return normalized;
}
function semanticDigest(
draft: Readonly<PluginPackageTaskDefinitionDraft>,
revision: number,
): string {
return taskDefinitionContentDigest({
projectId: draft.projectId,
taskId: draft.taskId,
revision,
name: draft.name,
...(draft.description === undefined
? {}
: { description: draft.description }),
kind: draft.kind,
spec: draft.spec,
labels: draft.labels,
enabled: draft.enabled,
});
}
function writeForDraft(
draft: Readonly<PluginPackageTaskDefinitionDraft>,
current: Readonly<TaskDefinitionRecord> | null,
generationDigest: string,
committedAtMs: number,
disposition: 'created' | 'updated',
): Readonly<PluginPackageTaskReconciliationWrite> {
const command = Object.freeze({
projectId: draft.projectId,
taskId: draft.taskId,
expectedRevision: current?.revision ?? null,
mutationId: mutationId(generationDigest, draft.taskId, disposition),
name: draft.name,
...(draft.description === undefined
? {}
: { description: draft.description }),
kind: draft.kind,
spec: draft.spec,
labels: draft.labels,
enabled: draft.enabled,
occurredAtMs: committedAtMs,
});
return Object.freeze({
command,
definition: createTaskDefinitionRecord(command, current?.createdAtMs ?? committedAtMs),
});
}
function disableWrite(
current: Readonly<TaskDefinitionRecord>,
generationDigest: string,
committedAtMs: number,
): Readonly<PluginPackageTaskReconciliationWrite> {
const command = Object.freeze({
projectId: current.projectId,
taskId: current.taskId,
expectedRevision: current.revision,
mutationId: mutationId(generationDigest, current.taskId, 'disabled'),
name: current.name,
...(current.description === undefined
? {}
: { description: current.description }),
kind: current.kind,
spec: current.spec,
labels: current.labels,
enabled: false,
occurredAtMs: committedAtMs,
});
return Object.freeze({
command,
definition: createTaskDefinitionRecord(command, current.createdAtMs),
});
}
export function pluginPackageTaskReconciliationTaskIds(
revisionValue: Readonly<PluginPackageMaterializedRevision>,
previousReceipt: Readonly<PluginPackageTaskReconciliationReceipt> | null,
registry: TaskSpecSemanticRegistry,
): readonly string[] {
const revision = normalizePluginPackageMaterializedRevision(revisionValue, registry);
const previous =
previousReceipt === null
? null
: normalizePluginPackageTaskReconciliationReceipt(previousReceipt);
return Object.freeze(
[...new Set([
...pluginPackageTaskDefinitionDrafts(revision, registry).map(
(draft) => draft.taskId,
),
...(previous?.items.map((item) => item.taskId) ?? []),
])].sort(),
);
}
export function planPluginPackageTaskReconciliation(
input: PlanPluginPackageTaskReconciliationInput,
): Readonly<PluginPackageTaskReconciliationPlan> {
if (
!input ||
typeof input !== 'object' ||
Array.isArray(input) ||
!(input.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)
) {
return invalid('plan input is invalid');
}
const revision = normalizePluginPackageMaterializedRevision(
input.revision,
input.taskSpecSemanticRegistry,
);
const generation = revision.generation;
const previous =
input.previousReceipt === null
? null
: normalizePluginPackageTaskReconciliationReceipt(input.previousReceipt);
const committedAtMs = integer(input.committedAtMs, 'committedAtMs', 0);
if (
(generation.generation === 1 && previous !== null) ||
(generation.generation > 1 &&
(previous === null ||
previous.projectId !== generation.projectId ||
previous.packageName !== generation.packageName ||
previous.generation !== generation.generation - 1 ||
previous.lockDigest !== generation.previousActiveLockDigest))
) {
return conflict('previous generation receipt chain is incomplete');
}
if (!Array.isArray(input.facts)) return invalid('facts are invalid');
const drafts = pluginPackageTaskDefinitionDrafts(
revision,
input.taskSpecSemanticRegistry,
);
const taskIds = pluginPackageTaskReconciliationTaskIds(
revision,
previous,
input.taskSpecSemanticRegistry,
);
if (taskIds.length > MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS) {
return invalid('task set exceeds its item budget');
}
const facts = new Map<string, Readonly<PluginPackageTaskOwnershipFact>>();
for (const value of input.facts) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('fact is invalid');
}
exactKeys(value, ['current', 'packageName', 'taskId'], [], 'fact');
const taskId = identifier(value.taskId, 'fact.taskId');
if (facts.has(taskId) || !taskIds.includes(taskId)) {
return invalid('facts must exactly and uniquely cover the task set');
}
if (
value.packageName !== null &&
(typeof value.packageName !== 'string' ||
!PACKAGE_NAME.test(value.packageName))
) {
return invalid('fact packageName is invalid');
}
const current =
value.current === null ? null : normalizeTaskDefinitionRecord(value.current);
if (
current !== null &&
(current.projectId !== generation.projectId || current.taskId !== taskId)
) {
return invalid('fact current definition identity is invalid');
}
facts.set(taskId, Object.freeze({ taskId, packageName: value.packageName, current }));
}
if (facts.size !== taskIds.length) {
return invalid('facts do not exactly cover the task set');
}
const draftById = new Map(drafts.map((draft) => [draft.taskId, draft]));
const previousById = new Map(previous?.items.map((item) => [item.taskId, item]) ?? []);
const items: PluginPackageTaskReconciliationItem[] = [];
const writes: PluginPackageTaskReconciliationWrite[] = [];
for (const taskId of taskIds) {
const fact = facts.get(taskId)!;
const draft = draftById.get(taskId);
const previousItem = previousById.get(taskId);
if (fact.packageName !== null && fact.packageName !== generation.packageName) {
return conflict(`TaskDefinition ${taskId} belongs to another Package`);
}
if (fact.current !== null && fact.packageName === null) {
return conflict(`TaskDefinition ${taskId} exists without Package ownership`);
}
if (
previousItem &&
(fact.current === null ||
fact.packageName !== generation.packageName ||
fact.current.revision !== previousItem.revision ||
fact.current.contentDigest !== previousItem.contentDigest)
) {
return conflict(`TaskDefinition ${taskId} changed outside reconciliation`);
}
if (draft) {
if (fact.current === null) {
const write = writeForDraft(
draft,
null,
generation.generationDigest,
committedAtMs,
'created',
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'created',
contentDigest: write.definition.contentDigest,
});
} else if (
semanticDigest(draft, fact.current.revision) === fact.current.contentDigest
) {
items.push({
taskId,
revision: fact.current.revision,
disposition: 'retained',
contentDigest: fact.current.contentDigest,
});
} else {
const write = writeForDraft(
draft,
fact.current,
generation.generationDigest,
committedAtMs,
'updated',
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'updated',
contentDigest: write.definition.contentDigest,
});
}
} else if (fact.current === null || !fact.current.enabled) {
if (fact.current !== null) {
items.push({
taskId,
revision: fact.current.revision,
disposition: 'already_disabled',
contentDigest: fact.current.contentDigest,
});
}
} else {
const write = disableWrite(
fact.current,
generation.generationDigest,
committedAtMs,
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'disabled',
contentDigest: write.definition.contentDigest,
});
}
}
items.sort((left, right) => left.taskId.localeCompare(right.taskId));
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA,
projectId: generation.projectId,
packageName: generation.packageName,
generation: generation.generation,
generationDigest: generation.generationDigest,
materializedRevisionDigest: revision.revisionDigest,
lockDigest: generation.lockDigest,
previousLockDigest: generation.previousActiveLockDigest,
committedAtMs,
items: Object.freeze(items.map((item) => Object.freeze(item))),
});
return Object.freeze({
receipt: normalizePluginPackageTaskReconciliationReceipt(
Object.freeze({
...unsigned,
receiptDigest: pluginPackageTaskReconciliationReceiptDigest(unsigned),
}),
),
writes: Object.freeze(writes),
});
}
@@ -0,0 +1,722 @@
import { createHash } from 'node:crypto';
import type { PluginPackagePublisherSignatureEvidence } from '../pluginPackageBundle';
import {
SECURITY_SUBJECT_TYPES,
type SecuritySubject,
} from '../../security/security';
export const PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA =
'qinglong/plugin-package-publisher-provenance@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-receipt@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-impact@v1' as const;
export const MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS = 4096;
export interface PluginPackagePublisherProvenance {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly stageEvidenceDigest: string;
readonly publisher: string;
readonly keyId: string;
readonly signatureDigest: string;
readonly keyNotBeforeMs: number;
readonly keyNotAfterMs: number;
readonly verifiedAtMs: number;
readonly provenanceDigest: string;
}
export interface CreatePluginPackagePublisherProvenanceInput {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly stageEvidenceDigest: string;
readonly signature: Readonly<PluginPackagePublisherSignatureEvidence>;
}
export type PluginPackagePublisherRevocationAuthorizationMode =
| 'dual_control'
| 'break_glass';
export type PluginPackagePublisherRevocationReason =
| 'suspected_key_compromise'
| 'confirmed_key_compromise';
export interface PluginPackagePublisherRevocationReceipt {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA;
readonly mutationId: string;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
readonly revokedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackagePublisherRevocationReceiptInput = Omit<
PluginPackagePublisherRevocationReceipt,
'receiptDigest' | 'schema'
>;
export interface PluginPackagePublisherRevocationImpactItem {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly provenanceDigest: string;
}
export interface PluginPackagePublisherRevocationImpact {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA;
readonly revocationReceiptDigest: string;
readonly items: readonly Readonly<PluginPackagePublisherRevocationImpactItem>[];
readonly generatedAtMs: number;
readonly impactDigest: string;
}
export type CreatePluginPackagePublisherRevocationImpactInput = Omit<
PluginPackagePublisherRevocationImpact,
'impactDigest' | 'schema'
>;
export class InvalidPluginPackagePublisherProvenanceError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_INVALID';
constructor(message: string) {
super(`Plugin Package publisher provenance is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherProvenanceError';
}
}
export class PluginPackagePublisherProvenanceConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_CONFLICT';
constructor(message: string) {
super(`Plugin Package publisher provenance conflicts with durable state: ${message}`);
this.name = 'PluginPackagePublisherProvenanceConflictError';
}
}
export class PluginPackagePublisherProvenanceUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package publisher provenance is unavailable', options);
this.name = 'PluginPackagePublisherProvenanceUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PROVENANCE_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-provenance-digest@v1\0';
const REVOCATION_RECEIPT_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-key-revocation-receipt-digest@v1\0';
const REVOCATION_IMPACT_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-key-revocation-impact-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherProvenanceError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('projectId is invalid');
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME_PATTERN.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function subject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const record = dataRecord(value, label);
exactKeys(record, ['id', 'type'], label);
if (
typeof value.type !== 'string' ||
!SECURITY_SUBJECT_TYPES.includes(
value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
) ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid(`${label} is invalid`);
}
return Object.freeze({
type: value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
id: value.id,
});
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function provenanceFields(
value: Omit<PluginPackagePublisherProvenance, 'provenanceDigest'>,
): object {
return {
schema: value.schema,
projectId: value.projectId,
packageName: value.packageName,
installationId: value.installationId,
lockDigest: value.lockDigest,
artifactDigest: value.artifactDigest,
manifestDigest: value.manifestDigest,
contentDigest: value.contentDigest,
stageEvidenceDigest: value.stageEvidenceDigest,
publisher: value.publisher,
keyId: value.keyId,
signatureDigest: value.signatureDigest,
keyNotBeforeMs: value.keyNotBeforeMs,
keyNotAfterMs: value.keyNotAfterMs,
verifiedAtMs: value.verifiedAtMs,
};
}
export function pluginPackagePublisherProvenanceDigest(
value: Omit<PluginPackagePublisherProvenance, 'provenanceDigest'>,
): string {
return createHash('sha256')
.update(PROVENANCE_DIGEST_DOMAIN)
.update(JSON.stringify(provenanceFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherProvenance(
value: PluginPackagePublisherProvenance,
): Readonly<PluginPackagePublisherProvenance> {
const record = dataRecord(value, 'provenance');
exactKeys(
record,
[
'artifactDigest',
'contentDigest',
'installationId',
'keyId',
'keyNotAfterMs',
'keyNotBeforeMs',
'lockDigest',
'manifestDigest',
'packageName',
'projectId',
'provenanceDigest',
'publisher',
'schema',
'signatureDigest',
'stageEvidenceDigest',
'verifiedAtMs',
],
'provenance',
);
if (value.schema !== PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA) {
return invalid('provenance schema is invalid');
}
const keyNotBeforeMs = timestamp(value.keyNotBeforeMs, 'keyNotBeforeMs');
const keyNotAfterMs = timestamp(value.keyNotAfterMs, 'keyNotAfterMs');
const verifiedAtMs = timestamp(value.verifiedAtMs, 'verifiedAtMs');
if (
keyNotAfterMs <= keyNotBeforeMs ||
verifiedAtMs < keyNotBeforeMs ||
verifiedAtMs >= keyNotAfterMs
) {
return invalid('signature verification time is outside key validity');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA,
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
artifactDigest: digest(value.artifactDigest, 'artifactDigest'),
manifestDigest: digest(value.manifestDigest, 'manifestDigest'),
contentDigest: digest(value.contentDigest, 'contentDigest'),
stageEvidenceDigest: digest(
value.stageEvidenceDigest,
'stageEvidenceDigest',
),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
signatureDigest: digest(value.signatureDigest, 'signatureDigest'),
keyNotBeforeMs,
keyNotAfterMs,
verifiedAtMs,
});
const provenanceDigest = pluginPackagePublisherProvenanceDigest(normalized);
if (value.provenanceDigest !== provenanceDigest) {
return invalid('provenanceDigest does not match provenance');
}
return Object.freeze({ ...normalized, provenanceDigest });
}
export function createPluginPackagePublisherProvenance(
input: CreatePluginPackagePublisherProvenanceInput,
): Readonly<PluginPackagePublisherProvenance> {
const value = dataRecord(input, 'provenance input');
exactKeys(
value,
[
'artifactDigest',
'contentDigest',
'installationId',
'lockDigest',
'manifestDigest',
'packageName',
'projectId',
'signature',
'stageEvidenceDigest',
],
'provenance input',
);
const signature = dataRecord(input.signature, 'signature evidence');
exactKeys(
signature,
[
'keyId',
'keyNotAfterMs',
'keyNotBeforeMs',
'publisher',
'signatureDigest',
'verifiedAtMs',
],
'signature evidence',
);
const unsigned: Omit<
PluginPackagePublisherProvenance,
'provenanceDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA,
projectId: projectId(input.projectId),
packageName: packageName(input.packageName),
installationId: identifier(input.installationId, 'installationId'),
lockDigest: digest(input.lockDigest, 'lockDigest'),
artifactDigest: digest(input.artifactDigest, 'artifactDigest'),
manifestDigest: digest(input.manifestDigest, 'manifestDigest'),
contentDigest: digest(input.contentDigest, 'contentDigest'),
stageEvidenceDigest: digest(
input.stageEvidenceDigest,
'stageEvidenceDigest',
),
publisher: publisher(input.signature.publisher),
keyId: identifier(input.signature.keyId, 'keyId'),
signatureDigest: digest(
input.signature.signatureDigest,
'signatureDigest',
),
keyNotBeforeMs: timestamp(
input.signature.keyNotBeforeMs,
'keyNotBeforeMs',
),
keyNotAfterMs: timestamp(
input.signature.keyNotAfterMs,
'keyNotAfterMs',
),
verifiedAtMs: timestamp(input.signature.verifiedAtMs, 'verifiedAtMs'),
};
return normalizePluginPackagePublisherProvenance({
...unsigned,
provenanceDigest: pluginPackagePublisherProvenanceDigest(unsigned),
});
}
function revocationReceiptFields(
value: Omit<PluginPackagePublisherRevocationReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
mutationId: value.mutationId,
publisher: value.publisher,
keyId: value.keyId,
previousTrustDigest: value.previousTrustDigest,
currentTrustDigest: value.currentTrustDigest,
proposer: value.proposer,
confirmer: value.confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
revokedAtMs: value.revokedAtMs,
};
}
export function pluginPackagePublisherRevocationReceiptDigest(
value: Omit<PluginPackagePublisherRevocationReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(REVOCATION_RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(revocationReceiptFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherRevocationReceipt(
value: PluginPackagePublisherRevocationReceipt,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const record = dataRecord(value, 'revocation receipt');
exactKeys(
record,
[
'authorizationMode',
'confirmer',
'currentTrustDigest',
'keyId',
'mutationId',
'previousTrustDigest',
'proposer',
'publisher',
'reasonCode',
'receiptDigest',
'revokedAtMs',
'schema',
],
'revocation receipt',
);
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA ||
(value.authorizationMode !== 'dual_control' &&
value.authorizationMode !== 'break_glass') ||
(value.reasonCode !== 'suspected_key_compromise' &&
value.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('revocation receipt classification is invalid');
}
const proposer = subject(value.proposer, 'proposer');
const confirmer = subject(value.confirmer, 'confirmer');
if (
value.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('revocation must change the publisher trust digest');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
proposer,
confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
revokedAtMs: timestamp(value.revokedAtMs, 'revokedAtMs'),
});
const receiptDigest =
pluginPackagePublisherRevocationReceiptDigest(normalized);
if (value.receiptDigest !== receiptDigest) {
return invalid('receiptDigest does not match revocation receipt');
}
return Object.freeze({ ...normalized, receiptDigest });
}
export function createPluginPackagePublisherRevocationReceipt(
input: CreatePluginPackagePublisherRevocationReceiptInput,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const value = dataRecord(input, 'revocation receipt input');
exactKeys(
value,
[
'authorizationMode',
'confirmer',
'currentTrustDigest',
'keyId',
'mutationId',
'previousTrustDigest',
'proposer',
'publisher',
'reasonCode',
'revokedAtMs',
],
'revocation receipt input',
);
const unsigned: Omit<
PluginPackagePublisherRevocationReceipt,
'receiptDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA,
mutationId: input.mutationId,
publisher: input.publisher,
keyId: input.keyId,
previousTrustDigest: input.previousTrustDigest,
currentTrustDigest: input.currentTrustDigest,
proposer: input.proposer,
confirmer: input.confirmer,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
revokedAtMs: input.revokedAtMs,
};
return normalizePluginPackagePublisherRevocationReceipt({
...unsigned,
receiptDigest: pluginPackagePublisherRevocationReceiptDigest(unsigned),
});
}
function compareImpactItems(
left: Readonly<PluginPackagePublisherRevocationImpactItem>,
right: Readonly<PluginPackagePublisherRevocationImpactItem>,
): number {
return (
Buffer.compare(
Buffer.from(left.projectId, 'utf8'),
Buffer.from(right.projectId, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.packageName, 'utf8'),
Buffer.from(right.packageName, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.installationId, 'utf8'),
Buffer.from(right.installationId, 'utf8'),
) ||
left.lockDigest.localeCompare(right.lockDigest)
);
}
function normalizeImpactItem(
value: PluginPackagePublisherRevocationImpactItem,
): Readonly<PluginPackagePublisherRevocationImpactItem> {
const record = dataRecord(value, 'impact item');
exactKeys(
record,
[
'installationId',
'lockDigest',
'packageName',
'projectId',
'provenanceDigest',
],
'impact item',
);
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
provenanceDigest: digest(value.provenanceDigest, 'provenanceDigest'),
});
}
function impactFields(
value: Omit<PluginPackagePublisherRevocationImpact, 'impactDigest'>,
): object {
return {
schema: value.schema,
revocationReceiptDigest: value.revocationReceiptDigest,
items: value.items,
generatedAtMs: value.generatedAtMs,
};
}
export function pluginPackagePublisherRevocationImpactDigest(
value: Omit<PluginPackagePublisherRevocationImpact, 'impactDigest'>,
): string {
return createHash('sha256')
.update(REVOCATION_IMPACT_DIGEST_DOMAIN)
.update(JSON.stringify(impactFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherRevocationImpact(
value: PluginPackagePublisherRevocationImpact,
): Readonly<PluginPackagePublisherRevocationImpact> {
const record = dataRecord(value, 'revocation impact');
exactKeys(
record,
[
'generatedAtMs',
'impactDigest',
'items',
'revocationReceiptDigest',
'schema',
],
'revocation impact',
);
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA ||
!Array.isArray(value.items) ||
value.items.length > MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS ||
Object.keys(value.items).some((key, index) => key !== String(index))
) {
return invalid('revocation impact schema or items are invalid');
}
const items = Object.freeze(value.items.map(normalizeImpactItem));
if (
items.some(
(item, index) =>
index > 0 && compareImpactItems(items[index - 1]!, item) >= 0,
) ||
new Set(items.map((item) => item.provenanceDigest)).size !== items.length ||
new Set(items.map((item) => item.installationId)).size !== items.length
) {
return invalid('revocation impact items must be unique and sorted');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA,
revocationReceiptDigest: digest(
value.revocationReceiptDigest,
'revocationReceiptDigest',
),
items,
generatedAtMs: timestamp(value.generatedAtMs, 'generatedAtMs'),
});
const impactDigest =
pluginPackagePublisherRevocationImpactDigest(normalized);
if (value.impactDigest !== impactDigest) {
return invalid('impactDigest does not match revocation impact');
}
return Object.freeze({ ...normalized, impactDigest });
}
export function createPluginPackagePublisherRevocationImpact(
input: CreatePluginPackagePublisherRevocationImpactInput,
): Readonly<PluginPackagePublisherRevocationImpact> {
const value = dataRecord(input, 'revocation impact input');
exactKeys(
value,
['generatedAtMs', 'items', 'revocationReceiptDigest'],
'revocation impact input',
);
if (
!Array.isArray(input.items) ||
input.items.length >
MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS ||
Object.keys(input.items).some((key, index) => key !== String(index))
) {
return invalid('revocation impact items are invalid');
}
const items = Object.freeze(
input.items.map(normalizeImpactItem).sort(compareImpactItems),
);
const unsigned: Omit<
PluginPackagePublisherRevocationImpact,
'impactDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA,
revocationReceiptDigest: input.revocationReceiptDigest,
items,
generatedAtMs: input.generatedAtMs,
};
return normalizePluginPackagePublisherRevocationImpact({
...unsigned,
impactDigest: pluginPackagePublisherRevocationImpactDigest(unsigned),
});
}
@@ -0,0 +1,589 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
createPluginPackagePublisherRevocationReceipt,
type PluginPackagePublisherRevocationAuthorizationMode,
type PluginPackagePublisherRevocationReason,
type PluginPackagePublisherRevocationReceipt,
} from './pluginPackagePublisherProvenance';
import {
normalizePluginPackagePublisherTrustSnapshot,
pluginPackagePublisherTrustRevokedDigest,
type PluginPackagePublisherTrustSnapshot,
} from './pluginPackagePublisherTrust';
import { normalizeProjectPolicySubject } from '../../security/project-policy/projectPolicy';
import {
SECURITY_AUTHENTICATION_ASSURANCES,
type SecurityAuthenticationAssurance,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../security/security';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-proposal@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE =
'plugin_package.publisher_key.revoke' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION =
'package.manage' as const;
export interface PluginPackagePublisherRevocationActionInput {
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
}
export interface PluginPackagePublisherRevocationProposal {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE;
readonly permission: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION;
readonly actionInput: Readonly<PluginPackagePublisherRevocationActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposerAssurance: SecurityAuthenticationAssurance;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface CreatePluginPackagePublisherRevocationProposalInput {
readonly actionRef: string;
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly trustSnapshot: PluginPackagePublisherTrustSnapshot;
readonly publisher: string;
readonly keyId: string;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
readonly proposedBy: SecuritySubject;
readonly proposerAssurance: SecurityAuthenticationAssurance;
readonly proposalFence: SecurityPolicyFence;
readonly createdAtMs: number;
}
export interface CreatePluginPackagePublisherRevocationProposalCommand {
readonly proposal: PluginPackagePublisherRevocationProposal;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackagePublisherRevocationProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackagePublisherRevocationProposal>;
}
export interface PluginPackagePublisherRevocationProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackagePublisherRevocationProposal> | null>;
createProposal(
command: CreatePluginPackagePublisherRevocationProposalCommand,
): Promise<
Readonly<CreatePluginPackagePublisherRevocationProposalResult>
>;
}
export class InvalidPluginPackagePublisherRevocationProposalError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_INVALID';
constructor(message: string) {
super(
`Plugin Package publisher revocation proposal is invalid: ${message}`,
);
this.name =
'InvalidPluginPackagePublisherRevocationProposalError';
}
}
export class PluginPackagePublisherRevocationProposalBindingConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_BINDING_CONFLICT';
constructor() {
super(
'Plugin Package publisher revocation proposal does not match its dispatch',
);
this.name =
'PluginPackagePublisherRevocationProposalBindingConflictError';
}
}
export class PluginPackagePublisherRevocationProposalConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_CONFLICT';
constructor() {
super(
'Plugin Package publisher revocation proposal conflicts with durable authority',
);
this.name =
'PluginPackagePublisherRevocationProposalConflictError';
}
}
export class PluginPackagePublisherRevocationProposalUnavailableError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super(
'Plugin Package publisher revocation proposal authority is unavailable',
options,
);
this.name =
'PluginPackagePublisherRevocationProposalUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherRevocationProposalError(message);
}
function dataRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('authorityProjectId is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function authorizationMode(
value: unknown,
): PluginPackagePublisherRevocationAuthorizationMode {
if (value !== 'dual_control' && value !== 'break_glass') {
return invalid('authorizationMode is invalid');
}
return value;
}
function reasonCode(
value: unknown,
): PluginPackagePublisherRevocationReason {
if (
value !== 'suspected_key_compromise' &&
value !== 'confirmed_key_compromise'
) {
return invalid('reasonCode is invalid');
}
return value;
}
function assurance(value: unknown): SecurityAuthenticationAssurance {
if (
typeof value !== 'string' ||
!SECURITY_AUTHENTICATION_ASSURANCES.includes(
value as SecurityAuthenticationAssurance,
)
) {
return invalid('proposerAssurance is invalid');
}
return value as SecurityAuthenticationAssurance;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function normalizeActionInput(
value: PluginPackagePublisherRevocationActionInput,
): Readonly<PluginPackagePublisherRevocationActionInput> {
const record = dataRecord(value, 'action input');
exactKeys(
record,
[
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
'authorizationMode',
'reasonCode',
],
'action input',
);
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('revocation must change the trust digest');
}
return Object.freeze({
authorityProjectId: projectId(value.authorityProjectId),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
trustGeneration: positiveInteger(
value.trustGeneration,
'trustGeneration',
),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
authorizationMode: authorizationMode(value.authorizationMode),
reasonCode: reasonCode(value.reasonCode),
});
}
export function pluginPackagePublisherRevocationActionDigest(
value: PluginPackagePublisherRevocationActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-key-revocation-action-digest@v1',
normalizeActionInput(value),
);
}
export function pluginPackagePublisherRevocationPreviewDigest(
value: PluginPackagePublisherRevocationActionInput,
): string {
const input = normalizeActionInput(value);
return contractDigest(
'qinglong/plugin-package-publisher-key-revocation-preview-digest@v1',
{
authorityProjectId: input.authorityProjectId,
trustAuthorityId: input.trustAuthorityId,
trustGeneration: input.trustGeneration,
publisher: input.publisher,
keyId: input.keyId,
previousTrustDigest: input.previousTrustDigest,
currentTrustDigest: input.currentTrustDigest,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
},
);
}
function withProposalDigest(
value: Omit<
PluginPackagePublisherRevocationProposal,
'proposalDigest'
>,
): Readonly<PluginPackagePublisherRevocationProposal> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-publisher-key-revocation-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackagePublisherRevocationProposal(
inputValue: CreatePluginPackagePublisherRevocationProposalInput,
): Readonly<PluginPackagePublisherRevocationProposal> {
const input = dataRecord(inputValue, 'proposal input');
exactKeys(
input,
[
'actionRef',
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'trustSnapshot',
'publisher',
'keyId',
'authorizationMode',
'reasonCode',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
],
'proposal input',
);
const trustSnapshot = normalizePluginPackagePublisherTrustSnapshot(
inputValue.trustSnapshot,
);
const actionInput = normalizeActionInput({
authorityProjectId: inputValue.authorityProjectId,
trustAuthorityId: inputValue.trustAuthorityId,
trustGeneration: inputValue.trustGeneration,
publisher: inputValue.publisher,
keyId: inputValue.keyId,
previousTrustDigest: trustSnapshot.snapshotDigest,
currentTrustDigest: pluginPackagePublisherTrustRevokedDigest(
trustSnapshot,
inputValue.publisher,
inputValue.keyId,
),
authorizationMode: inputValue.authorizationMode,
reasonCode: inputValue.reasonCode,
});
const proposerAssurance = assurance(inputValue.proposerAssurance);
if (
actionInput.authorizationMode === 'break_glass' &&
proposerAssurance !== 'hardware'
) {
return invalid('break-glass proposer must use hardware assurance');
}
const proposedBy = normalizeProjectPolicySubject(inputValue.proposedBy);
return withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.authorityProjectId,
actionType: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE,
permission: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherRevocationActionDigest(actionInput),
previewDigest:
pluginPackagePublisherRevocationPreviewDigest(actionInput),
proposedBy,
proposerAssurance,
proposalFence: normalizeApprovedActionFence(
inputValue.proposalFence,
),
createdAtMs: timestamp(inputValue.createdAtMs, 'createdAtMs'),
});
}
export function normalizePluginPackagePublisherRevocationProposal(
value: PluginPackagePublisherRevocationProposal,
): Readonly<PluginPackagePublisherRevocationProposal> {
const record = dataRecord(value, 'proposal');
exactKeys(
record,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA ||
value.actionType !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE ||
value.permission !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION
) {
return invalid('schema or action authority is invalid');
}
const actionInput = normalizeActionInput(value.actionInput);
const proposedBy = normalizeProjectPolicySubject(value.proposedBy);
const proposerAssurance = assurance(value.proposerAssurance);
if (
actionInput.authorizationMode === 'break_glass' &&
proposerAssurance !== 'hardware'
) {
return invalid('break-glass proposer must use hardware assurance');
}
const normalized = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA,
actionRef: actionRef(value.actionRef),
projectId: projectId(value.projectId),
actionType: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE,
permission: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherRevocationActionDigest(actionInput),
previewDigest:
pluginPackagePublisherRevocationPreviewDigest(actionInput),
proposedBy,
proposerAssurance,
proposalFence: normalizeApprovedActionFence(value.proposalFence),
createdAtMs: timestamp(value.createdAtMs, 'createdAtMs'),
});
if (
normalized.projectId !== actionInput.authorityProjectId ||
digest(value.actionDigest, 'actionDigest') !==
normalized.actionDigest ||
digest(value.previewDigest, 'previewDigest') !==
normalized.previewDigest ||
digest(value.proposalDigest, 'proposalDigest') !==
normalized.proposalDigest
) {
return invalid('proposal digest or derived binding is invalid');
}
return normalized;
}
export function resolvePluginPackagePublisherRevocationProposal(
proposalValue: PluginPackagePublisherRevocationProposal,
dispatchValue: ApprovedActionDispatchRecord,
revokedAtMsValue: number,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const proposal =
normalizePluginPackagePublisherRevocationProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const revokedAtMs = timestamp(revokedAtMsValue, 'revokedAtMs');
const action = proposal.actionInput;
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
!sameSubject(dispatch.requestedBy, proposal.proposedBy) ||
dispatch.createdAtMs < proposal.createdAtMs ||
revokedAtMs < dispatch.createdAtMs ||
revokedAtMs >= dispatch.expiresAtMs ||
(action.authorizationMode === 'dual_control' &&
sameSubject(dispatch.requestedBy, dispatch.approvedBy)) ||
(action.authorizationMode === 'break_glass' &&
(proposal.proposerAssurance !== 'hardware' ||
dispatch.approvalAssurance !== 'hardware'))
) {
throw new PluginPackagePublisherRevocationProposalBindingConflictError();
}
return createPluginPackagePublisherRevocationReceipt({
mutationId: dispatch.id,
publisher: action.publisher,
keyId: action.keyId,
previousTrustDigest: action.previousTrustDigest,
currentTrustDigest: action.currentTrustDigest,
proposer: proposal.proposedBy,
confirmer: dispatch.approvedBy,
authorizationMode: action.authorizationMode,
reasonCode: action.reasonCode,
revokedAtMs,
});
}
@@ -0,0 +1,604 @@
import { createHash, createPublicKey } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_PUBLISHER_KEYS,
PluginPackagePublisherTrustRegistry,
type PluginPackagePublisherKeyDefinition,
} from '../pluginPackageBundle';
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA =
'qinglong/plugin-package-publisher-trust-snapshot@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA =
'qinglong/plugin-package-publisher-trust-head@v1' as const;
export interface PluginPackagePublisherTrustSnapshotKey {
readonly publisher: string;
readonly keyId: string;
readonly publicKeyDigest: string;
readonly notBeforeMs: number;
readonly notAfterMs: number;
}
export interface PluginPackagePublisherTrustSnapshot {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA;
readonly keys: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[];
readonly snapshotDigest: string;
}
export interface PluginPackagePublisherTrustKeyRef {
readonly publisher: string;
readonly keyId: string;
}
export interface PluginPackagePublisherTrustHead {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA;
readonly authorityId: string;
readonly generation: number;
readonly baseSnapshotDigest: string;
readonly effectiveTrustDigest: string;
readonly updatedAtMs: number;
readonly headDigest: string;
}
export interface PluginPackagePublisherTrustAuthorityState {
readonly head: Readonly<PluginPackagePublisherTrustHead>;
readonly effectiveSnapshot: Readonly<PluginPackagePublisherTrustSnapshot>;
}
export interface ObservePluginPackagePublisherTrustSnapshotInput {
readonly authorityId: string;
readonly snapshot: PluginPackagePublisherTrustSnapshot;
readonly observedBy: string;
readonly observedAtMs: number;
}
export interface ObservePluginPackagePublisherTrustSnapshotResult
extends PluginPackagePublisherTrustAuthorityState {
readonly status: 'created' | 'existing' | 'candidate';
}
export interface PluginPackagePublisherTrustAuthorityRepository {
findAuthority(
authorityId: string,
): Promise<Readonly<PluginPackagePublisherTrustAuthorityState> | null>;
observeSnapshot(
input: ObservePluginPackagePublisherTrustSnapshotInput,
): Promise<Readonly<ObservePluginPackagePublisherTrustSnapshotResult>>;
}
export class InvalidPluginPackagePublisherTrustSnapshotError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_INVALID';
constructor(message: string) {
super(`Plugin Package publisher trust snapshot is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherTrustSnapshotError';
}
}
export class PluginPackagePublisherTrustAuthorityConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_AUTHORITY_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust snapshot conflicts with durable authority',
);
this.name = 'PluginPackagePublisherTrustAuthorityConflictError';
}
}
export class PluginPackagePublisherTrustAuthorityUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_AUTHORITY_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package publisher trust authority is unavailable', options);
this.name = 'PluginPackagePublisherTrustAuthorityUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const TRUST_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-trust-keyset-digest@v1\0';
const TRUST_HEAD_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-trust-head-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherTrustSnapshotError(message);
}
function exactObject(
value: unknown,
keys: readonly string[],
label: string,
): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const actual = Reflect.ownKeys(value);
const expected = [...keys].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== expected.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== expected[index])
) {
return invalid(`${label} shape is invalid`);
}
return value as Record<string, unknown>;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function keyId(value: unknown): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid('keyId is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function compareKeys(
left: Readonly<PluginPackagePublisherTrustSnapshotKey>,
right: Readonly<PluginPackagePublisherTrustSnapshotKey>,
): number {
return (
Buffer.compare(
Buffer.from(left.publisher, 'utf8'),
Buffer.from(right.publisher, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.keyId, 'utf8'),
Buffer.from(right.keyId, 'utf8'),
)
);
}
function normalizeKey(
value: PluginPackagePublisherTrustSnapshotKey,
): Readonly<PluginPackagePublisherTrustSnapshotKey> {
exactObject(
value,
[
'publisher',
'keyId',
'publicKeyDigest',
'notBeforeMs',
'notAfterMs',
],
'snapshot key',
);
const notBeforeMs = timestamp(value.notBeforeMs, 'notBeforeMs');
const notAfterMs = timestamp(value.notAfterMs, 'notAfterMs');
if (notAfterMs <= notBeforeMs) {
return invalid('key lifetime is invalid');
}
return Object.freeze({
publisher: publisher(value.publisher),
keyId: keyId(value.keyId),
publicKeyDigest: digest(value.publicKeyDigest, 'publicKeyDigest'),
notBeforeMs,
notAfterMs,
});
}
export function pluginPackagePublisherTrustKeysetDigest(
keysValue: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[],
): string {
if (
!Array.isArray(keysValue) ||
Object.keys(keysValue).some((key, index) => key !== String(index))
) {
return invalid('keyset is invalid');
}
const keys = keysValue.map(normalizeKey);
if (
keys.some(
(key, index) => index > 0 && compareKeys(keys[index - 1]!, key) >= 0,
)
) {
return invalid('keyset must be unique and sorted');
}
return createHash('sha256')
.update(TRUST_DIGEST_DOMAIN)
.update(JSON.stringify(keys))
.digest('hex');
}
export function normalizePluginPackagePublisherTrustSnapshot(
value: PluginPackagePublisherTrustSnapshot,
): Readonly<PluginPackagePublisherTrustSnapshot> {
exactObject(value, ['schema', 'keys', 'snapshotDigest'], 'snapshot');
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA ||
!Array.isArray(value.keys) ||
value.keys.length > MAX_PLUGIN_PACKAGE_PUBLISHER_KEYS ||
Object.keys(value.keys).some((key, index) => key !== String(index))
) {
return invalid('snapshot schema or keys are invalid');
}
const keys = Object.freeze(value.keys.map(normalizeKey));
const snapshotDigest = pluginPackagePublisherTrustKeysetDigest(keys);
if (value.snapshotDigest !== snapshotDigest) {
return invalid('snapshotDigest does not match keys');
}
return Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
snapshotDigest,
});
}
export function createPluginPackagePublisherTrustSnapshot(
definitions: readonly Readonly<PluginPackagePublisherKeyDefinition>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
try {
new PluginPackagePublisherTrustRegistry(definitions);
} catch {
return invalid('publisher key definitions are invalid');
}
const keys = Object.freeze(
definitions
.map((definition) => {
let publicKeyDigest: string;
try {
publicKeyDigest = createHash('sha256')
.update(
createPublicKey(definition.publicKeyPem).export({
type: 'spki',
format: 'der',
}),
)
.digest('hex');
} catch {
return invalid('publisher public key is invalid');
}
return normalizeKey({
publisher: definition.publisher,
keyId: definition.keyId,
publicKeyDigest,
notBeforeMs: definition.notBeforeMs,
notAfterMs: definition.notAfterMs,
});
})
.sort(compareKeys),
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
});
return normalizePluginPackagePublisherTrustSnapshot({
...unsigned,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(keys),
});
}
/**
* Treats the mounted document as public-key material only and lets the durable
* effective snapshot decide which identities are trusted. Extra candidate
* keys in the document are deliberately excluded.
*/
export function createPluginPackagePublisherEffectiveTrustRegistry(
definitions: readonly Readonly<PluginPackagePublisherKeyDefinition>[],
effectiveSnapshotValue: PluginPackagePublisherTrustSnapshot,
): PluginPackagePublisherTrustRegistry {
const materialSnapshot =
createPluginPackagePublisherTrustSnapshot(definitions);
const effectiveSnapshot =
normalizePluginPackagePublisherTrustSnapshot(effectiveSnapshotValue);
const definitionsByIdentity = new Map(
definitions.map((definition) => [
`${definition.publisher}\0${definition.keyId}`,
definition,
]),
);
const materialKeys = new Map(
materialSnapshot.keys.map((key) => [
`${key.publisher}\0${key.keyId}`,
Object.freeze({
key,
definition: definitionsByIdentity.get(
`${key.publisher}\0${key.keyId}`,
),
}),
]),
);
const selected: PluginPackagePublisherKeyDefinition[] = [];
for (const effectiveKey of effectiveSnapshot.keys) {
const material = materialKeys.get(
`${effectiveKey.publisher}\0${effectiveKey.keyId}`,
);
if (
!material ||
JSON.stringify(material.key) !== JSON.stringify(effectiveKey) ||
!material.definition
) {
return invalid(
'effective trust snapshot is not backed by mounted key material',
);
}
selected.push({ ...material.definition });
}
if (selected.length < 1) {
return invalid('effective trust snapshot must contain one key');
}
return new PluginPackagePublisherTrustRegistry(selected);
}
function trustSnapshotFromKeys(
keys: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
const canonical = Object.freeze([...keys].sort(compareKeys));
return normalizePluginPackagePublisherTrustSnapshot({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys: canonical,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(canonical),
});
}
export function createPluginPackagePublisherTrustOverlapAdditionSnapshot(
currentValue: PluginPackagePublisherTrustSnapshot,
candidateValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
observedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustSnapshot> {
const current =
normalizePluginPackagePublisherTrustSnapshot(currentValue);
const candidate =
normalizePluginPackagePublisherTrustSnapshot(candidateValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const observedAtMs = timestamp(observedAtMsValue, 'observedAtMs');
const currentKeys = new Map(
current.keys.map((key) => [`${key.publisher}\0${key.keyId}`, key]),
);
const added = candidate.keys.filter(
(key) => !currentKeys.has(`${key.publisher}\0${key.keyId}`),
);
if (
candidate.keys.length !== current.keys.length + 1 ||
current.keys.some((key) => {
const next = candidate.keys.find(
(candidateKey) =>
candidateKey.publisher === key.publisher &&
candidateKey.keyId === key.keyId,
);
return !next || JSON.stringify(next) !== JSON.stringify(key);
}) ||
added.length !== 1 ||
added[0]!.publisher !== targetPublisher ||
added[0]!.keyId !== targetKeyId ||
added[0]!.notBeforeMs > observedAtMs ||
observedAtMs >= added[0]!.notAfterMs
) {
return invalid(
'overlap addition must preserve every key and add one active target',
);
}
return candidate;
}
export function createPluginPackagePublisherTrustRetirementSnapshot(
currentValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
observedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustSnapshot> {
const current =
normalizePluginPackagePublisherTrustSnapshot(currentValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const observedAtMs = timestamp(observedAtMsValue, 'observedAtMs');
const remaining = current.keys.filter(
(key) =>
key.publisher !== targetPublisher || key.keyId !== targetKeyId,
);
if (
remaining.length !== current.keys.length - 1 ||
!remaining.some(
(key) =>
key.publisher === targetPublisher &&
key.notBeforeMs <= observedAtMs &&
observedAtMs < key.notAfterMs,
)
) {
return invalid(
'retirement must remove one target and retain an active publisher key',
);
}
return trustSnapshotFromKeys(remaining);
}
export function createPluginPackagePublisherEffectiveTrustSnapshot(
snapshotValue: PluginPackagePublisherTrustSnapshot,
revokedValue: readonly Readonly<PluginPackagePublisherTrustKeyRef>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
if (
!Array.isArray(revokedValue) ||
Object.keys(revokedValue).some((key, index) => key !== String(index))
) {
return invalid('revoked key references are invalid');
}
const revoked = new Set<string>();
for (const value of revokedValue) {
exactObject(value, ['publisher', 'keyId'], 'revoked key reference');
const identity = `${publisher(value.publisher)}\0${keyId(value.keyId)}`;
if (revoked.has(identity)) {
return invalid('revoked key references must be unique');
}
revoked.add(identity);
}
const keys = Object.freeze(
snapshot.keys.filter(
(key) => !revoked.has(`${key.publisher}\0${key.keyId}`),
),
);
return normalizePluginPackagePublisherTrustSnapshot({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(keys),
});
}
function trustHeadDigest(
value: Omit<PluginPackagePublisherTrustHead, 'headDigest'>,
): string {
return createHash('sha256')
.update(TRUST_HEAD_DIGEST_DOMAIN)
.update(JSON.stringify(value))
.digest('hex');
}
export function normalizePluginPackagePublisherTrustHead(
value: PluginPackagePublisherTrustHead,
): Readonly<PluginPackagePublisherTrustHead> {
exactObject(
value,
[
'schema',
'authorityId',
'generation',
'baseSnapshotDigest',
'effectiveTrustDigest',
'updatedAtMs',
'headDigest',
],
'trust head',
);
if (value.schema !== PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA) {
return invalid('trust head schema is invalid');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: keyId(value.authorityId),
generation: positiveInteger(value.generation, 'generation'),
baseSnapshotDigest: digest(
value.baseSnapshotDigest,
'baseSnapshotDigest',
),
effectiveTrustDigest: digest(
value.effectiveTrustDigest,
'effectiveTrustDigest',
),
updatedAtMs: timestamp(value.updatedAtMs, 'updatedAtMs'),
});
const headDigest = trustHeadDigest(normalized);
if (value.headDigest !== headDigest) {
return invalid('headDigest does not match trust head');
}
return Object.freeze({ ...normalized, headDigest });
}
export function createPluginPackagePublisherTrustHead(
authorityIdValue: string,
snapshotValue: PluginPackagePublisherTrustSnapshot,
updatedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustHead> {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
if (snapshot.keys.length < 1) {
return invalid('base trust snapshot must contain one key');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: keyId(authorityIdValue),
generation: 1,
baseSnapshotDigest: snapshot.snapshotDigest,
effectiveTrustDigest: snapshot.snapshotDigest,
updatedAtMs: timestamp(updatedAtMsValue, 'updatedAtMs'),
});
return normalizePluginPackagePublisherTrustHead({
...unsigned,
headDigest: trustHeadDigest(unsigned),
});
}
export function advancePluginPackagePublisherTrustHead(
headValue: PluginPackagePublisherTrustHead,
effectiveSnapshotValue: PluginPackagePublisherTrustSnapshot,
updatedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustHead> {
const head = normalizePluginPackagePublisherTrustHead(headValue);
const effectiveSnapshot =
normalizePluginPackagePublisherTrustSnapshot(effectiveSnapshotValue);
const updatedAtMs = timestamp(updatedAtMsValue, 'updatedAtMs');
if (
effectiveSnapshot.snapshotDigest === head.effectiveTrustDigest ||
updatedAtMs < head.updatedAtMs ||
head.generation >= 2_147_483_647
) {
return invalid('trust head transition is invalid');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: head.authorityId,
generation: head.generation + 1,
baseSnapshotDigest: head.baseSnapshotDigest,
effectiveTrustDigest: effectiveSnapshot.snapshotDigest,
updatedAtMs,
});
return normalizePluginPackagePublisherTrustHead({
...unsigned,
headDigest: trustHeadDigest(unsigned),
});
}
export function pluginPackagePublisherTrustRevokedDigest(
snapshotValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
): string {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const remaining = snapshot.keys.filter(
(key) =>
key.publisher !== targetPublisher || key.keyId !== targetKeyId,
);
if (remaining.length === snapshot.keys.length) {
return invalid('revoked key is absent from the trust snapshot');
}
return pluginPackagePublisherTrustKeysetDigest(remaining);
}
@@ -0,0 +1,708 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
createPluginPackagePublisherTrustOverlapAdditionSnapshot,
createPluginPackagePublisherTrustRetirementSnapshot,
normalizePluginPackagePublisherTrustSnapshot,
type PluginPackagePublisherTrustSnapshot,
} from './pluginPackagePublisherTrust';
import { normalizeProjectPolicySubject } from '../../security/project-policy/projectPolicy';
import {
type SecurityAuthenticationAssurance,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../security/security';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA =
'qinglong/plugin-package-publisher-trust-transition-proposal@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA =
'qinglong/plugin-package-publisher-trust-transition-receipt@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION =
'package.manage' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES =
Object.freeze({
overlap_add: 'plugin_package.publisher_key.overlap_add',
safe_retire: 'plugin_package.publisher_key.safe_retire',
} as const);
export type PluginPackagePublisherTrustTransitionMode =
keyof typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES;
export type PluginPackagePublisherTrustTransitionActionType =
(typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES)[PluginPackagePublisherTrustTransitionMode];
export interface PluginPackagePublisherTrustTransitionActionInput {
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly mode: PluginPackagePublisherTrustTransitionMode;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
}
export interface PluginPackagePublisherTrustTransitionProposal {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: PluginPackagePublisherTrustTransitionActionType;
readonly permission: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION;
readonly actionInput: Readonly<PluginPackagePublisherTrustTransitionActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposerAssurance: Extract<
SecurityAuthenticationAssurance,
'multi_factor' | 'hardware'
>;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface PluginPackagePublisherTrustTransitionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA;
readonly mutationId: string;
readonly proposalDigest: string;
readonly trustAuthorityId: string;
readonly previousGeneration: number;
readonly currentGeneration: number;
readonly mode: PluginPackagePublisherTrustTransitionMode;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly retirementMatchingInstallations: 0 | null;
readonly executedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackagePublisherTrustTransitionProposalInput =
Readonly<{
actionRef: string;
authorityProjectId: string;
trustAuthorityId: string;
trustGeneration: number;
mode: PluginPackagePublisherTrustTransitionMode;
trustSnapshot: PluginPackagePublisherTrustSnapshot;
materialSnapshot?: PluginPackagePublisherTrustSnapshot;
publisher: string;
keyId: string;
proposedBy: SecuritySubject;
proposerAssurance: SecurityAuthenticationAssurance;
proposalFence: SecurityPolicyFence;
createdAtMs: number;
}>;
export interface CreatePluginPackagePublisherTrustTransitionProposalCommand {
readonly proposal: PluginPackagePublisherTrustTransitionProposal;
readonly candidateSnapshot: PluginPackagePublisherTrustSnapshot;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackagePublisherTrustTransitionProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackagePublisherTrustTransitionProposal>;
}
export interface PluginPackagePublisherTrustTransitionProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackagePublisherTrustTransitionProposal> | null>;
createProposal(
command: CreatePluginPackagePublisherTrustTransitionProposalCommand,
): Promise<
Readonly<CreatePluginPackagePublisherTrustTransitionProposalResult>
>;
}
export class InvalidPluginPackagePublisherTrustTransitionError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_INVALID';
constructor(message: string) {
super(`Plugin Package publisher trust transition is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherTrustTransitionError';
}
}
export class PluginPackagePublisherTrustTransitionBindingConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_BINDING_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust transition does not match its dispatch',
);
this.name =
'PluginPackagePublisherTrustTransitionBindingConflictError';
}
}
export class PluginPackagePublisherTrustTransitionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust transition conflicts with durable authority',
);
this.name = 'PluginPackagePublisherTrustTransitionConflictError';
}
}
export class PluginPackagePublisherTrustTransitionUnavailableError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super(
'Plugin Package publisher trust transition authority is unavailable',
options,
);
this.name = 'PluginPackagePublisherTrustTransitionUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherTrustTransitionError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
({ get, set, enumerable }) =>
get !== undefined || set !== undefined || enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('authorityProjectId is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function mode(value: unknown): PluginPackagePublisherTrustTransitionMode {
if (value !== 'overlap_add' && value !== 'safe_retire') {
return invalid('mode is invalid');
}
return value;
}
function strongAssurance(
value: unknown,
): 'multi_factor' | 'hardware' {
if (value !== 'multi_factor' && value !== 'hardware') {
return invalid('proposerAssurance must be multi_factor or hardware');
}
return value;
}
function userSubject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const normalized = normalizeProjectPolicySubject(value);
if (normalized.type !== 'user') {
return invalid(`${label} must be a User`);
}
return normalized;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function normalizeActionInput(
value: PluginPackagePublisherTrustTransitionActionInput,
): Readonly<PluginPackagePublisherTrustTransitionActionInput> {
const record = dataRecord(value, 'action input');
exactKeys(
record,
[
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'mode',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
],
'action input',
);
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('transition must change the trust digest');
}
return Object.freeze({
authorityProjectId: projectId(value.authorityProjectId),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
trustGeneration: positiveInteger(
value.trustGeneration,
'trustGeneration',
),
mode: mode(value.mode),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
});
}
export function pluginPackagePublisherTrustTransitionActionDigest(
value: PluginPackagePublisherTrustTransitionActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-trust-transition-action-digest@v1',
normalizeActionInput(value),
);
}
export function pluginPackagePublisherTrustTransitionPreviewDigest(
value: PluginPackagePublisherTrustTransitionActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-trust-transition-preview-digest@v1',
normalizeActionInput(value),
);
}
function withProposalDigest(
value: Omit<
PluginPackagePublisherTrustTransitionProposal,
'proposalDigest'
>,
): Readonly<PluginPackagePublisherTrustTransitionProposal> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-publisher-trust-transition-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackagePublisherTrustTransitionProposal(
inputValue: CreatePluginPackagePublisherTrustTransitionProposalInput,
): Readonly<{
proposal: Readonly<PluginPackagePublisherTrustTransitionProposal>;
candidateSnapshot: Readonly<PluginPackagePublisherTrustSnapshot>;
}> {
const input = dataRecord(inputValue, 'proposal input');
const optional = Object.hasOwn(input, 'materialSnapshot')
? ['materialSnapshot']
: [];
exactKeys(
input,
[
'actionRef',
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'mode',
'trustSnapshot',
'publisher',
'keyId',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
...optional,
],
'proposal input',
);
const transitionMode = mode(inputValue.mode);
const trustSnapshot = normalizePluginPackagePublisherTrustSnapshot(
inputValue.trustSnapshot,
);
const candidateSnapshot =
transitionMode === 'overlap_add'
? createPluginPackagePublisherTrustOverlapAdditionSnapshot(
trustSnapshot,
inputValue.materialSnapshot ??
invalid('overlap addition requires materialSnapshot'),
inputValue.publisher,
inputValue.keyId,
inputValue.createdAtMs,
)
: (() => {
if (inputValue.materialSnapshot !== undefined) {
return invalid('retirement cannot accept materialSnapshot');
}
return createPluginPackagePublisherTrustRetirementSnapshot(
trustSnapshot,
inputValue.publisher,
inputValue.keyId,
inputValue.createdAtMs,
);
})();
const actionInput = normalizeActionInput({
authorityProjectId: inputValue.authorityProjectId,
trustAuthorityId: inputValue.trustAuthorityId,
trustGeneration: inputValue.trustGeneration,
mode: transitionMode,
publisher: inputValue.publisher,
keyId: inputValue.keyId,
previousTrustDigest: trustSnapshot.snapshotDigest,
currentTrustDigest: candidateSnapshot.snapshotDigest,
});
const proposal = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.authorityProjectId,
actionType:
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES[
transitionMode
],
permission: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherTrustTransitionActionDigest(actionInput),
previewDigest:
pluginPackagePublisherTrustTransitionPreviewDigest(actionInput),
proposedBy: userSubject(inputValue.proposedBy, 'proposedBy'),
proposerAssurance: strongAssurance(inputValue.proposerAssurance),
proposalFence: normalizeApprovedActionFence(inputValue.proposalFence),
createdAtMs: timestamp(inputValue.createdAtMs, 'createdAtMs'),
});
return Object.freeze({ proposal, candidateSnapshot });
}
export function normalizePluginPackagePublisherTrustTransitionProposal(
value: PluginPackagePublisherTrustTransitionProposal,
): Readonly<PluginPackagePublisherTrustTransitionProposal> {
const record = dataRecord(value, 'proposal');
exactKeys(
record,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
const actionInput = normalizeActionInput(value.actionInput);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA ||
value.permission !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION ||
value.actionType !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES[
actionInput.mode
]
) {
return invalid('schema or action authority is invalid');
}
const normalized = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA,
actionRef: actionRef(value.actionRef),
projectId: projectId(value.projectId),
actionType: value.actionType,
permission: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherTrustTransitionActionDigest(actionInput),
previewDigest:
pluginPackagePublisherTrustTransitionPreviewDigest(actionInput),
proposedBy: userSubject(value.proposedBy, 'proposedBy'),
proposerAssurance: strongAssurance(value.proposerAssurance),
proposalFence: normalizeApprovedActionFence(value.proposalFence),
createdAtMs: timestamp(value.createdAtMs, 'createdAtMs'),
});
if (
normalized.projectId !== actionInput.authorityProjectId ||
digest(value.actionDigest, 'actionDigest') !==
normalized.actionDigest ||
digest(value.previewDigest, 'previewDigest') !==
normalized.previewDigest ||
digest(value.proposalDigest, 'proposalDigest') !==
normalized.proposalDigest
) {
return invalid('proposal digest or derived binding is invalid');
}
return normalized;
}
function withReceiptDigest(
value: Omit<
PluginPackagePublisherTrustTransitionReceipt,
'receiptDigest'
>,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
receiptDigest: contractDigest(
'qinglong/plugin-package-publisher-trust-transition-receipt-digest@v1',
normalized,
),
});
}
export function normalizePluginPackagePublisherTrustTransitionReceipt(
value: PluginPackagePublisherTrustTransitionReceipt,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const record = dataRecord(value, 'transition receipt');
exactKeys(
record,
[
'schema',
'mutationId',
'proposalDigest',
'trustAuthorityId',
'previousGeneration',
'currentGeneration',
'mode',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
'proposer',
'confirmer',
'retirementMatchingInstallations',
'executedAtMs',
'receiptDigest',
],
'transition receipt',
);
const transitionMode = mode(value.mode);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA ||
(transitionMode === 'overlap_add' &&
value.retirementMatchingInstallations !== null) ||
(transitionMode === 'safe_retire' &&
value.retirementMatchingInstallations !== 0)
) {
return invalid('transition receipt mode or retirement proof is invalid');
}
const previousGeneration = positiveInteger(
value.previousGeneration,
'previousGeneration',
);
const normalized = withReceiptDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
proposalDigest: digest(value.proposalDigest, 'proposalDigest'),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
previousGeneration,
currentGeneration: positiveInteger(
value.currentGeneration,
'currentGeneration',
),
mode: transitionMode,
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest: digest(
value.previousTrustDigest,
'previousTrustDigest',
),
currentTrustDigest: digest(
value.currentTrustDigest,
'currentTrustDigest',
),
proposer: userSubject(value.proposer, 'proposer'),
confirmer: userSubject(value.confirmer, 'confirmer'),
retirementMatchingInstallations:
value.retirementMatchingInstallations,
executedAtMs: timestamp(value.executedAtMs, 'executedAtMs'),
});
if (
normalized.currentGeneration !== previousGeneration + 1 ||
normalized.previousTrustDigest === normalized.currentTrustDigest ||
sameSubject(normalized.proposer, normalized.confirmer) ||
digest(value.receiptDigest, 'receiptDigest') !==
normalized.receiptDigest
) {
return invalid('transition receipt derived binding is invalid');
}
return normalized;
}
export function resolvePluginPackagePublisherTrustTransitionProposal(
proposalValue: PluginPackagePublisherTrustTransitionProposal,
dispatchValue: ApprovedActionDispatchRecord,
executedAtMsValue: number,
retirementMatchingInstallationsValue: 0 | null,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const proposal =
normalizePluginPackagePublisherTrustTransitionProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const executedAtMs = timestamp(executedAtMsValue, 'executedAtMs');
const action = proposal.actionInput;
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
!sameSubject(dispatch.requestedBy, proposal.proposedBy) ||
sameSubject(dispatch.requestedBy, dispatch.approvedBy) ||
(dispatch.approvalAssurance !== 'multi_factor' &&
dispatch.approvalAssurance !== 'hardware') ||
dispatch.createdAtMs < proposal.createdAtMs ||
executedAtMs < dispatch.createdAtMs ||
executedAtMs >= dispatch.expiresAtMs ||
(action.mode === 'overlap_add' &&
retirementMatchingInstallationsValue !== null) ||
(action.mode === 'safe_retire' &&
retirementMatchingInstallationsValue !== 0)
) {
throw new PluginPackagePublisherTrustTransitionBindingConflictError();
}
return normalizePluginPackagePublisherTrustTransitionReceipt(
withReceiptDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA,
mutationId: dispatch.id,
proposalDigest: proposal.proposalDigest,
trustAuthorityId: action.trustAuthorityId,
previousGeneration: action.trustGeneration,
currentGeneration: action.trustGeneration + 1,
mode: action.mode,
publisher: action.publisher,
keyId: action.keyId,
previousTrustDigest: action.previousTrustDigest,
currentTrustDigest: action.currentTrustDigest,
proposer: proposal.proposedBy,
confirmer: dispatch.approvedBy,
retirementMatchingInstallations:
retirementMatchingInstallationsValue,
executedAtMs,
}),
);
}
@@ -0,0 +1,265 @@
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import type { SecurityAuditRecord } from '../../../security/audit/securityAudit';
import type { RunCancellationReason, RunStatus } from '../../../run/run';
import type { StepRunKind, StepRunStatus } from '../../../run/stepRun';
import type {
PluginPackageWorkflowAdmissionReceipt,
PluginPackageWorkflowExecutionPlan,
} from '../pluginPackageWorkflowExecutionPlan';
export interface AuthorizedPluginPackageWorkflowAdmission {
readonly plan: PluginPackageWorkflowExecutionPlan;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowAdministrationRepository {
findPlanByPlanId(
planId: string,
): Promise<Readonly<PluginPackageWorkflowExecutionPlan> | null>;
admitAuthorized(admission: AuthorizedPluginPackageWorkflowAdmission): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}>
>;
}
export const PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES = [
'accepted',
'existing',
'already_requested',
'already_terminal',
] as const;
export type PluginPackageWorkflowCancellationStatus =
(typeof PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES)[number];
export interface AuthorizedPluginPackageWorkflowCancellation {
readonly projectId: string;
readonly packageName: string;
readonly runId: string;
readonly mutationId: string;
readonly runEventId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowCancellationResult {
readonly status: PluginPackageWorkflowCancellationStatus;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly runStatus: RunStatus;
readonly runVersion: number;
readonly eventSequence: number;
readonly cancelRequestedAtMs?: number;
readonly cancelReason?: RunCancellationReason;
}
export interface PluginPackageWorkflowCancellationRepository {
requestUserCancellation(
cancellation: AuthorizedPluginPackageWorkflowCancellation,
): Promise<Readonly<PluginPackageWorkflowCancellationResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA =
'qinglong/plugin-package-workflow-run-inspection@v1' as const;
export interface AuthorizedPluginPackageWorkflowRunInspection {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunInspectionResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly run: Readonly<{
status: RunStatus;
version: number;
eventSequence: number;
createdAtMs: number;
queuedAtMs: number | null;
startedAtMs: number | null;
finishedAtMs: number | null;
cancelRequestedAtMs: number | null;
cancelReason: RunCancellationReason | null;
}> | null;
readonly stepCount: number | null;
readonly stepStatusCounts: Readonly<Record<StepRunStatus, number>> | null;
}
export interface PluginPackageWorkflowRunInspectionRepository {
inspectRunAuthorized(
inspection: AuthorizedPluginPackageWorkflowRunInspection,
): Promise<Readonly<PluginPackageWorkflowRunInspectionResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA =
'qinglong/plugin-package-workflow-run-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE = 64;
export interface PluginPackageWorkflowRunListCursor {
readonly admittedAtMs: number;
readonly runId: string;
}
export interface AuthorizedPluginPackageWorkflowRunList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly limit: number;
readonly after: Readonly<PluginPackageWorkflowRunListCursor> | null;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunListItem {
readonly runId: string;
readonly status: RunStatus;
readonly version: number;
readonly eventSequence: number;
readonly stepCount: number;
readonly admittedAtMs: number;
readonly queuedAtMs: number | null;
readonly startedAtMs: number | null;
readonly finishedAtMs: number | null;
readonly cancelRequestedAtMs: number | null;
readonly cancelReason: RunCancellationReason | null;
}
export interface PluginPackageWorkflowRunListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly after: Readonly<PluginPackageWorkflowRunListCursor> | null;
readonly runs: readonly Readonly<PluginPackageWorkflowRunListItem>[];
readonly truncated: boolean;
readonly next: Readonly<PluginPackageWorkflowRunListCursor> | null;
}
export interface PluginPackageWorkflowRunListRepository {
listRunsAuthorized(
query: AuthorizedPluginPackageWorkflowRunList,
): Promise<Readonly<PluginPackageWorkflowRunListResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA =
'qinglong/plugin-package-workflow-step-run-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE = 64;
export interface PluginPackageWorkflowStepRunCursor {
readonly stepKey: string;
readonly id: string;
}
export interface AuthorizedPluginPackageWorkflowStepRunList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly limit: number;
readonly after: Readonly<PluginPackageWorkflowStepRunCursor> | null;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowStepRunListItem {
readonly id: string;
readonly parentStepRunId: string | null;
readonly stepKey: string;
readonly kind: StepRunKind;
readonly required: boolean;
readonly status: StepRunStatus;
readonly version: number;
readonly attemptCount: number;
readonly readyAtMs: number | null;
readonly startedAtMs: number | null;
readonly finishedAtMs: number | null;
readonly resultCode: string | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
}
export interface PluginPackageWorkflowStepRunListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly stepRuns: readonly Readonly<PluginPackageWorkflowStepRunListItem>[];
readonly truncated: boolean;
readonly next: Readonly<PluginPackageWorkflowStepRunCursor> | null;
}
export interface PluginPackageWorkflowStepRunListRepository {
listStepRunsAuthorized(
query: AuthorizedPluginPackageWorkflowStepRunList,
): Promise<Readonly<PluginPackageWorkflowStepRunListResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA =
'qinglong/plugin-package-workflow-run-event-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE = 64;
export interface AuthorizedPluginPackageWorkflowRunEventList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly limit: number;
readonly afterSequence: number;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunEventListItem {
readonly id: string;
readonly sequence: number;
readonly type: string;
readonly stepRunId: string | null;
readonly createdAtMs: number;
}
export interface PluginPackageWorkflowRunEventListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly afterSequence: number;
readonly headSequence: number | null;
readonly events: readonly Readonly<PluginPackageWorkflowRunEventListItem>[];
readonly truncated: boolean;
readonly nextAfterSequence: number | null;
}
export interface PluginPackageWorkflowRunEventListRepository {
listRunEventsAuthorized(
query: AuthorizedPluginPackageWorkflowRunEventList,
): Promise<Readonly<PluginPackageWorkflowRunEventListResult>>;
}
@@ -0,0 +1,41 @@
export class InvalidPluginPackageWorkflowAdministrationMutationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_MUTATION_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow administration mutation is invalid: ${message}`,
);
this.name = 'InvalidPluginPackageWorkflowAdministrationMutationError';
}
}
export class PluginPackageWorkflowAdministrationAuthorizationFenceConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Plugin Package Workflow administration authorization fence changed');
this.name =
'PluginPackageWorkflowAdministrationAuthorizationFenceConflictError';
}
}
export class PluginPackageWorkflowAdministrationMutationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_MUTATION_CONFLICT';
constructor() {
super(
'Plugin Package Workflow administration conflicts with durable state',
);
this.name = 'PluginPackageWorkflowAdministrationMutationConflictError';
}
}
export class PluginPackageWorkflowCancellationNotFoundError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_NOT_FOUND';
constructor() {
super('Plugin Package Workflow cancellation target does not exist');
this.name = 'PluginPackageWorkflowCancellationNotFoundError';
}
}
@@ -0,0 +1,206 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_STATUSES } from '../../../run/run';
import { normalizePluginPackageWorkflowExecutionPlan } from '../pluginPackageWorkflowExecutionPlan';
import {
PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES,
type AuthorizedPluginPackageWorkflowAdmission,
type AuthorizedPluginPackageWorkflowCancellation,
type PluginPackageWorkflowCancellationResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
packageName,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowAdmission(
value: AuthorizedPluginPackageWorkflowAdmission,
): Readonly<AuthorizedPluginPackageWorkflowAdmission> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['actor', 'audit', 'fence', 'plan'])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'admission shape is invalid',
);
}
try {
const plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.start' ||
audit.projectId !== plan.target.projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
audit.occurredAtMs !== plan.plannedAtMs ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'audit binding is invalid',
);
}
return Object.freeze({ plan, actor, fence, audit });
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'admission value is invalid',
);
}
}
export function normalizeAuthorizedPluginPackageWorkflowCancellation(
value: AuthorizedPluginPackageWorkflowCancellation,
): Readonly<AuthorizedPluginPackageWorkflowCancellation> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'audit',
'fence',
'mutationId',
'packageName',
'projectId',
'runEventId',
'runId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const runId = identifier(value.runId, 'runId');
const mutationId = identifier(value.mutationId, 'mutationId');
const runEventId = identifier(value.runEventId, 'runEventId');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.cancel' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
runId,
mutationId,
runEventId,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation value is invalid',
);
}
}
export function normalizePluginPackageWorkflowCancellationResult(
value: PluginPackageWorkflowCancellationResult,
): Readonly<PluginPackageWorkflowCancellationResult> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation result is invalid',
);
}
const hasCancellation = value.cancelRequestedAtMs !== undefined;
if (
!exactKeys(
value,
hasCancellation
? [
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'packageName',
'projectId',
'runId',
'runStatus',
'runVersion',
'status',
'workflowId',
]
: [
'eventSequence',
'packageName',
'projectId',
'runId',
'runStatus',
'runVersion',
'status',
'workflowId',
],
) ||
!PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES.includes(value.status) ||
!RUN_STATUSES.includes(value.runStatus) ||
!Number.isSafeInteger(value.runVersion) ||
value.runVersion < 1 ||
!Number.isSafeInteger(value.eventSequence) ||
value.eventSequence < 0 ||
(hasCancellation &&
(!Number.isSafeInteger(value.cancelRequestedAtMs) ||
(value.cancelRequestedAtMs as number) < 0 ||
!['user', 'policy', 'shutdown', 'reconcile', 'timeout'].includes(
value.cancelReason ?? '',
))) ||
(!hasCancellation && value.cancelReason !== undefined)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation result state is invalid',
);
}
return Object.freeze({
status: value.status,
projectId: identifier(value.projectId, 'projectId'),
packageName: packageName(value.packageName),
workflowId: identifier(value.workflowId, 'workflowId'),
runId: identifier(value.runId, 'runId'),
runStatus: value.runStatus,
runVersion: value.runVersion,
eventSequence: value.eventSequence,
...(hasCancellation
? {
cancelRequestedAtMs: value.cancelRequestedAtMs!,
cancelReason: value.cancelReason!,
}
: {}),
});
}
@@ -0,0 +1,254 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowRunEventList,
type PluginPackageWorkflowRunEventListItem,
type PluginPackageWorkflowRunEventListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowRunEventList(
value: AuthorizedPluginPackageWorkflowRunEventList,
): Readonly<AuthorizedPluginPackageWorkflowRunEventList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'afterSequence',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE ||
!Number.isSafeInteger(value.afterSequence) ||
value.afterSequence < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list page is invalid',
);
}
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.event.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
limit: value.limit,
afterSequence: value.afterSequence,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list value is invalid',
);
}
}
const RUN_EVENT_TYPE = /^[a-z][a-z0-9_.-]{0,127}$/;
function normalizeWorkflowRunEventListItem(
value: PluginPackageWorkflowRunEventListItem,
): Readonly<PluginPackageWorkflowRunEventListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['createdAtMs', 'id', 'sequence', 'stepRunId', 'type']) ||
!Number.isSafeInteger(value.sequence) ||
value.sequence < 1 ||
typeof value.type !== 'string' ||
!RUN_EVENT_TYPE.test(value.type) ||
!Number.isSafeInteger(value.createdAtMs) ||
value.createdAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list item is invalid',
);
}
return Object.freeze({
id: identifier(value.id, 'RunEvent id'),
sequence: value.sequence,
type: value.type,
stepRunId:
value.stepRunId === null
? null
: identifier(value.stepRunId, 'RunEvent StepRun id'),
createdAtMs: value.createdAtMs,
});
}
export function normalizePluginPackageWorkflowRunEventListResult(
value: PluginPackageWorkflowRunEventListResult,
): Readonly<PluginPackageWorkflowRunEventListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'afterSequence',
'events',
'found',
'headSequence',
'nextAfterSequence',
'packageName',
'projectId',
'runId',
'schema',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA ||
typeof value.found !== 'boolean' ||
typeof value.truncated !== 'boolean' ||
!Number.isSafeInteger(value.afterSequence) ||
value.afterSequence < 0 ||
!Array.isArray(value.events) ||
value.events.length > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (
value.headSequence !== null ||
value.events.length !== 0 ||
value.truncated ||
value.nextAfterSequence !== null
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing RunEvent list result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
afterSequence: value.afterSequence,
headSequence: null,
events: Object.freeze([]),
truncated: false,
nextAfterSequence: null,
});
}
if (
!Number.isSafeInteger(value.headSequence) ||
(value.headSequence as number) < 0 ||
value.afterSequence > (value.headSequence as number)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list head is invalid',
);
}
const headSequence = value.headSequence as number;
const events = value.events.map(normalizeWorkflowRunEventListItem);
const ids = new Set<string>();
for (let index = 0; index < events.length; index += 1) {
const event = events[index]!;
if (
ids.has(event.id) ||
event.sequence !== value.afterSequence + index + 1 ||
event.sequence > headSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list sequence is invalid',
);
}
ids.add(event.id);
}
const lastSequence = events.at(-1)?.sequence ?? value.afterSequence;
let nextAfterSequence: number | null = null;
if (value.truncated) {
if (
events.length === 0 ||
lastSequence >= headSequence ||
value.nextAfterSequence !== lastSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list continuation is invalid',
);
}
nextAfterSequence = lastSequence;
} else if (
value.nextAfterSequence !== null ||
lastSequence !== headSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list terminal page is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
afterSequence: value.afterSequence,
headSequence,
events: Object.freeze(events),
truncated: value.truncated,
nextAfterSequence,
});
}
@@ -0,0 +1,225 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_CANCELLATION_REASONS, RUN_STATUSES } from '../../../run/run';
import { STEP_RUN_STATUSES, type StepRunStatus } from '../../../run/stepRun';
import {
PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
type AuthorizedPluginPackageWorkflowRunInspection,
type PluginPackageWorkflowRunInspectionResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowRunInspection(
value: AuthorizedPluginPackageWorkflowRunInspection,
): Readonly<AuthorizedPluginPackageWorkflowRunInspection> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'audit',
'fence',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.run.read' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection value is invalid',
);
}
}
export function normalizePluginPackageWorkflowRunInspectionResult(
value: PluginPackageWorkflowRunInspectionResult,
): Readonly<PluginPackageWorkflowRunInspectionResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'found',
'packageName',
'projectId',
'run',
'runId',
'schema',
'stepCount',
'stepStatusCounts',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA ||
typeof value.found !== 'boolean'
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (
value.run !== null ||
value.stepCount !== null ||
value.stepStatusCounts !== null
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing run inspection result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
run: null,
stepCount: null,
stepStatusCounts: null,
});
}
if (
!value.run ||
typeof value.run !== 'object' ||
Array.isArray(value.run) ||
!exactKeys(value.run, [
'cancelReason',
'cancelRequestedAtMs',
'createdAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'startedAtMs',
'status',
'version',
]) ||
!RUN_STATUSES.includes(value.run.status) ||
!Number.isSafeInteger(value.run.version) ||
value.run.version < 1 ||
!Number.isSafeInteger(value.run.eventSequence) ||
value.run.eventSequence < 0 ||
!Number.isSafeInteger(value.run.createdAtMs) ||
value.run.createdAtMs < 0 ||
!Number.isSafeInteger(value.stepCount) ||
(value.stepCount as number) < 1 ||
(value.stepCount as number) > 128 ||
!value.stepStatusCounts ||
typeof value.stepStatusCounts !== 'object' ||
Array.isArray(value.stepStatusCounts) ||
!exactKeys(value.stepStatusCounts, STEP_RUN_STATUSES)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'found run inspection result is invalid',
);
}
const queuedAtMs = nullableTimestamp(value.run.queuedAtMs);
const startedAtMs = nullableTimestamp(value.run.startedAtMs);
const finishedAtMs = nullableTimestamp(value.run.finishedAtMs);
const cancelRequestedAtMs = nullableTimestamp(value.run.cancelRequestedAtMs);
const cancelReason = value.run.cancelReason;
if (
(cancelRequestedAtMs === null) !== (cancelReason === null) ||
(cancelReason !== null && !RUN_CANCELLATION_REASONS.includes(cancelReason))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection cancellation state is invalid',
);
}
const counts = Object.fromEntries(
STEP_RUN_STATUSES.map((status) => {
const count = value.stepStatusCounts![status];
if (!Number.isSafeInteger(count) || count < 0 || count > 128) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection StepRun counts are invalid',
);
}
return [status, count];
}),
) as Record<StepRunStatus, number>;
if (
Object.values(counts).reduce((total, count) => total + count, 0) !==
value.stepCount
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection StepRun count is inconsistent',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
run: Object.freeze({
status: value.run.status,
version: value.run.version,
eventSequence: value.run.eventSequence,
createdAtMs: value.run.createdAtMs,
queuedAtMs,
startedAtMs,
finishedAtMs,
cancelRequestedAtMs,
cancelReason,
}),
stepCount: value.stepCount,
stepStatusCounts: Object.freeze(counts),
});
}
@@ -0,0 +1,282 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_CANCELLATION_REASONS, RUN_STATUSES } from '../../../run/run';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowRunList,
type PluginPackageWorkflowRunListCursor,
type PluginPackageWorkflowRunListItem,
type PluginPackageWorkflowRunListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
function normalizeWorkflowRunListCursor(
value: PluginPackageWorkflowRunListCursor,
label: string,
): Readonly<PluginPackageWorkflowRunListCursor> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['admittedAtMs', 'runId']) ||
!Number.isSafeInteger(value.admittedAtMs) ||
value.admittedAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return Object.freeze({
admittedAtMs: value.admittedAtMs,
runId: identifier(value.runId, `${label}.runId`),
});
}
function workflowRunListPositionBefore(
left: Readonly<PluginPackageWorkflowRunListCursor>,
right: Readonly<PluginPackageWorkflowRunListCursor>,
): boolean {
return (
left.admittedAtMs < right.admittedAtMs ||
(left.admittedAtMs === right.admittedAtMs && left.runId < right.runId)
);
}
export function normalizeAuthorizedPluginPackageWorkflowRunList(
value: AuthorizedPluginPackageWorkflowRunList,
): Readonly<AuthorizedPluginPackageWorkflowRunList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'after',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list limit is invalid',
);
}
const after =
value.after === null
? null
: normalizeWorkflowRunListCursor(value.after, 'run list cursor');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.run.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
limit: value.limit,
after,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list value is invalid',
);
}
}
function normalizeWorkflowRunListItem(
value: PluginPackageWorkflowRunListItem,
): Readonly<PluginPackageWorkflowRunListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'admittedAtMs',
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'runId',
'startedAtMs',
'status',
'stepCount',
'version',
]) ||
!RUN_STATUSES.includes(value.status) ||
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
!Number.isSafeInteger(value.eventSequence) ||
value.eventSequence < 0 ||
!Number.isSafeInteger(value.stepCount) ||
value.stepCount < 1 ||
value.stepCount > 128 ||
!Number.isSafeInteger(value.admittedAtMs) ||
value.admittedAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list item is invalid',
);
}
const queuedAtMs = nullableTimestamp(value.queuedAtMs);
const startedAtMs = nullableTimestamp(value.startedAtMs);
const finishedAtMs = nullableTimestamp(value.finishedAtMs);
const cancelRequestedAtMs = nullableTimestamp(value.cancelRequestedAtMs);
if (
(cancelRequestedAtMs === null) !== (value.cancelReason === null) ||
(value.cancelReason !== null &&
!RUN_CANCELLATION_REASONS.includes(value.cancelReason))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list cancellation state is invalid',
);
}
return Object.freeze({
runId: identifier(value.runId, 'run list runId'),
status: value.status,
version: value.version,
eventSequence: value.eventSequence,
stepCount: value.stepCount,
admittedAtMs: value.admittedAtMs,
queuedAtMs,
startedAtMs,
finishedAtMs,
cancelRequestedAtMs,
cancelReason: value.cancelReason,
});
}
export function normalizePluginPackageWorkflowRunListResult(
value: PluginPackageWorkflowRunListResult,
): Readonly<PluginPackageWorkflowRunListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'after',
'next',
'packageName',
'projectId',
'runs',
'schema',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA ||
!Array.isArray(value.runs) ||
value.runs.length > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE ||
typeof value.truncated !== 'boolean'
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const after =
value.after === null
? null
: normalizeWorkflowRunListCursor(value.after, 'run list result cursor');
const runs = value.runs.map(normalizeWorkflowRunListItem);
const ids = new Set<string>();
for (let index = 0; index < runs.length; index += 1) {
const run = runs[index]!;
const position = { admittedAtMs: run.admittedAtMs, runId: run.runId };
if (ids.has(run.runId)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list identities are not unique',
);
}
ids.add(run.runId);
const previous = index === 0 ? after : runs[index - 1]!;
if (
previous !== null &&
!workflowRunListPositionBefore(position, {
admittedAtMs: previous.admittedAtMs,
runId: previous.runId,
})
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list order is invalid',
);
}
}
const next =
value.next === null
? null
: normalizeWorkflowRunListCursor(value.next, 'run list next cursor');
const last = runs.at(-1);
if (
(value.truncated &&
(!last ||
!next ||
next.admittedAtMs !== last.admittedAtMs ||
next.runId !== last.runId)) ||
(!value.truncated && next !== null)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list continuation is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA,
projectId,
packageName: normalizedPackageName,
workflowId,
after,
runs: Object.freeze(runs),
truncated: value.truncated,
next,
});
}
@@ -0,0 +1,339 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { STEP_RUN_KINDS, STEP_RUN_STATUSES } from '../../../run/stepRun';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowStepRunList,
type PluginPackageWorkflowStepRunCursor,
type PluginPackageWorkflowStepRunListItem,
type PluginPackageWorkflowStepRunListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowStepRunList(
value: AuthorizedPluginPackageWorkflowStepRunList,
): Readonly<AuthorizedPluginPackageWorkflowStepRunList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'after',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list limit is invalid',
);
}
let after: Readonly<PluginPackageWorkflowStepRunCursor> | null = null;
if (value.after !== null) {
if (
!value.after ||
typeof value.after !== 'object' ||
Array.isArray(value.after) ||
!exactKeys(value.after, ['id', 'stepKey'])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list cursor is invalid',
);
}
after = Object.freeze({
stepKey: resourceId(value.after.stepKey, 'after.stepKey'),
id: identifier(value.after.id, 'after.id'),
});
}
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.step.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
limit: value.limit,
after,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list value is invalid',
);
}
}
const STEP_RUN_RESULT_CODE = /^[a-z][a-z0-9_]{0,63}$/;
function normalizeWorkflowStepRunListItem(
value: PluginPackageWorkflowStepRunListItem,
): Readonly<PluginPackageWorkflowStepRunListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'attemptCount',
'createdAtMs',
'finishedAtMs',
'id',
'kind',
'parentStepRunId',
'readyAtMs',
'required',
'resultCode',
'startedAtMs',
'status',
'stepKey',
'updatedAtMs',
'version',
]) ||
!STEP_RUN_KINDS.includes(value.kind) ||
!STEP_RUN_STATUSES.includes(value.status) ||
typeof value.required !== 'boolean' ||
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
value.version > 2_147_483_647 ||
!Number.isSafeInteger(value.attemptCount) ||
value.attemptCount < 0 ||
value.attemptCount > 64 ||
!Number.isSafeInteger(value.createdAtMs) ||
value.createdAtMs < 0 ||
!Number.isSafeInteger(value.updatedAtMs) ||
value.updatedAtMs < value.createdAtMs
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list item is invalid',
);
}
const id = identifier(value.id, 'StepRun id');
const parentStepRunId =
value.parentStepRunId === null
? null
: identifier(value.parentStepRunId, 'parent StepRun id');
if (parentStepRunId === id) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list parent is invalid',
);
}
const stepKey = resourceId(value.stepKey, 'StepRun stepKey');
const readyAtMs = nullableTimestamp(value.readyAtMs);
const startedAtMs = nullableTimestamp(value.startedAtMs);
const finishedAtMs = nullableTimestamp(value.finishedAtMs);
const resultCode = value.resultCode;
if (
(resultCode !== null &&
(typeof resultCode !== 'string' ||
!STEP_RUN_RESULT_CODE.test(resultCode))) ||
(readyAtMs !== null &&
(readyAtMs < value.createdAtMs || readyAtMs > value.updatedAtMs)) ||
(startedAtMs !== null &&
(readyAtMs === null ||
startedAtMs < readyAtMs ||
startedAtMs > value.updatedAtMs)) ||
(finishedAtMs !== null &&
(finishedAtMs < value.createdAtMs ||
finishedAtMs > value.updatedAtMs ||
(readyAtMs !== null && finishedAtMs < readyAtMs) ||
(startedAtMs !== null && finishedAtMs < startedAtMs))) ||
(value.status === 'pending' &&
(readyAtMs !== null || startedAtMs !== null || finishedAtMs !== null)) ||
((value.status === 'ready' || value.status === 'waiting_approval') &&
(readyAtMs === null || startedAtMs !== null || finishedAtMs !== null)) ||
((value.status === 'running' || value.status === 'lost') &&
(readyAtMs === null || startedAtMs === null || finishedAtMs !== null)) ||
(['succeeded', 'failed', 'skipped', 'cancelled', 'timed_out'].includes(
value.status,
) &&
finishedAtMs === null) ||
(value.status === 'succeeded' && resultCode !== null) ||
(['failed', 'skipped', 'cancelled', 'timed_out', 'lost'].includes(
value.status,
) &&
resultCode === null) ||
(['pending', 'ready', 'waiting_approval', 'running'].includes(
value.status,
) &&
resultCode !== null)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list item state is invalid',
);
}
return Object.freeze({
id,
parentStepRunId,
stepKey,
kind: value.kind,
required: value.required,
status: value.status,
version: value.version,
attemptCount: value.attemptCount,
readyAtMs,
startedAtMs,
finishedAtMs,
resultCode,
createdAtMs: value.createdAtMs,
updatedAtMs: value.updatedAtMs,
});
}
export function normalizePluginPackageWorkflowStepRunListResult(
value: PluginPackageWorkflowStepRunListResult,
): Readonly<PluginPackageWorkflowStepRunListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'found',
'next',
'packageName',
'projectId',
'runId',
'schema',
'stepRuns',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA ||
typeof value.found !== 'boolean' ||
typeof value.truncated !== 'boolean' ||
!Array.isArray(value.stepRuns) ||
value.stepRuns.length > MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (value.stepRuns.length !== 0 || value.truncated || value.next !== null) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing StepRun list result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
stepRuns: Object.freeze([]),
truncated: false,
next: null,
});
}
const stepRuns = value.stepRuns.map(normalizeWorkflowStepRunListItem);
const identities = new Set<string>();
for (let index = 0; index < stepRuns.length; index += 1) {
const item = stepRuns[index]!;
if (identities.has(item.id) || identities.has(`step:${item.stepKey}`)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list identities are duplicated',
);
}
identities.add(item.id);
identities.add(`step:${item.stepKey}`);
const previous = stepRuns[index - 1];
if (
previous &&
(previous.stepKey > item.stepKey ||
(previous.stepKey === item.stepKey && previous.id >= item.id))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list order is invalid',
);
}
}
let next: Readonly<PluginPackageWorkflowStepRunCursor> | null = null;
if (value.truncated) {
const last = stepRuns.at(-1);
if (
!last ||
!value.next ||
typeof value.next !== 'object' ||
Array.isArray(value.next) ||
!exactKeys(value.next, ['id', 'stepKey']) ||
value.next.id !== last.id ||
value.next.stepKey !== last.stepKey
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list continuation is invalid',
);
}
next = Object.freeze({ id: last.id, stepKey: last.stepKey });
} else if (value.next !== null) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list continuation is unexpected',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
stepRuns: Object.freeze(stepRuns),
truncated: value.truncated,
next,
});
}
@@ -0,0 +1,86 @@
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
export function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
actual.length === canonical.length &&
actual.every((key, index) => key === canonical[index])
);
}
export function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
export function normalizeFence(
value: SecurityPolicyFence,
): SecurityPolicyFence {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['bindingVersion', 'projectVersion']) ||
!Number.isSafeInteger(value.projectVersion) ||
value.projectVersion < 1 ||
!Number.isSafeInteger(value.bindingVersion) ||
(value.bindingVersion as number) < 1
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'authorization fence is invalid',
);
}
return Object.freeze({
projectVersion: value.projectVersion,
bindingVersion: value.bindingVersion,
});
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RESOURCE_ID = /^[a-z][a-z0-9-]{0,62}$/;
export function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return value;
}
export function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'packageName is invalid',
);
}
return value;
}
export function resourceId(value: unknown, label: string): string {
if (typeof value !== 'string' || !RESOURCE_ID.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return value;
}
export function nullableTimestamp(value: unknown): number | null {
if (value === null) return null;
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection timestamp is invalid',
);
}
return value as number;
}
@@ -0,0 +1,7 @@
export * from './plugin-package-workflow-administration/contracts';
export * from './plugin-package-workflow-administration/errors';
export * from './plugin-package-workflow-administration/runInspection';
export * from './plugin-package-workflow-administration/runList';
export * from './plugin-package-workflow-administration/stepRunList';
export * from './plugin-package-workflow-administration/runEventList';
export * from './plugin-package-workflow-administration/mutation';
@@ -0,0 +1,547 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt,
type PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from './pluginPackageWorkflowTaskAttemptAdmission';
import {
RUN_DISPATCH_LEASE_STATUSES,
type RunDispatchLeaseStatus,
} from '../../run/runDispatchLease';
import type {
RunAttemptRecord,
RunCancellationReason,
RunEventRecord,
RunRecord,
} from '../../run/run';
import {
MAX_STEP_RUNS_PER_RUN,
STEP_RUN_TERMINAL_STATUSES,
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA =
'qinglong/plugin-package-workflow-cancellation-convergence@v1' as const;
export interface PluginPackageWorkflowCancellationActiveAttempt {
readonly admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly leaseStatus: RunDispatchLeaseStatus | null;
}
export interface PluginPackageWorkflowCancellationSnapshot {
readonly run: Readonly<RunRecord>;
readonly stepRuns: readonly Readonly<StepRunRecord>[];
readonly activeTaskAttempts:
readonly Readonly<PluginPackageWorkflowCancellationActiveAttempt>[];
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowCancellationAttemptTransition {
readonly previousStatus: 'claimed';
readonly attempt: Readonly<RunAttemptRecord>;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowCancellationTerminalTransition {
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly status: 'cancelled' | 'timed_out';
readonly finishedAtMs: number;
readonly errorCode: 'EXECUTION_CANCELLED' | 'EXECUTION_TIMED_OUT';
readonly errorSummary: string;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowCancellationResolution {
readonly schema:
typeof PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA;
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly run: Readonly<RunRecord>;
readonly attemptTransitions:
readonly Readonly<PluginPackageWorkflowCancellationAttemptTransition>[];
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly blockedAttemptIds: readonly string[];
readonly blockedStepRunIds: readonly string[];
readonly terminalTransition:
Readonly<PluginPackageWorkflowCancellationTerminalTransition> | null;
readonly observedAtMs: number;
}
export class InvalidPluginPackageWorkflowCancellationConvergenceError
extends TypeError
{
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow cancellation convergence is invalid: ${message}`,
);
this.name =
'InvalidPluginPackageWorkflowCancellationConvergenceError';
}
}
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const TERMINAL_STEP_STATUSES = new Set(STEP_RUN_TERMINAL_STATUSES);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-cancellation-convergence-id@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowCancellationConvergenceError(message);
}
function counter(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) > 2_147_483_647
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function identity(
runId: string,
cancelRequestedAtMs: number,
kind: 'attempt' | 'step' | 'run',
targetId: string,
epoch: number,
): string {
return createHash('sha256')
.update(ID_DOMAIN)
.update(runId, 'utf8')
.update('\0', 'utf8')
.update(String(cancelRequestedAtMs), 'utf8')
.update('\0', 'utf8')
.update(kind, 'utf8')
.update('\0', 'utf8')
.update(targetId, 'utf8')
.update('\0', 'utf8')
.update(String(epoch), 'utf8')
.digest('hex')
.slice(0, 32);
}
function terminalMapping(reason: RunCancellationReason): Readonly<{
status: 'cancelled' | 'timed_out';
errorCode: 'EXECUTION_CANCELLED' | 'EXECUTION_TIMED_OUT';
errorSummary: string;
}> {
return reason === 'timeout'
? Object.freeze({
status: 'timed_out' as const,
errorCode: 'EXECUTION_TIMED_OUT' as const,
errorSummary: 'Execution exceeded its configured timeout',
})
: Object.freeze({
status: 'cancelled' as const,
errorCode: 'EXECUTION_CANCELLED' as const,
errorSummary: 'Execution was cancelled',
});
}
function validateRun(run: Readonly<RunRecord>): Readonly<{
cancelRequestedAtMs: number;
cancelReason: RunCancellationReason;
}> {
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.status !== 'running' ||
run.cancelRequestedAtMs === undefined ||
run.cancelReason === undefined
) {
invalid('Run is not a cancelling runtime-owned Workflow aggregate');
}
counter(run.version, 'Run version');
counter(run.eventSequence, 'Run event sequence');
const cancelRequestedAtMs = timestamp(
run.cancelRequestedAtMs,
'Run cancellation time',
);
return Object.freeze({
cancelRequestedAtMs,
cancelReason: run.cancelReason,
});
}
function validateActiveAttempt(
run: Readonly<RunRecord>,
value: Readonly<PluginPackageWorkflowCancellationActiveAttempt>,
stepsById: ReadonlyMap<string, Readonly<StepRunRecord>>,
): Readonly<{
admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
attempt: Readonly<RunAttemptRecord>;
leaseStatus: RunDispatchLeaseStatus | null;
stepRun: Readonly<StepRunRecord>;
}> {
let admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
try {
admission =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
value.admission,
);
} catch {
return invalid('active Attempt admission is invalid');
}
const { attempt } = value;
if (
!attempt ||
typeof attempt !== 'object' ||
Array.isArray(attempt) ||
!ACTIVE_ATTEMPT_STATUSES.has(attempt.status) ||
attempt.id !== admission.attemptId ||
attempt.runId !== run.id ||
attempt.runId !== admission.runId ||
attempt.stepRunId !== admission.stepRunId ||
attempt.attempt !== admission.attemptNumber ||
attempt.executorType !== admission.executorType ||
attempt.createdAtMs !== admission.admittedAtMs
) {
invalid('active Attempt does not match its immutable admission');
}
counter(attempt.callbackSequence, 'Attempt callback sequence');
if (
value.leaseStatus !== null &&
!RUN_DISPATCH_LEASE_STATUSES.includes(value.leaseStatus)
) {
invalid('active Attempt lease status is invalid');
}
const stepRun = stepsById.get(admission.stepRunId);
if (!stepRun || stepRun.kind !== 'task') {
invalid('active Attempt StepRun is missing');
}
if (
attempt.status === 'claimed' ||
attempt.status === 'starting'
) {
if (
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest ||
attempt.startedAtMs !== undefined
) {
invalid('pre-start Attempt crossed its admitted StepRun epoch');
}
} else if (
stepRun.status !== 'running' ||
stepRun.version !== admission.stepRunVersion + 1 ||
stepRun.startedAtMs === null ||
attempt.startedAtMs === undefined
) {
invalid('running Attempt does not match the canonical StepRun');
}
return Object.freeze({
admission,
attempt,
leaseStatus: value.leaseStatus,
stepRun,
});
}
/**
* Converges one cancelling Workflow snapshot without inventing completion for
* active execution. Unleased pre-start claims and non-executing StepRuns are
* settled immediately; leased/starting/running Attempts remain blocked until
* worker completion or recovery crosses their own authority fences.
*/
export function resolvePluginPackageWorkflowCancellation(
snapshot: Readonly<PluginPackageWorkflowCancellationSnapshot>,
): Readonly<PluginPackageWorkflowCancellationResolution> {
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
invalid('snapshot is invalid');
}
const { cancelRequestedAtMs, cancelReason } = validateRun(snapshot.run);
const observedAtMs = timestamp(snapshot.observedAtMs, 'observation time');
if (observedAtMs < cancelRequestedAtMs) {
invalid('observation precedes cancellation intent');
}
if (
!Array.isArray(snapshot.stepRuns) ||
snapshot.stepRuns.length < 1 ||
snapshot.stepRuns.length > MAX_STEP_RUNS_PER_RUN ||
!Array.isArray(snapshot.activeTaskAttempts)
) {
invalid('Workflow StepRun or active Attempt collection is invalid');
}
const steps = snapshot.stepRuns.map((value) => {
try {
return normalizeStepRunRecord(value);
} catch {
return invalid('StepRun is invalid');
}
}).sort((left, right) =>
left.stepKey.localeCompare(right.stepKey) || left.id.localeCompare(right.id));
const stepsById = new Map<string, Readonly<StepRunRecord>>();
for (const stepRun of steps) {
if (
stepRun.runId !== snapshot.run.id ||
stepsById.has(stepRun.id) ||
observedAtMs < stepRun.updatedAtMs
) {
invalid('StepRun set is incomplete, duplicated or time-inconsistent');
}
stepsById.set(stepRun.id, stepRun);
}
const active = snapshot.activeTaskAttempts
.map((value) =>
validateActiveAttempt(snapshot.run, value, stepsById))
.sort((left, right) => left.attempt.id.localeCompare(right.attempt.id));
const activeByStepId = new Map<
string,
(typeof active)[number]
>();
for (const value of active) {
if (
activeByStepId.has(value.stepRun.id) ||
observedAtMs < value.attempt.createdAtMs ||
observedAtMs < (value.attempt.startedAtMs ?? 0)
) {
invalid('active Attempt set is duplicated or time-inconsistent');
}
activeByStepId.set(value.stepRun.id, value);
}
const terminal = terminalMapping(cancelReason);
const attemptTransitions:
PluginPackageWorkflowCancellationAttemptTransition[] = [];
const stepMutations: StepRunMutation[] = [];
const blockedAttemptIds: string[] = [];
const blockedStepRunIds = new Set<string>();
let runVersion = snapshot.run.version;
let runEventSequence = snapshot.run.eventSequence;
for (const value of active) {
const isBlocked =
value.attempt.status !== 'claimed' ||
value.leaseStatus === 'leased';
if (isBlocked) {
blockedAttemptIds.push(value.attempt.id);
blockedStepRunIds.add(value.stepRun.id);
continue;
}
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'attempt',
value.attempt.id,
value.attempt.callbackSequence,
);
runVersion += 1;
runEventSequence += 1;
const attempt = Object.freeze({
...value.attempt,
status: terminal.status,
finishedAtMs: observedAtMs,
errorCode: terminal.errorCode,
errorSummary: terminal.errorSummary,
});
const event = Object.freeze({
id: `wca:${digest}`,
runId: snapshot.run.id,
sequence: runEventSequence,
type: `workflow.task_attempt.${terminal.status}`,
dedupeKey: `wca:${digest}`,
actorType: 'reconciler' as const,
actorId: 'runtime:cancellation',
attemptId: attempt.id,
stepRunId: value.stepRun.id,
payload: Object.freeze({
execution_scope: 'workflow_task',
attempt_id: attempt.id,
step_run_id: value.stepRun.id,
from_status: 'claimed',
to_status: terminal.status,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
version: runVersion,
}),
createdAtMs: observedAtMs,
} satisfies RunEventRecord);
attemptTransitions.push(Object.freeze({
previousStatus: 'claimed' as const,
attempt,
event,
}));
}
let projectedSteps = new Map(stepsById);
for (const current of steps) {
if (
TERMINAL_STEP_STATUSES.has(
current.status as (typeof STEP_RUN_TERMINAL_STATUSES)[number],
) ||
blockedStepRunIds.has(current.id)
) {
continue;
}
if (current.status === 'running') {
blockedStepRunIds.add(current.id);
continue;
}
const target =
cancelReason === 'timeout' &&
(current.status === 'ready' ||
current.status === 'waiting_approval')
? 'timed_out'
: 'cancelled';
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'step',
current.id,
current.version,
);
const mutation = transitionStepRunMutation(
current,
{
expectedVersion: current.version,
expectedDigest: current.stepRunDigest,
mutationId: `wcm:${digest}`,
to: target,
atMs: observedAtMs,
resultCode:
target === 'timed_out'
? 'workflow_timed_out'
: 'workflow_cancelled',
...(target === 'timed_out'
? { errorSummary: terminal.errorSummary }
: {}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId: `wcs:${digest}`,
dedupeKey: `wcs:${digest}`,
actor: {
type: 'reconciler',
id: 'runtime:cancellation',
},
},
);
stepMutations.push(mutation);
projectedSteps.set(current.id, mutation.stepRun);
runVersion += 1;
runEventSequence += 1;
}
const blockedSteps = [...blockedStepRunIds].sort();
const canTerminalize =
blockedSteps.length === 0 &&
[...projectedSteps.values()].every((stepRun) =>
TERMINAL_STEP_STATUSES.has(
stepRun.status as (typeof STEP_RUN_TERMINAL_STATUSES)[number],
));
let terminalTransition:
PluginPackageWorkflowCancellationTerminalTransition | null = null;
if (canTerminalize) {
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'run',
snapshot.run.id,
runVersion,
);
terminalTransition = Object.freeze({
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
status: terminal.status,
finishedAtMs: observedAtMs,
errorCode: terminal.errorCode,
errorSummary: terminal.errorSummary,
event: Object.freeze({
id: `wcr:${digest}`,
runId: snapshot.run.id,
sequence: runEventSequence + 1,
type: `workflow.${terminal.status}`,
dedupeKey: `wcr:${digest}`,
actorType: 'reconciler',
actorId: 'runtime:cancellation',
payload: Object.freeze({
from_status: 'running',
to_status: terminal.status,
step_count: steps.length,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
version: runVersion + 1,
}),
createdAtMs: observedAtMs,
}),
});
runVersion += 1;
runEventSequence += 1;
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA,
expectedRunVersion: snapshot.run.version,
expectedRunEventSequence: snapshot.run.eventSequence,
run: Object.freeze({
...snapshot.run,
version: runVersion,
eventSequence: runEventSequence,
...(terminalTransition === null
? {}
: {
status: terminalTransition.status,
finishedAtMs: terminalTransition.finishedAtMs,
errorCode: terminalTransition.errorCode,
errorSummary: terminalTransition.errorSummary,
}),
}),
attemptTransitions: Object.freeze(attemptTransitions),
stepMutations: Object.freeze(stepMutations),
blockedAttemptIds: Object.freeze(blockedAttemptIds),
blockedStepRunIds: Object.freeze(blockedSteps),
terminalTransition,
observedAtMs,
});
}
@@ -0,0 +1,963 @@
import { createHash } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_AUTOMATION_WORKFLOWS,
normalizePluginPackageAutomationPublication,
type PluginPackageAutomationPublication,
type PluginPackageAutomationPublicationTarget,
} from '../pluginPackageAutomationPublication';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
normalizePluginPackageMaterializedRevision,
normalizePluginPackageWorkflowResource,
type PluginPackageMaterializedRevision,
type PluginPackageTaskResource,
type PluginPackageWorkflowResource,
} from '../pluginPackageResourceMaterialization';
import type { RunEventRecord, RunRecord } from '../../run/run';
import {
createStepRunMutation,
normalizeStepRunMutation,
type StepRunMutation,
} from '../../run/stepRun';
import { TaskSpecSemanticRegistry } from '../../task-definition/taskSpecSemantic';
export const PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA =
'qinglong/plugin-package-workflow-execution-plan@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_BYTES = 256 * 1024;
export const PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA =
'qinglong/plugin-package-workflow-admission-receipt@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_BYTES = 256 * 1024;
export interface PluginPackageWorkflowExecutionPlanTarget
extends PluginPackageAutomationPublicationTarget {
readonly publicationDigest: string;
readonly workflowId: string;
readonly workflowDefinitionDigest: string;
}
export interface PluginPackageWorkflowExecutionPlanStep {
readonly stepRunId: string;
readonly stepKey: string;
readonly taskId: string;
readonly taskDefinitionRef: string;
readonly taskDefinitionDigest: string;
readonly needs: readonly string[];
readonly initialStatus: 'pending' | 'ready';
readonly required: true;
}
export interface PluginPackageWorkflowExecutionPlan {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA;
readonly planId: string;
readonly runId: string;
readonly target: Readonly<PluginPackageWorkflowExecutionPlanTarget>;
readonly steps: readonly Readonly<PluginPackageWorkflowExecutionPlanStep>[];
readonly plannedAtMs: number;
readonly planDigest: string;
}
export interface CreatePluginPackageWorkflowExecutionPlanInput {
readonly planId: string;
readonly runId: string;
readonly workflowId: string;
readonly stepRunIds: Readonly<Record<string, string>>;
readonly publication: Readonly<PluginPackageAutomationPublication>;
readonly revision: Readonly<PluginPackageMaterializedRevision>;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
readonly plannedAtMs: number;
}
export interface PluginPackageWorkflowAdmissionReceiptStep {
readonly stepKey: string;
readonly stepRunId: string;
readonly stepRunDigest: string;
readonly mutationId: string;
readonly eventId: string;
}
export interface PluginPackageWorkflowAdmissionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA;
readonly planId: string;
readonly planDigest: string;
readonly runId: string;
readonly publicationDigest: string;
readonly workflowId: string;
readonly steps: readonly Readonly<PluginPackageWorkflowAdmissionReceiptStep>[];
readonly finalRunVersion: number;
readonly finalRunEventSequence: number;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageWorkflowAdmissionBundle {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly admissionEvent: Readonly<RunEventRecord>;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}
export interface PluginPackageWorkflowAdmissionRepository {
findByPlanId(
planId: string,
): Promise<Readonly<PluginPackageWorkflowAdmissionReceipt> | null>;
findByRunId(
runId: string,
): Promise<Readonly<PluginPackageWorkflowAdmissionReceipt> | null>;
admit(plan: Readonly<PluginPackageWorkflowExecutionPlan>): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}>
>;
}
export class InvalidPluginPackageWorkflowExecutionPlanError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow execution plan is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowExecutionPlanError';
}
}
export class PluginPackageWorkflowExecutionPlanConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_CONFLICT';
constructor(message: string) {
super(`Plugin Package Workflow cannot be planned: ${message}`);
this.name = 'PluginPackageWorkflowExecutionPlanConflictError';
}
}
export class InvalidPluginPackageWorkflowAdmissionReceiptError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow admission receipt is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowAdmissionReceiptError';
}
}
export class PluginPackageWorkflowAdmissionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_CONFLICT';
constructor(message: string) {
super(`Plugin Package Workflow admission conflicts with state: ${message}`);
this.name = 'PluginPackageWorkflowAdmissionConflictError';
}
}
export class PluginPackageWorkflowAdmissionNotAllowedError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_NOT_ALLOWED';
constructor() {
super('Plugin Package Workflow admission is not allowed');
this.name = 'PluginPackageWorkflowAdmissionNotAllowedError';
}
}
export class PluginPackageWorkflowAdmissionUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow admission is unavailable', options);
this.name = 'PluginPackageWorkflowAdmissionUnavailableError';
}
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PORTABLE_RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,35}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RESOURCE_ID = /^[a-z][a-z0-9-]{0,62}$/;
const DIGEST = /^[0-9a-f]{64}$/;
const PLAN_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-execution-plan-digest@v1\0',
'utf8',
);
const WORKFLOW_DEFINITION_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-definition-digest@v1\0',
'utf8',
);
const WORKFLOW_ADMISSION_RECEIPT_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-admission-receipt-digest@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowExecutionPlanError(message);
}
function portableRunId(value: unknown, label: string): string {
if (typeof value !== 'string' || !PORTABLE_RUN_ID.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function conflict(message: string): never {
throw new PluginPackageWorkflowExecutionPlanConflictError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key) => typeof key !== 'string') ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function denseArray(
value: unknown,
maximum: number,
label: string,
minimum = 1,
): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length < minimum ||
value.length > maximum
) {
return invalid(`${label} is invalid`);
}
const keys = Object.keys(value);
const ownKeys = Reflect.ownKeys(value);
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
ownKeys.length !== value.length + 1 ||
!ownKeys.includes('length') ||
keys.length !== value.length ||
keys.some((key, index) => key !== String(index)) ||
keys.some((key) => {
const descriptor = descriptors[key];
return (
descriptor === undefined ||
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true
);
})
) {
return invalid(`${label} must be a dense data array`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function resourceId(value: unknown, label: string): string {
if (typeof value !== 'string' || !RESOURCE_ID.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function positiveInteger(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > 2_147_483_647
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid('plannedAtMs is invalid');
}
return value as number;
}
function hash(domain: Buffer, value: unknown): string {
return createHash('sha256')
.update(domain)
.update(JSON.stringify(value))
.digest('hex');
}
export function pluginPackageWorkflowDefinitionDigest(
value: PluginPackageWorkflowResource,
): string {
return hash(
WORKFLOW_DEFINITION_DIGEST_DOMAIN,
normalizePluginPackageWorkflowResource(value),
);
}
function target(
value: PluginPackageWorkflowExecutionPlanTarget,
): Readonly<PluginPackageWorkflowExecutionPlanTarget> {
const record = dataRecord(value, 'plan target');
exactKeys(
record,
[
'generation',
'generationDigest',
'installationId',
'lockDigest',
'materializedRevisionDigest',
'packageName',
'projectId',
'publicationDigest',
'workflowDefinitionDigest',
'workflowId',
],
'plan target',
);
return Object.freeze({
projectId: identifier(value.projectId, 'projectId'),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
generation: positiveInteger(value.generation, 'generation'),
generationDigest: digest(value.generationDigest, 'generationDigest'),
materializedRevisionDigest: digest(
value.materializedRevisionDigest,
'materializedRevisionDigest',
),
publicationDigest: digest(value.publicationDigest, 'publicationDigest'),
workflowId: resourceId(value.workflowId, 'workflowId'),
workflowDefinitionDigest: digest(
value.workflowDefinitionDigest,
'workflowDefinitionDigest',
),
});
}
function taskDefinitionRef(
materializedRevisionDigest: string,
taskId: string,
): string {
return `plugin-package:${materializedRevisionDigest}:task:${taskId}`;
}
function normalizeStep(
value: PluginPackageWorkflowExecutionPlanStep,
planTarget: Readonly<PluginPackageWorkflowExecutionPlanTarget>,
): Readonly<PluginPackageWorkflowExecutionPlanStep> {
const step = dataRecord(value, 'plan step');
exactKeys(
step,
[
'initialStatus',
'needs',
'required',
'stepKey',
'stepRunId',
'taskDefinitionDigest',
'taskDefinitionRef',
'taskId',
],
'plan step',
);
if (
(value.initialStatus !== 'pending' && value.initialStatus !== 'ready') ||
value.required !== true
) {
return invalid('plan step status or required flag is invalid');
}
const stepKey = resourceId(value.stepKey, 'stepKey');
const taskId = resourceId(value.taskId, 'taskId');
const needs = denseArray(
value.needs,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'step needs',
0,
);
const normalizedNeeds = Object.freeze(
needs.map((need) => resourceId(need, 'step dependency')),
);
if (
new Set(normalizedNeeds).size !== normalizedNeeds.length ||
normalizedNeeds.includes(stepKey) ||
[...normalizedNeeds]
.sort()
.some((need, index) => need !== normalizedNeeds[index]) ||
(normalizedNeeds.length === 0) !== (value.initialStatus === 'ready')
) {
return invalid('step dependency or initial status is invalid');
}
const expectedReference = taskDefinitionRef(
planTarget.materializedRevisionDigest,
taskId,
);
if (value.taskDefinitionRef !== expectedReference) {
return invalid('taskDefinitionRef is not generation-bound');
}
return Object.freeze({
stepRunId: identifier(value.stepRunId, 'stepRunId'),
stepKey,
taskId,
taskDefinitionRef: expectedReference,
taskDefinitionDigest: digest(
value.taskDefinitionDigest,
'taskDefinitionDigest',
),
needs: normalizedNeeds,
initialStatus: value.initialStatus,
required: true,
});
}
export function pluginPackageWorkflowExecutionPlanDigest(
value:
| Omit<PluginPackageWorkflowExecutionPlan, 'planDigest'>
| PluginPackageWorkflowExecutionPlan,
): string {
return hash(PLAN_DIGEST_DOMAIN, {
schema: value.schema,
planId: value.planId,
runId: value.runId,
target: value.target,
steps: value.steps,
plannedAtMs: value.plannedAtMs,
});
}
function bounded(
value: Readonly<PluginPackageWorkflowExecutionPlan>,
): Readonly<PluginPackageWorkflowExecutionPlan> {
if (
Buffer.byteLength(JSON.stringify(value), 'utf8') >
MAX_PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_BYTES
) {
return invalid('encoded plan exceeds its size limit');
}
return value;
}
function assertDag(
steps: readonly Readonly<PluginPackageWorkflowExecutionPlanStep>[],
): void {
const byKey = new Map(steps.map((step) => [step.stepKey, step]));
if (
byKey.size !== steps.length ||
new Set(steps.map(({ stepRunId }) => stepRunId)).size !== steps.length ||
steps.some(({ needs }) => needs.some((need) => !byKey.has(need)))
) {
invalid('plan step identity or dependency is invalid');
}
const pending = new Map(
steps.map((step) => [step.stepKey, new Set(step.needs)]),
);
const ready = [...pending.entries()]
.filter(([, needs]) => needs.size === 0)
.map(([stepKey]) => stepKey);
let visited = 0;
while (ready.length > 0) {
const current = ready.pop()!;
if (!pending.delete(current)) continue;
visited += 1;
for (const [stepKey, needs] of pending) {
if (needs.delete(current) && needs.size === 0) ready.push(stepKey);
}
}
if (visited !== steps.length) invalid('plan graph contains a cycle');
}
export function normalizePluginPackageWorkflowExecutionPlan(
value: PluginPackageWorkflowExecutionPlan,
): Readonly<PluginPackageWorkflowExecutionPlan> {
const plan = dataRecord(value, 'plan');
exactKeys(
plan,
[
'planDigest',
'planId',
'plannedAtMs',
'runId',
'schema',
'steps',
'target',
],
'plan',
);
if (value.schema !== PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA) {
return invalid('plan schema is invalid');
}
const normalizedTarget = target(value.target);
const steps = denseArray(
value.steps,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'plan steps',
)
.map((step) =>
normalizeStep(
step as PluginPackageWorkflowExecutionPlanStep,
normalizedTarget,
),
)
.sort((left, right) => left.stepKey.localeCompare(right.stepKey));
if (
steps.some(
(step, index) => index > 0 && steps[index - 1]!.stepKey === step.stepKey,
)
) {
return invalid('plan step identity is duplicated');
}
assertDag(steps);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA,
planId: identifier(value.planId, 'planId'),
runId: portableRunId(value.runId, 'runId'),
target: normalizedTarget,
steps: Object.freeze(steps),
plannedAtMs: timestamp(value.plannedAtMs),
});
const planDigest = digest(value.planDigest, 'planDigest');
if (pluginPackageWorkflowExecutionPlanDigest(unsigned) !== planDigest) {
return invalid('planDigest does not match plan');
}
return bounded(Object.freeze({ ...unsigned, planDigest }));
}
function assertPublicationRevisionBinding(
publication: Readonly<PluginPackageAutomationPublication>,
revision: Readonly<PluginPackageMaterializedRevision>,
): void {
const generation = revision.generation;
if (
publication.state !== 'active' ||
publication.target.projectId !== generation.projectId ||
publication.target.packageName !== generation.packageName ||
publication.target.installationId !== generation.installationId ||
publication.target.lockDigest !== generation.lockDigest ||
publication.target.generation !== generation.generation ||
publication.target.generationDigest !== generation.generationDigest ||
publication.target.materializedRevisionDigest !== revision.revisionDigest
) {
conflict('publication is not the active definition of this revision');
}
}
export function createPluginPackageWorkflowExecutionPlan(
value: CreatePluginPackageWorkflowExecutionPlanInput,
): Readonly<PluginPackageWorkflowExecutionPlan> {
const input = dataRecord(value, 'create input');
exactKeys(
input,
[
'planId',
'plannedAtMs',
'publication',
'revision',
'runId',
'stepRunIds',
'taskSpecSemanticRegistry',
'workflowId',
],
'create input',
);
if (!(value.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)) {
return invalid('TaskSpec semantic registry is invalid');
}
const publication = normalizePluginPackageAutomationPublication(
value.publication,
);
const revision = normalizePluginPackageMaterializedRevision(
value.revision,
value.taskSpecSemanticRegistry,
);
assertPublicationRevisionBinding(publication, revision);
const workflowId = resourceId(value.workflowId, 'workflowId');
const publicationWorkflow = publication.definitions.workflows.find(
(workflow) => workflow.id === workflowId,
);
const revisionWorkflowResource = revision.resources.find(
(resource) =>
resource.kind === 'workflow' &&
(resource.value as PluginPackageWorkflowResource).id === workflowId,
);
if (!publicationWorkflow || !revisionWorkflowResource) {
return conflict('Workflow is not present in the exact publication');
}
const revisionWorkflow = normalizePluginPackageWorkflowResource(
revisionWorkflowResource.value,
);
const workflowDefinitionDigest =
pluginPackageWorkflowDefinitionDigest(publicationWorkflow);
if (
workflowDefinitionDigest !==
pluginPackageWorkflowDefinitionDigest(revisionWorkflow) ||
!publicationWorkflow.enabled
) {
return conflict('Workflow definition drifted or is disabled');
}
if (
publication.definitions.workflows.length >
MAX_PLUGIN_PACKAGE_AUTOMATION_WORKFLOWS
) {
return invalid('publication Workflow count exceeds the limit');
}
const tasks = new Map(
revision.resources
.filter(({ kind }) => kind === 'task')
.map((resource) => [
(resource.value as PluginPackageTaskResource).id,
resource,
]),
);
const stepRunIds = dataRecord(value.stepRunIds, 'stepRunIds');
exactKeys(
stepRunIds,
publicationWorkflow.steps.map(({ id }) => id),
'stepRunIds',
);
if (publicationWorkflow.steps.length < 1) {
return conflict('Workflow has no executable steps');
}
const planTarget = target({
...publication.target,
publicationDigest: publication.publicationDigest,
workflowId,
workflowDefinitionDigest,
});
const steps = publicationWorkflow.steps.map((step) => {
const taskResource = tasks.get(step.task);
if (!taskResource) {
return conflict('Workflow Task is absent from the exact revision');
}
const task = taskResource.value as PluginPackageTaskResource;
if (!task.enabled) {
return conflict('Workflow Task is disabled');
}
return normalizeStep(
{
stepRunId: stepRunIds[step.id] as string,
stepKey: step.id,
taskId: step.task,
taskDefinitionRef: taskDefinitionRef(
revision.revisionDigest,
step.task,
),
taskDefinitionDigest: taskResource.sourceDigest,
needs: step.needs,
initialStatus: step.needs.length === 0 ? 'ready' : 'pending',
required: true,
},
planTarget,
);
});
assertDag(steps);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA,
planId: identifier(value.planId, 'planId'),
runId: portableRunId(value.runId, 'runId'),
target: planTarget,
steps: Object.freeze(
[...steps].sort((left, right) =>
left.stepKey.localeCompare(right.stepKey),
),
),
plannedAtMs: timestamp(value.plannedAtMs),
});
const result = Object.freeze({
...unsigned,
planDigest: pluginPackageWorkflowExecutionPlanDigest(unsigned),
});
return normalizePluginPackageWorkflowExecutionPlan(result);
}
function admissionIdentity(
prefix: 'wfa' | 'wfe' | 'wfm',
planDigest: string,
index?: number,
): string {
if (index === undefined) return `${prefix}:${planDigest.slice(0, 32)}`;
const digestLength = prefix === 'wfe' ? 27 : 56;
return `${prefix}:${planDigest.slice(0, digestLength)}:${index}`;
}
function receiptStep(
value: PluginPackageWorkflowAdmissionReceiptStep,
): Readonly<PluginPackageWorkflowAdmissionReceiptStep> {
const step = dataRecord(value, 'receipt step');
exactKeys(
step,
['eventId', 'mutationId', 'stepKey', 'stepRunDigest', 'stepRunId'],
'receipt step',
);
return Object.freeze({
stepKey: resourceId(value.stepKey, 'receipt stepKey'),
stepRunId: identifier(value.stepRunId, 'receipt stepRunId'),
stepRunDigest: digest(value.stepRunDigest, 'receipt stepRunDigest'),
mutationId: identifier(value.mutationId, 'receipt mutationId'),
eventId: identifier(value.eventId, 'receipt eventId'),
});
}
function workflowAdmissionReceiptFields(
value:
| Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'>
| PluginPackageWorkflowAdmissionReceipt,
): Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'> {
return {
schema: value.schema,
planId: value.planId,
planDigest: value.planDigest,
runId: value.runId,
publicationDigest: value.publicationDigest,
workflowId: value.workflowId,
steps: value.steps,
finalRunVersion: value.finalRunVersion,
finalRunEventSequence: value.finalRunEventSequence,
admittedAtMs: value.admittedAtMs,
};
}
export function pluginPackageWorkflowAdmissionReceiptDigest(
value:
| Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'>
| PluginPackageWorkflowAdmissionReceipt,
): string {
return hash(
WORKFLOW_ADMISSION_RECEIPT_DIGEST_DOMAIN,
workflowAdmissionReceiptFields(value),
);
}
export function normalizePluginPackageWorkflowAdmissionReceipt(
value: PluginPackageWorkflowAdmissionReceipt,
): Readonly<PluginPackageWorkflowAdmissionReceipt> {
const receipt = dataRecord(value, 'admission receipt');
exactKeys(
receipt,
[
'admittedAtMs',
'finalRunEventSequence',
'finalRunVersion',
'planDigest',
'planId',
'publicationDigest',
'receiptDigest',
'runId',
'schema',
'steps',
'workflowId',
],
'admission receipt',
);
if (value.schema !== PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'schema is invalid',
);
}
const steps = denseArray(
value.steps,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'receipt steps',
)
.map((step) =>
receiptStep(step as PluginPackageWorkflowAdmissionReceiptStep),
)
.sort((left, right) => left.stepKey.localeCompare(right.stepKey));
if (
new Set(steps.map(({ stepKey }) => stepKey)).size !== steps.length ||
new Set(steps.map(({ stepRunId }) => stepRunId)).size !== steps.length ||
new Set(steps.map(({ mutationId }) => mutationId)).size !== steps.length ||
new Set(steps.map(({ eventId }) => eventId)).size !== steps.length
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'step identity is duplicated',
);
}
const finalCounter = steps.length + 1;
if (
value.finalRunVersion !== finalCounter ||
value.finalRunEventSequence !== finalCounter
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'final Run counters are invalid',
);
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA,
planId: identifier(value.planId, 'receipt planId'),
planDigest: digest(value.planDigest, 'receipt planDigest'),
runId: portableRunId(value.runId, 'receipt runId'),
publicationDigest: digest(
value.publicationDigest,
'receipt publicationDigest',
),
workflowId: resourceId(value.workflowId, 'receipt workflowId'),
steps: Object.freeze(steps),
finalRunVersion: finalCounter,
finalRunEventSequence: finalCounter,
admittedAtMs: timestamp(value.admittedAtMs),
});
const receiptDigest = digest(value.receiptDigest, 'receiptDigest');
if (pluginPackageWorkflowAdmissionReceiptDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'receiptDigest does not match receipt',
);
}
const normalized = Object.freeze({ ...unsigned, receiptDigest });
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_BYTES
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'encoded receipt exceeds its size limit',
);
}
return normalized;
}
export function createPluginPackageWorkflowAdmissionBundle(
planValue: PluginPackageWorkflowExecutionPlan,
): Readonly<PluginPackageWorkflowAdmissionBundle> {
const plan = normalizePluginPackageWorkflowExecutionPlan(planValue);
const admissionEvent = Object.freeze({
id: admissionIdentity('wfa', plan.planDigest),
runId: plan.runId,
sequence: 1,
type: 'workflow.admitted',
dedupeKey: admissionIdentity('wfa', plan.planDigest),
actorType: 'system' as const,
payload: Object.freeze({
planId: plan.planId,
planDigest: plan.planDigest,
publicationDigest: plan.target.publicationDigest,
workflowId: plan.target.workflowId,
workflowDefinitionDigest: plan.target.workflowDefinitionDigest,
stepCount: plan.steps.length,
}),
createdAtMs: plan.plannedAtMs,
} satisfies RunEventRecord);
const stepMutations = plan.steps.map((step, index) =>
normalizeStepRunMutation(
createStepRunMutation(
{
id: step.stepRunId,
runId: plan.runId,
stepKey: step.stepKey,
kind: 'task',
definitionRef: step.taskDefinitionRef,
definitionDigest: step.taskDefinitionDigest,
required: true,
initialStatus: step.initialStatus,
mutationId: admissionIdentity('wfm', plan.planDigest, index + 1),
createdAtMs: plan.plannedAtMs,
},
{
expectedRunVersion: index + 1,
expectedRunEventSequence: index + 1,
eventId: admissionIdentity('wfe', plan.planDigest, index + 1),
dedupeKey: admissionIdentity('wfe', plan.planDigest, index + 1),
actor: { type: 'system' },
},
),
),
);
const finalCounter = stepMutations.length + 1;
const run = Object.freeze({
id: plan.runId,
projectId: plan.target.projectId,
taskId: plan.target.workflowId,
taskRevision: plan.target.publicationDigest,
taskSnapshotRef:
`plugin-package:${plan.target.publicationDigest}:workflow:` +
plan.target.workflowId,
triggerType: 'plugin_package_workflow',
executionOrigin: 'system' as const,
executionOwner: 'runtime' as const,
requestId: plan.planId,
status: 'running' as const,
version: finalCounter,
eventSequence: finalCounter,
priority: 0,
idempotencyKey: `plugin-package-workflow:${plan.planId}`,
createdAtMs: plan.plannedAtMs,
startedAtMs: plan.plannedAtMs,
} satisfies RunRecord);
const receiptUnsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA,
planId: plan.planId,
planDigest: plan.planDigest,
runId: plan.runId,
publicationDigest: plan.target.publicationDigest,
workflowId: plan.target.workflowId,
steps: Object.freeze(
stepMutations.map((mutation) =>
Object.freeze({
stepKey: mutation.stepRun.stepKey,
stepRunId: mutation.stepRun.id,
stepRunDigest: mutation.stepRun.stepRunDigest,
mutationId: mutation.mutationId,
eventId: mutation.event.id,
}),
),
),
finalRunVersion: finalCounter,
finalRunEventSequence: finalCounter,
admittedAtMs: plan.plannedAtMs,
});
const receipt = normalizePluginPackageWorkflowAdmissionReceipt({
...receiptUnsigned,
receiptDigest: pluginPackageWorkflowAdmissionReceiptDigest(receiptUnsigned),
});
return Object.freeze({
plan,
run,
admissionEvent,
stepMutations: Object.freeze(stepMutations),
receipt,
});
}
@@ -0,0 +1,430 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowExecutionPlan,
type PluginPackageWorkflowExecutionPlan,
} from './pluginPackageWorkflowExecutionPlan';
import type { RunEventRecord, RunRecord, RunStatus } from '../../run/run';
import {
STEP_RUN_TERMINAL_STATUSES,
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
type StepRunStatus,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA =
'qinglong/plugin-package-workflow-frontier@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_FRONTIER_PAGE_SIZE = 64;
export type PluginPackageWorkflowTerminalStatus = Extract<
RunStatus,
'succeeded' | 'failed' | 'cancelled' | 'timed_out'
>;
export interface PluginPackageWorkflowFrontierSnapshot {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly stepRuns: readonly Readonly<StepRunRecord>[];
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowFrontierResolution {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA;
readonly runId: string;
readonly planDigest: string;
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly readyStepRunIds: readonly string[];
readonly terminalStatus: PluginPackageWorkflowTerminalStatus | null;
readonly terminalTransition: Readonly<PluginPackageWorkflowTerminalTransition> | null;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowTerminalTransition {
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly status: PluginPackageWorkflowTerminalStatus;
readonly finishedAtMs: number;
readonly errorCode: string | null;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowFrontierCursor {
readonly admittedAtMs: number;
readonly planDigest: string;
}
export interface PluginPackageWorkflowFrontierCandidate
extends PluginPackageWorkflowFrontierCursor {
readonly runId: string;
}
export interface PluginPackageWorkflowFrontierPage {
readonly candidates: readonly Readonly<PluginPackageWorkflowFrontierCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageWorkflowFrontierCursor>;
}
export interface PluginPackageWorkflowFrontierAdvanceResult {
readonly status: 'advanced' | 'unchanged' | 'terminal' | 'settled';
readonly runId: string;
readonly planDigest: string;
readonly stepMutationCount: number;
readonly readyStepRunIds: readonly string[];
readonly terminalStatus: PluginPackageWorkflowTerminalStatus | null;
readonly runVersion: number;
readonly runEventSequence: number;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowFrontierRepository {
listCandidates(query: Readonly<{
limit: number;
after?: Readonly<PluginPackageWorkflowFrontierCursor>;
}>): Promise<Readonly<PluginPackageWorkflowFrontierPage>>;
advance(
runId: string,
): Promise<Readonly<PluginPackageWorkflowFrontierAdvanceResult>>;
}
export class InvalidPluginPackageWorkflowFrontierError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow frontier is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowFrontierError';
}
}
export class PluginPackageWorkflowFrontierConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_CONFLICT';
constructor() {
super('Plugin Package Workflow frontier changed concurrently');
this.name = 'PluginPackageWorkflowFrontierConflictError';
}
}
export class PluginPackageWorkflowFrontierUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow frontier is unavailable', options);
this.name = 'PluginPackageWorkflowFrontierUnavailableError';
}
}
const FRONTIER_ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-frontier-id@v1\0',
'utf8',
);
const BLOCKING_TERMINAL_STATUSES = new Set<StepRunStatus>([
'failed',
'skipped',
'cancelled',
'timed_out',
]);
const TERMINAL_STATUSES = new Set<StepRunStatus>(
STEP_RUN_TERMINAL_STATUSES,
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowFrontierError(message);
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid('observation time is invalid');
}
return value as number;
}
function counter(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function frontierIdentity(
planDigest: string,
stepRun: Readonly<StepRunRecord>,
target: 'ready' | 'skipped',
): Readonly<{ eventId: string; mutationId: string }> {
const digest = createHash('sha256')
.update(FRONTIER_ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0', 'utf8')
.update(stepRun.id, 'utf8')
.update('\0', 'utf8')
.update(String(stepRun.version), 'utf8')
.update('\0', 'utf8')
.update(target, 'utf8')
.digest('hex');
return Object.freeze({
eventId: `wff:${digest.slice(0, 32)}`,
mutationId: `workflow-frontier:${digest}`,
});
}
function terminalIdentity(
planDigest: string,
runVersion: number,
status: PluginPackageWorkflowTerminalStatus,
): string {
const digest = createHash('sha256')
.update(FRONTIER_ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0terminal\0', 'utf8')
.update(String(runVersion), 'utf8')
.update('\0', 'utf8')
.update(status, 'utf8')
.digest('hex');
return `wft:${digest.slice(0, 32)}`;
}
function terminalErrorCode(
status: PluginPackageWorkflowTerminalStatus,
): string | null {
if (status === 'succeeded') return null;
if (status === 'failed') return 'workflow_step_failed';
if (status === 'timed_out') return 'workflow_step_timed_out';
return 'workflow_step_cancelled';
}
function validateRun(
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
run: Readonly<RunRecord>,
): void {
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== plan.runId ||
run.projectId !== plan.target.projectId ||
run.taskId !== plan.target.workflowId ||
run.taskRevision !== plan.target.publicationDigest ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.requestId !== plan.planId ||
run.idempotencyKey !== `plugin-package-workflow:${plan.planId}` ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined
) {
invalid('Run does not match the admitted Workflow');
}
counter(run.version, 'Run version');
counter(run.eventSequence, 'Run event sequence');
}
function validateStepRuns(
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
stepRunValues: readonly Readonly<StepRunRecord>[],
): ReadonlyMap<string, Readonly<StepRunRecord>> {
if (
!Array.isArray(stepRunValues) ||
stepRunValues.length !== plan.steps.length
) {
return invalid('StepRun set is incomplete');
}
const byKey = new Map<string, Readonly<StepRunRecord>>();
for (const value of stepRunValues) {
let stepRun: Readonly<StepRunRecord>;
try {
stepRun = normalizeStepRunRecord(value);
} catch {
return invalid('StepRun record is invalid');
}
const step = plan.steps.find(({ stepKey }) => stepKey === stepRun.stepKey);
if (
!step ||
byKey.has(step.stepKey) ||
stepRun.id !== step.stepRunId ||
stepRun.runId !== plan.runId ||
stepRun.parentStepRunId !== null ||
stepRun.kind !== 'task' ||
stepRun.definitionRef !== step.taskDefinitionRef ||
stepRun.definitionDigest !== step.taskDefinitionDigest ||
stepRun.required !== step.required
) {
return invalid('StepRun does not match the immutable plan');
}
byKey.set(step.stepKey, stepRun);
}
return byKey;
}
function dependencyCannotSucceed(
stepKey: string,
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
stepRuns: ReadonlyMap<string, Readonly<StepRunRecord>>,
memo: Map<string, boolean>,
visiting: Set<string>,
): boolean {
const memoized = memo.get(stepKey);
if (memoized !== undefined) return memoized;
if (visiting.has(stepKey)) {
return invalid('Workflow dependency graph is cyclic');
}
const step = plan.steps.find((candidate) => candidate.stepKey === stepKey);
const stepRun = stepRuns.get(stepKey);
if (!step || !stepRun) return invalid('Workflow dependency is missing');
if (BLOCKING_TERMINAL_STATUSES.has(stepRun.status)) {
memo.set(stepKey, true);
return true;
}
if (stepRun.status !== 'pending') {
memo.set(stepKey, false);
return false;
}
visiting.add(stepKey);
const blocked = step.needs.some((dependency) =>
dependencyCannotSucceed(
dependency,
plan,
stepRuns,
memo,
visiting,
),
);
visiting.delete(stepKey);
memo.set(stepKey, blocked);
return blocked;
}
function terminalStatus(
statuses: readonly StepRunStatus[],
): PluginPackageWorkflowTerminalStatus | null {
if (!statuses.every((status) => TERMINAL_STATUSES.has(status))) return null;
if (statuses.includes('failed') || statuses.includes('skipped')) {
return 'failed';
}
if (statuses.includes('timed_out')) return 'timed_out';
if (statuses.includes('cancelled')) return 'cancelled';
return 'succeeded';
}
export function resolvePluginPackageWorkflowFrontier(
value: PluginPackageWorkflowFrontierSnapshot,
): Readonly<PluginPackageWorkflowFrontierResolution> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('snapshot is invalid');
}
const plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
validateRun(plan, value.run);
const observedAtMs = timestamp(value.observedAtMs);
const byKey = validateStepRuns(plan, value.stepRuns);
if (
[...byKey.values()].some(
(stepRun) => observedAtMs < stepRun.updatedAtMs,
)
) {
return invalid('observation time precedes StepRun state');
}
const blockedMemo = new Map<string, boolean>();
const projectedStatuses = new Map(
[...byKey].map(([stepKey, stepRun]) => [stepKey, stepRun.status]),
);
const mutations: Readonly<StepRunMutation>[] = [];
let runVersion = value.run.version;
let runEventSequence = value.run.eventSequence;
for (const step of plan.steps) {
const stepRun = byKey.get(step.stepKey)!;
if (stepRun.status !== 'pending') continue;
const blocked = dependencyCannotSucceed(
step.stepKey,
plan,
byKey,
blockedMemo,
new Set(),
);
const allDependenciesSucceeded = step.needs.every(
(dependency) => byKey.get(dependency)!.status === 'succeeded',
);
if (!blocked && !allDependenciesSucceeded) continue;
const target = blocked ? 'skipped' : 'ready';
const identity = frontierIdentity(plan.planDigest, stepRun, target);
const mutation = transitionStepRunMutation(
stepRun,
{
expectedVersion: stepRun.version,
expectedDigest: stepRun.stepRunDigest,
mutationId: identity.mutationId,
to: target,
atMs: observedAtMs,
...(target === 'skipped'
? { resultCode: 'dependency_not_succeeded' }
: {}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId: identity.eventId,
dedupeKey: identity.eventId,
actor: { type: 'reconciler' },
},
);
mutations.push(mutation);
projectedStatuses.set(step.stepKey, target);
runVersion += 1;
runEventSequence += 1;
}
const readyStepRunIds = plan.steps
.filter((step) => projectedStatuses.get(step.stepKey) === 'ready')
.map((step) => step.stepRunId);
const aggregateStatus = terminalStatus(
plan.steps.map((step) => projectedStatuses.get(step.stepKey)!),
);
const terminalTransition =
aggregateStatus === null
? null
: (() => {
const eventId = terminalIdentity(
plan.planDigest,
runVersion,
aggregateStatus,
);
return Object.freeze({
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
status: aggregateStatus,
finishedAtMs: observedAtMs,
errorCode: terminalErrorCode(aggregateStatus),
event: Object.freeze({
id: eventId,
runId: plan.runId,
sequence: runEventSequence + 1,
type: `workflow.${aggregateStatus}`,
dedupeKey: eventId,
actorType: 'reconciler',
payload: Object.freeze({
planDigest: plan.planDigest,
workflowId: plan.target.workflowId,
stepCount: plan.steps.length,
status: aggregateStatus,
}),
createdAtMs: observedAtMs,
}),
} satisfies PluginPackageWorkflowTerminalTransition);
})();
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA,
runId: plan.runId,
planDigest: plan.planDigest,
expectedRunVersion: value.run.version,
expectedRunEventSequence: value.run.eventSequence,
stepMutations: Object.freeze(mutations),
readyStepRunIds: Object.freeze(readyStepRunIds),
terminalStatus: aggregateStatus,
terminalTransition,
observedAtMs,
});
}
@@ -0,0 +1,688 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageTaskReconciliationReceipt,
type PluginPackageTaskReconciliationReceipt,
} from '../pluginPackageTaskReconciliation';
import {
normalizePluginPackageWorkflowExecutionPlan,
type PluginPackageWorkflowExecutionPlan,
} from './pluginPackageWorkflowExecutionPlan';
import {
normalizeClusterTaskExecutionRevision,
type ClusterTaskExecutionRevision,
} from '../../task-definition/clusterExecutionRevision';
import {
normalizeLocalTaskExecutionRevision,
type LocalTaskExecutionRevision,
} from '../../local-runtime/localDispatch';
import type { RunAttemptRecord, RunEventRecord, RunRecord } from '../../run/run';
import {
MAX_STEP_RUN_ATTEMPTS,
normalizeStepRunRecord,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA =
'qinglong/plugin-package-workflow-task-attempt-admission@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS =
128 * MAX_STEP_RUN_ATTEMPTS;
export type PluginPackageWorkflowTaskExecutorType =
| 'local_process'
| 'remote_worker';
export interface PluginPackageWorkflowTaskExecutionBinding {
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly taskDefinitionDigest: string;
readonly executorType: PluginPackageWorkflowTaskExecutorType;
readonly executionDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionReceipt {
readonly schema:
typeof PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA;
readonly attemptId: string;
readonly planDigest: string;
readonly runId: string;
readonly stepRunId: string;
readonly stepRunVersion: number;
readonly stepRunDigest: string;
readonly resourceTaskId: string;
readonly taskReconciliationReceiptDigest: string;
readonly taskId: string;
readonly taskRevision: string;
readonly taskDefinitionDigest: string;
readonly executorType: PluginPackageWorkflowTaskExecutorType;
readonly executionDigest: string;
readonly attemptNumber: number;
readonly eventId: string;
readonly runVersion: number;
readonly runEventSequence: number;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionBundle {
readonly receipt: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly event: Readonly<RunEventRecord>;
readonly run: Readonly<RunRecord>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionCursor {
readonly readyAtMs: number;
readonly stepRunId: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionCandidate
extends PluginPackageWorkflowTaskAttemptAdmissionCursor {
readonly runId: string;
readonly planDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionPage {
readonly candidates: readonly Readonly<PluginPackageWorkflowTaskAttemptAdmissionCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageWorkflowTaskAttemptAdmissionCursor>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionResult {
readonly status: 'created' | 'existing';
readonly receipt: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionRepository {
listCandidates(query: Readonly<{
limit: number;
after?: Readonly<PluginPackageWorkflowTaskAttemptAdmissionCursor>;
}>): Promise<
Readonly<PluginPackageWorkflowTaskAttemptAdmissionPage>
>;
admit(
runId: string,
stepRunId: string,
): Promise<
Readonly<PluginPackageWorkflowTaskAttemptAdmissionResult>
>;
}
export interface CreatePluginPackageWorkflowTaskAttemptAdmissionInput {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly stepRun: Readonly<StepRunRecord>;
readonly taskReconciliation:
Readonly<PluginPackageTaskReconciliationReceipt>;
readonly execution: Readonly<
LocalTaskExecutionRevision | ClusterTaskExecutionRevision
>;
readonly attemptNumber: number;
readonly admittedAtMs: number;
}
export class InvalidPluginPackageWorkflowTaskAttemptAdmissionError
extends TypeError
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow Task Attempt admission is invalid: ${message}`,
);
this.name =
'InvalidPluginPackageWorkflowTaskAttemptAdmissionError';
}
}
export class PluginPackageWorkflowTaskAttemptAdmissionConflictError
extends Error
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_CONFLICT';
constructor() {
super('Plugin Package Workflow Task Attempt admission conflicts with state');
this.name =
'PluginPackageWorkflowTaskAttemptAdmissionConflictError';
}
}
export class PluginPackageWorkflowTaskAttemptAdmissionUnavailableError
extends Error
{
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow Task Attempt admission is unavailable', {
cause: options?.cause,
});
this.name =
'PluginPackageWorkflowTaskAttemptAdmissionUnavailableError';
}
}
const DIGEST = /^[0-9a-f]{64}$/;
const IDENTITY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TASK_REVISION = /^qltd:v1:([1-9][0-9]{0,9}):([0-9a-f]{64})$/;
const ACTIVE_RECONCILIATION_DISPOSITIONS = new Set([
'created',
'retained',
'updated',
]);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-attempt-id@v1\0',
'utf8',
);
const RECEIPT_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-attempt-receipt@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowTaskAttemptAdmissionError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.getPrototypeOf(value) !== Object.prototype
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function identity(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTITY.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function integer(
value: unknown,
minimum: number,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
return integer(value, 0, Number.MAX_SAFE_INTEGER, label);
}
function taskIdentity(packageName: string, resourceTaskId: string): string {
return identity(
`pkg:${packageName}:${resourceTaskId}`,
'runtime Task identity',
);
}
function executionBinding(
value: Readonly<
LocalTaskExecutionRevision | ClusterTaskExecutionRevision
>,
): Readonly<PluginPackageWorkflowTaskExecutionBinding> {
let normalized:
| Readonly<LocalTaskExecutionRevision>
| Readonly<ClusterTaskExecutionRevision>;
try {
normalized =
value?.executorType === 'local_process'
? normalizeLocalTaskExecutionRevision(
value as LocalTaskExecutionRevision,
)
: value?.executorType === 'remote_worker'
? normalizeClusterTaskExecutionRevision(
value as ClusterTaskExecutionRevision,
)
: invalid('execution revision executorType is invalid');
} catch (error) {
if (
error instanceof
InvalidPluginPackageWorkflowTaskAttemptAdmissionError
) {
throw error;
}
return invalid('execution revision is invalid');
}
const taskRevision = identity(
normalized.taskRevision,
'execution revision taskRevision',
);
const revisionMatch = TASK_REVISION.exec(taskRevision);
if (!revisionMatch) {
invalid('execution revision Task identity is inconsistent');
}
const taskDefinitionDigest = revisionMatch[2]!;
return Object.freeze({
projectId: identity(normalized.projectId, 'execution revision projectId'),
taskId: identity(normalized.taskId, 'execution revision taskId'),
taskRevision,
taskDefinitionDigest,
executorType: normalized.executorType,
executionDigest: digest(
normalized.contentDigest,
'execution revision contentDigest',
),
});
}
function admissionIdentity(
planDigest: string,
stepRunId: string,
stepRunVersion: number,
): Readonly<{ attemptId: string; eventId: string }> {
const value = createHash('sha256')
.update(ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0', 'utf8')
.update(stepRunId, 'utf8')
.update('\0', 'utf8')
.update(String(stepRunVersion), 'utf8')
.digest('hex');
return Object.freeze({
attemptId: `wta:${value.slice(0, 32)}`,
eventId: `wte:${value.slice(0, 32)}`,
});
}
function unsignedReceipt(
value: Omit<
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
'receiptDigest'
>,
): object {
return {
schema: value.schema,
attemptId: value.attemptId,
planDigest: value.planDigest,
runId: value.runId,
stepRunId: value.stepRunId,
stepRunVersion: value.stepRunVersion,
stepRunDigest: value.stepRunDigest,
resourceTaskId: value.resourceTaskId,
taskReconciliationReceiptDigest:
value.taskReconciliationReceiptDigest,
taskId: value.taskId,
taskRevision: value.taskRevision,
taskDefinitionDigest: value.taskDefinitionDigest,
executorType: value.executorType,
executionDigest: value.executionDigest,
attemptNumber: value.attemptNumber,
eventId: value.eventId,
runVersion: value.runVersion,
runEventSequence: value.runEventSequence,
admittedAtMs: value.admittedAtMs,
};
}
export function pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(
value: Omit<
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
'receiptDigest'
>,
): string {
return createHash('sha256')
.update(RECEIPT_DOMAIN)
.update(JSON.stringify(unsignedReceipt(value)), 'utf8')
.digest('hex');
}
export function normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
value: PluginPackageWorkflowTaskAttemptAdmissionReceipt,
): Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt> {
const receipt = dataRecord(value, 'admission receipt');
exactKeys(
receipt,
[
'admittedAtMs',
'attemptId',
'attemptNumber',
'eventId',
'executionDigest',
'executorType',
'planDigest',
'receiptDigest',
'resourceTaskId',
'runEventSequence',
'runId',
'runVersion',
'schema',
'stepRunDigest',
'stepRunId',
'stepRunVersion',
'taskDefinitionDigest',
'taskId',
'taskReconciliationReceiptDigest',
'taskRevision',
],
[],
'admission receipt',
);
if (
value.schema !==
PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA
) {
invalid('admission receipt schema is invalid');
}
const executorType = value.executorType;
if (executorType !== 'local_process' && executorType !== 'remote_worker') {
invalid('admission receipt executorType is invalid');
}
const taskDefinitionDigest = digest(
value.taskDefinitionDigest,
'admission receipt taskDefinitionDigest',
);
const taskRevision = identity(
value.taskRevision,
'admission receipt taskRevision',
);
const revisionMatch = TASK_REVISION.exec(taskRevision);
if (!revisionMatch || revisionMatch[2] !== taskDefinitionDigest) {
invalid('admission receipt Task revision is inconsistent');
}
const runVersion = integer(
value.runVersion,
1,
2_147_483_647,
'admission receipt Run version',
);
const runEventSequence = integer(
value.runEventSequence,
1,
2_147_483_647,
'admission receipt Run event sequence',
);
if (runVersion !== runEventSequence) {
invalid('admission receipt Run counters are inconsistent');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA,
attemptId: identity(value.attemptId, 'admission receipt attemptId'),
planDigest: digest(value.planDigest, 'admission receipt planDigest'),
runId: identity(value.runId, 'admission receipt runId'),
stepRunId: identity(value.stepRunId, 'admission receipt stepRunId'),
stepRunVersion: integer(
value.stepRunVersion,
1,
2_147_483_647,
'admission receipt StepRun version',
),
stepRunDigest: digest(
value.stepRunDigest,
'admission receipt StepRun digest',
),
resourceTaskId: identity(
value.resourceTaskId,
'admission receipt resourceTaskId',
),
taskReconciliationReceiptDigest: digest(
value.taskReconciliationReceiptDigest,
'admission receipt Task reconciliation digest',
),
taskId: identity(value.taskId, 'admission receipt taskId'),
taskRevision,
taskDefinitionDigest,
executorType,
executionDigest: digest(
value.executionDigest,
'admission receipt executionDigest',
),
attemptNumber: integer(
value.attemptNumber,
1,
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS,
'admission receipt attemptNumber',
),
eventId: identity(value.eventId, 'admission receipt eventId'),
runVersion,
runEventSequence,
admittedAtMs: timestamp(
value.admittedAtMs,
'admission receipt admittedAtMs',
),
});
const receiptDigest = digest(
value.receiptDigest,
'admission receipt receiptDigest',
);
if (
pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(unsigned) !==
receiptDigest
) {
invalid('admission receipt digest does not match');
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function createPluginPackageWorkflowTaskAttemptAdmission(
value: CreatePluginPackageWorkflowTaskAttemptAdmissionInput,
): Readonly<PluginPackageWorkflowTaskAttemptAdmissionBundle> {
const input = dataRecord(value, 'admission input');
exactKeys(
input,
[
'admittedAtMs',
'attemptNumber',
'execution',
'plan',
'run',
'stepRun',
'taskReconciliation',
],
[],
'admission input',
);
let plan: Readonly<PluginPackageWorkflowExecutionPlan>;
let stepRun: Readonly<StepRunRecord>;
let taskReconciliation:
Readonly<PluginPackageTaskReconciliationReceipt>;
try {
plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
stepRun = normalizeStepRunRecord(value.stepRun);
taskReconciliation =
normalizePluginPackageTaskReconciliationReceipt(
value.taskReconciliation,
);
} catch {
return invalid('durable Workflow evidence is invalid');
}
const execution = executionBinding(value.execution);
const attemptNumber = integer(
value.attemptNumber,
1,
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS,
'attemptNumber',
);
const admittedAtMs = timestamp(value.admittedAtMs, 'admittedAtMs');
const run = value.run;
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== plan.runId ||
run.projectId !== plan.target.projectId ||
run.taskId !== plan.target.workflowId ||
run.taskRevision !== plan.target.publicationDigest ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.requestId !== plan.planId ||
run.idempotencyKey !== `plugin-package-workflow:${plan.planId}` ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined ||
!Number.isSafeInteger(run.version) ||
run.version < 1 ||
run.version !== run.eventSequence
) {
invalid('Run does not match the admitted Workflow aggregate');
}
const planStep = plan.steps.find(
({ stepRunId }) => stepRunId === stepRun.id,
);
if (
!planStep ||
stepRun.runId !== run.id ||
stepRun.stepKey !== planStep.stepKey ||
stepRun.kind !== 'task' ||
stepRun.definitionRef !== planStep.taskDefinitionRef ||
stepRun.definitionDigest !== planStep.taskDefinitionDigest ||
stepRun.required !== planStep.required ||
stepRun.status !== 'ready' ||
stepRun.attemptCount >= MAX_STEP_RUN_ATTEMPTS
) {
invalid('StepRun is not one exact ready Task from the plan');
}
if (
taskReconciliation.projectId !== plan.target.projectId ||
taskReconciliation.packageName !== plan.target.packageName ||
taskReconciliation.generation !== plan.target.generation ||
taskReconciliation.generationDigest !== plan.target.generationDigest ||
taskReconciliation.materializedRevisionDigest !==
plan.target.materializedRevisionDigest ||
taskReconciliation.lockDigest !== plan.target.lockDigest
) {
invalid('Task reconciliation does not match the immutable plan');
}
const expectedTaskId = taskIdentity(
plan.target.packageName,
planStep.taskId,
);
const item = taskReconciliation.items.find(
({ taskId }) => taskId === expectedTaskId,
);
if (
!item ||
!ACTIVE_RECONCILIATION_DISPOSITIONS.has(item.disposition) ||
execution.projectId !== plan.target.projectId ||
execution.taskId !== item.taskId ||
execution.taskDefinitionDigest !== item.contentDigest ||
execution.taskRevision !==
`qltd:v1:${item.revision}:${item.contentDigest}`
) {
invalid('execution binding is not the reconciled Task revision');
}
if (
admittedAtMs < plan.plannedAtMs ||
admittedAtMs < taskReconciliation.committedAtMs ||
admittedAtMs < stepRun.updatedAtMs
) {
invalid('admission time precedes durable evidence');
}
if (
run.version >= 2_147_483_647 ||
run.eventSequence >= 2_147_483_647
) {
invalid('Run counters overflowed');
}
const ids = admissionIdentity(
plan.planDigest,
stepRun.id,
stepRun.version,
);
const nextRun = Object.freeze({
...run,
version: run.version + 1,
eventSequence: run.eventSequence + 1,
});
const attempt = Object.freeze({
id: ids.attemptId,
runId: run.id,
stepRunId: stepRun.id,
attempt: attemptNumber,
status: 'claimed' as const,
executorType: execution.executorType,
callbackSequence: 0,
createdAtMs: admittedAtMs,
} satisfies RunAttemptRecord);
const event = Object.freeze({
id: ids.eventId,
runId: run.id,
sequence: nextRun.eventSequence,
type: 'workflow.task_attempt_admitted',
dedupeKey: ids.eventId,
actorType: 'system' as const,
attemptId: attempt.id,
stepRunId: stepRun.id,
payload: Object.freeze({
planDigest: plan.planDigest,
stepRunId: stepRun.id,
stepRunVersion: stepRun.version,
resourceTaskId: planStep.taskId,
taskId: execution.taskId,
taskRevision: execution.taskRevision,
executorType: execution.executorType,
executionDigest: execution.executionDigest,
attemptNumber,
}),
createdAtMs: admittedAtMs,
} satisfies RunEventRecord);
const receiptUnsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA,
attemptId: attempt.id,
planDigest: plan.planDigest,
runId: run.id,
stepRunId: stepRun.id,
stepRunVersion: stepRun.version,
stepRunDigest: stepRun.stepRunDigest,
resourceTaskId: planStep.taskId,
taskReconciliationReceiptDigest: taskReconciliation.receiptDigest,
taskId: execution.taskId,
taskRevision: execution.taskRevision,
taskDefinitionDigest: execution.taskDefinitionDigest,
executorType: execution.executorType,
executionDigest: execution.executionDigest,
attemptNumber,
eventId: event.id,
runVersion: nextRun.version,
runEventSequence: nextRun.eventSequence,
admittedAtMs,
});
const receipt =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt({
...receiptUnsigned,
receiptDigest:
pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(
receiptUnsigned,
),
});
return Object.freeze({ receipt, attempt, event, run: nextRun });
}
@@ -0,0 +1,391 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt,
type PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from './pluginPackageWorkflowTaskAttemptAdmission';
import type { RunAttemptRecord, RunEventRecord, RunRecord } from '../../run/run';
import {
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA =
'qinglong/plugin-package-workflow-task-recovery@v1' as const;
export type PluginPackageWorkflowTaskRecoveryReason =
| 'unstarted_claim_expired'
| 'execution_not_running';
export interface PluginPackageWorkflowTaskRecoveryInput {
readonly admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly run: Readonly<RunRecord>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly stepRun: Readonly<StepRunRecord>;
readonly reason: PluginPackageWorkflowTaskRecoveryReason;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowTaskRecoveryBundle {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA;
readonly disposition: 'requeued' | 'failed';
readonly run: Readonly<RunRecord>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly attemptEvent: Readonly<RunEventRecord>;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
}
export class InvalidPluginPackageWorkflowTaskRecoveryError
extends TypeError
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow Task recovery is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowTaskRecoveryError';
}
}
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-recovery-id@v1\0',
'utf8',
);
const LOST_ERROR_CODE = Object.freeze({
unstarted_claim_expired:
'CLUSTER_RECOVERY_UNSTARTED_CLAIM_EXPIRED',
execution_not_running:
'CLUSTER_RECOVERY_EXECUTION_NOT_RUNNING',
});
const LOST_ERROR_SUMMARY = Object.freeze({
unstarted_claim_expired:
'The Workflow Task Attempt claim expired before execution started',
execution_not_running:
'Trusted execution evidence proved that the Workflow Task Attempt is not running',
});
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowTaskRecoveryError(message);
}
function safeInteger(
value: unknown,
minimum: number,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function identity(
attempt: Readonly<RunAttemptRecord>,
stepRun: Readonly<StepRunRecord>,
reason: PluginPackageWorkflowTaskRecoveryReason,
): Readonly<{
attemptEventId: string;
requeueMutationId: string;
requeueEventId: string;
lostMutationId: string;
lostEventId: string;
failedMutationId: string;
failedEventId: string;
}> {
const digest = createHash('sha256')
.update(ID_DOMAIN)
.update(attempt.runId, 'utf8')
.update('\0', 'utf8')
.update(attempt.id, 'utf8')
.update('\0', 'utf8')
.update(String(attempt.callbackSequence), 'utf8')
.update('\0', 'utf8')
.update(stepRun.id, 'utf8')
.update('\0', 'utf8')
.update(String(stepRun.version), 'utf8')
.update('\0', 'utf8')
.update(reason, 'utf8')
.digest('hex')
.slice(0, 32);
return Object.freeze({
attemptEventId: `wra:${digest}`,
requeueMutationId: `wrq:${digest}`,
requeueEventId: `wqe:${digest}`,
lostMutationId: `wrl:${digest}`,
lostEventId: `wle:${digest}`,
failedMutationId: `wrf:${digest}`,
failedEventId: `wfe:${digest}`,
});
}
function validateAuthority(
input: Readonly<PluginPackageWorkflowTaskRecoveryInput>,
admission: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>,
stepRun: Readonly<StepRunRecord>,
): void {
const { run, attempt, reason } = input;
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== admission.runId ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined
) {
invalid('Run is not an active runtime-owned Workflow aggregate');
}
const runVersion = safeInteger(
run.version,
1,
2_147_483_644,
'Run version',
);
const runEventSequence = safeInteger(
run.eventSequence,
1,
2_147_483_644,
'Run event sequence',
);
if (
runVersion !== runEventSequence ||
admission.runVersion > runVersion ||
admission.runEventSequence > runEventSequence
) {
invalid('Run aggregate counters do not contain the admission event');
}
if (
!attempt ||
typeof attempt !== 'object' ||
Array.isArray(attempt) ||
attempt.id !== admission.attemptId ||
attempt.runId !== run.id ||
attempt.stepRunId !== admission.stepRunId ||
attempt.attempt !== admission.attemptNumber ||
attempt.executorType !== admission.executorType ||
attempt.createdAtMs !== admission.admittedAtMs ||
!ACTIVE_ATTEMPT_STATUSES.has(attempt.status)
) {
invalid('Attempt is not the active admission-bound Workflow Task Attempt');
}
safeInteger(
attempt.callbackSequence,
0,
2_147_483_647,
'Attempt callback sequence',
);
if (
stepRun.id !== admission.stepRunId ||
stepRun.runId !== run.id ||
stepRun.kind !== 'task'
) {
invalid('StepRun is not the admitted Workflow Task');
}
if (reason === 'unstarted_claim_expired') {
if (
attempt.status !== 'claimed' ||
attempt.startedAtMs !== undefined ||
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest
) {
invalid('unstarted recovery crossed the Workflow Task start barrier');
}
} else if (attempt.status === 'starting') {
if (
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest
) {
invalid('starting recovery does not match the admitted StepRun epoch');
}
} else if (
attempt.status !== 'running' ||
stepRun.status !== 'running' ||
stepRun.version !== admission.stepRunVersion + 1 ||
stepRun.startedAtMs === null
) {
invalid('running recovery does not match the canonical StepRun');
}
}
function transitionTime(
observedAtMs: number,
run: Readonly<RunRecord>,
attempt: Readonly<RunAttemptRecord>,
stepRun: Readonly<StepRunRecord>,
): number {
const atMs = safeInteger(
observedAtMs,
0,
Number.MAX_SAFE_INTEGER,
'recovery observation time',
);
const lowerBound = Math.max(
run.createdAtMs,
run.startedAtMs ?? 0,
attempt.createdAtMs,
attempt.startedAtMs ?? 0,
attempt.finishedAtMs ?? 0,
stepRun.createdAtMs,
stepRun.updatedAtMs,
stepRun.startedAtMs ?? 0,
stepRun.finishedAtMs ?? 0,
);
if (atMs < lowerBound) {
invalid('recovery observation precedes durable state');
}
return atMs;
}
/**
* Resolves only one immutable, admission-bound Workflow Task Attempt.
*
* An expired pre-start claim is safe to requeue by refreshing the exact
* `ready` StepRun epoch. Once the start barrier has been crossed, v1 fails the
* StepRun after trusted absence evidence instead of silently duplicating an
* external side effect. The Workflow aggregate Run remains `running`; its
* frontier owns final aggregation.
*/
export function buildPluginPackageWorkflowTaskRecovery(
input: Readonly<PluginPackageWorkflowTaskRecoveryInput>,
): Readonly<PluginPackageWorkflowTaskRecoveryBundle> {
let admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
let stepRun: Readonly<StepRunRecord>;
try {
admission =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
input.admission,
);
stepRun = normalizeStepRunRecord(input.stepRun);
} catch {
return invalid('durable admission or StepRun evidence is invalid');
}
if (
input.reason !== 'unstarted_claim_expired' &&
input.reason !== 'execution_not_running'
) {
invalid('recovery reason is invalid');
}
validateAuthority(input, admission, stepRun);
const atMs = transitionTime(
input.observedAtMs,
input.run,
input.attempt,
stepRun,
);
const ids = identity(input.attempt, stepRun, input.reason);
const errorCode = LOST_ERROR_CODE[input.reason];
const errorSummary = LOST_ERROR_SUMMARY[input.reason];
let runVersion = input.run.version + 1;
let runEventSequence = input.run.eventSequence + 1;
const attempt = Object.freeze({
...input.attempt,
status: 'lost' as const,
finishedAtMs: atMs,
errorCode,
errorSummary,
});
const attemptEvent = Object.freeze({
id: ids.attemptEventId,
runId: input.run.id,
sequence: runEventSequence,
type: 'workflow.task_attempt.lost',
dedupeKey: ids.attemptEventId,
actorType: 'system' as const,
attemptId: attempt.id,
stepRunId: stepRun.id,
payload: Object.freeze({
execution_scope: 'workflow_task',
attempt_id: attempt.id,
step_run_id: stepRun.id,
from_status: input.attempt.status,
to_status: 'lost',
reason: input.reason,
error_code: errorCode,
version: runVersion,
}),
createdAtMs: atMs,
} satisfies RunEventRecord);
const stepMutations: Readonly<StepRunMutation>[] = [];
const transition = (
mutationId: string,
eventId: string,
to: 'ready' | 'lost' | 'failed',
): void => {
const mutation = transitionStepRunMutation(
stepRun,
{
expectedVersion: stepRun.version,
expectedDigest: stepRun.stepRunDigest,
mutationId,
to,
atMs,
...(to === 'ready'
? {}
: {
resultCode: 'cluster_recovery_execution_not_running',
errorSummary,
}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId,
dedupeKey: eventId,
actor: { type: 'system' },
},
);
stepMutations.push(mutation);
stepRun = mutation.stepRun;
runVersion += 1;
runEventSequence += 1;
};
if (input.reason === 'unstarted_claim_expired') {
transition(
ids.requeueMutationId,
ids.requeueEventId,
'ready',
);
} else if (input.attempt.status === 'starting') {
transition(
ids.failedMutationId,
ids.failedEventId,
'failed',
);
} else {
transition(ids.lostMutationId, ids.lostEventId, 'lost');
transition(
ids.failedMutationId,
ids.failedEventId,
'failed',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA,
disposition:
input.reason === 'unstarted_claim_expired' ? 'requeued' : 'failed',
run: Object.freeze({
...input.run,
version: runVersion,
eventSequence: runEventSequence,
}),
attempt,
attemptEvent,
stepMutations: Object.freeze(stepMutations),
});
}
@@ -0,0 +1,156 @@
import { timingSafeEqual } from 'node:crypto';
import type { ClusterTaskExecutionRevision } from '../task-definition/clusterExecutionRevision';
import {
CLUSTER_EXECUTOR_TYPE,
normalizeClusterTaskExecutionRevision,
} from '../task-definition/clusterExecutionRevision';
import type { RunDispatchLeaseRecord } from '../run/runDispatchLease';
import {
assertRunDispatchId,
assertRunDispatchLeaseRecord,
digestRunDispatchLeaseToken,
} from '../run/runDispatchLease';
import {
assertWorkerId,
assertWorkerSessionId,
} from '../worker/workerSession';
export * from './remoteWorkerPlacement';
export const MAX_REMOTE_DISPATCH_PAGE_SIZE = 64;
const SHA256 = /^[a-f0-9]{64}$/;
export interface ClusterDispatchCandidateCursor {
readonly priority: number;
readonly queuedAtMs: number;
readonly attemptCreatedAtMs: number;
readonly attemptId: string;
}
export interface ClusterDispatchCandidate extends ClusterDispatchCandidateCursor {
readonly runId: string;
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly attemptNumber: number;
readonly executorType: typeof CLUSTER_EXECUTOR_TYPE;
}
export interface ClusterDispatchCandidatePage {
readonly observedAtMs: number;
readonly candidates: readonly ClusterDispatchCandidate[];
readonly truncated: boolean;
readonly next?: ClusterDispatchCandidateCursor;
}
export interface ClusterDispatchRecovery {
readonly observedAtMs: number;
readonly candidate: ClusterDispatchCandidate;
readonly lease: RunDispatchLeaseRecord;
readonly workerCurrent: boolean;
}
export interface ClusterDispatchSource {
listClusterDispatchCandidates(options: Readonly<{
limit: number;
after?: ClusterDispatchCandidateCursor;
}>): Promise<ClusterDispatchCandidatePage>;
findClusterDispatchRecovery(offerId: string): Promise<ClusterDispatchRecovery | null>;
}
export interface ClusterRemoteExecutionOffer {
readonly offerId: string;
readonly deliveryKind: 'new_claim' | 'lease_recovery';
readonly executionDigest: string;
readonly candidate: ClusterDispatchCandidate;
readonly worker: Readonly<{
workerId: string;
sessionId: string;
generation: number;
}>;
readonly lease: RunDispatchLeaseRecord;
/** Ephemeral capability supplied by the Worker; never persist or log it. */
readonly leaseToken: string;
readonly executionRevision: ClusterTaskExecutionRevision;
readonly placementScore: number;
}
function invalid(message: string): never {
throw new TypeError(`Remote dispatch value is invalid: ${message}`);
}
function safeInteger(value: unknown, label: string, minimum = 0): number {
if (!Number.isSafeInteger(value) || (value as number) < minimum) invalid(`${label} is invalid`);
return value as number;
}
export function normalizeClusterDispatchCandidate(value: ClusterDispatchCandidate): ClusterDispatchCandidate {
if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('candidate is invalid');
for (const [label, id] of [
['runId', value.runId], ['attemptId', value.attemptId], ['projectId', value.projectId],
['taskId', value.taskId], ['taskRevision', value.taskRevision],
] as const) assertRunDispatchId(label, id);
if (!Number.isSafeInteger(value.priority)) invalid('candidate priority is invalid');
safeInteger(value.queuedAtMs, 'candidate queuedAtMs');
safeInteger(value.attemptCreatedAtMs, 'candidate attemptCreatedAtMs');
safeInteger(value.attemptNumber, 'candidate attemptNumber', 1);
if (value.executorType !== CLUSTER_EXECUTOR_TYPE) invalid('candidate executorType is invalid');
return Object.freeze({ ...value });
}
export function normalizeClusterDispatchCursor(value: ClusterDispatchCandidateCursor): ClusterDispatchCandidateCursor {
if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('cursor is invalid');
if (!Number.isSafeInteger(value.priority)) invalid('cursor priority is invalid');
safeInteger(value.queuedAtMs, 'cursor queuedAtMs');
safeInteger(value.attemptCreatedAtMs, 'cursor attemptCreatedAtMs');
assertRunDispatchId('attemptId', value.attemptId);
return Object.freeze({ ...value });
}
export function assertRemoteDispatchPageSize(limit: number): void {
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_REMOTE_DISPATCH_PAGE_SIZE) {
throw new RangeError(`Remote dispatch page size must be between 1 and ${MAX_REMOTE_DISPATCH_PAGE_SIZE}`);
}
}
export function createClusterRemoteExecutionOffer(value: ClusterRemoteExecutionOffer): ClusterRemoteExecutionOffer {
assertRunDispatchId('offerId', value.offerId);
const candidate = normalizeClusterDispatchCandidate(value.candidate);
assertWorkerId(value.worker.workerId);
assertWorkerSessionId(value.worker.sessionId);
safeInteger(value.worker.generation, 'offer worker generation', 1);
assertRunDispatchLeaseRecord(value.lease);
if (
value.lease.status !== 'leased' ||
value.lease.attemptId !== candidate.attemptId || value.lease.runId !== candidate.runId ||
value.lease.workerId !== value.worker.workerId ||
value.lease.workerSessionId !== value.worker.sessionId ||
value.lease.workerGeneration !== value.worker.generation ||
digestRunDispatchLeaseToken(value.leaseToken) !== value.lease.leaseTokenDigest
) invalid('offer authority does not match');
const executionRevision = normalizeClusterTaskExecutionRevision(value.executionRevision);
if (
executionRevision.projectId !== candidate.projectId ||
executionRevision.taskId !== candidate.taskId ||
executionRevision.taskRevision !== candidate.taskRevision
) invalid('offer execution revision does not match candidate');
if (!SHA256.test(value.executionDigest) || value.executionDigest !== executionRevision.contentDigest) invalid('offer execution digest does not match');
if (!Number.isSafeInteger(value.placementScore) || value.placementScore < 0) invalid('offer placement score is invalid');
return Object.freeze({
offerId: value.offerId,
deliveryKind: value.deliveryKind,
executionDigest: value.executionDigest,
candidate,
worker: Object.freeze({ ...value.worker }),
lease: Object.freeze({ ...value.lease }),
leaseToken: value.leaseToken,
executionRevision,
placementScore: value.placementScore,
});
}
export function leaseTokenMatchesDigest(token: string, digest: string): boolean {
const actual = Buffer.from(digestRunDispatchLeaseToken(token), 'hex');
const expected = SHA256.test(digest) ? Buffer.from(digest, 'hex') : Buffer.alloc(0);
return actual.length === expected.length && timingSafeEqual(actual, expected);
}
@@ -0,0 +1,381 @@
import type { ClusterRemoteExecutionOffer } from './remoteDispatch';
import {
createClusterRemoteExecutionOffer,
normalizeClusterDispatchCandidate,
} from './remoteDispatch';
import {
assertRunDispatchId,
assertRunDispatchLeaseToken,
digestRunDispatchLeaseToken,
} from '../run/runDispatchLease';
import {
assertWorkerId,
assertWorkerSessionId,
} from '../worker/workerSession';
export const REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA =
'qinglong/remote-execution-offer@v1';
export const MAX_REMOTE_EXECUTION_OFFER_RESPONSE_BYTES = 128 * 1024;
const IDLE_REASONS = [
'worker_unavailable',
'no_candidates',
'no_match',
'plans_unavailable',
'claim_raced',
'claim_budget_exhausted',
'scan_budget_exhausted',
] as const;
export type RemoteExecutionOfferIdleReason = (typeof IDLE_REASONS)[number];
export interface RemoteExecutionOfferClaimAuthority {
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly offerId: string;
readonly leaseToken: string;
}
export interface RemoteExecutionOfferDeliveryStats {
readonly pages: number;
readonly candidates: number;
readonly plansUnavailable: number;
readonly placementMismatches: number;
readonly claimAttempts: number;
readonly claimRaces: number;
}
export type RemoteExecutionOfferPullResult =
| Readonly<{
status: 'offered';
offer: ClusterRemoteExecutionOffer;
stats: RemoteExecutionOfferDeliveryStats;
truncated: boolean;
}>
| Readonly<{
status: 'idle';
reason: RemoteExecutionOfferIdleReason;
stats: RemoteExecutionOfferDeliveryStats;
truncated: boolean;
}>;
export type RemoteExecutionOfferPullBody =
| Readonly<{
schema: typeof REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA;
status: 'offered';
offer: Readonly<{
offerId: string;
deliveryKind: ClusterRemoteExecutionOffer['deliveryKind'];
executionDigest: string;
candidate: ClusterRemoteExecutionOffer['candidate'];
worker: ClusterRemoteExecutionOffer['worker'];
lease: Readonly<{
version: number;
leaseGeneration: number;
acquiredAtMs: number;
renewedAtMs: number;
expiresAtMs: number;
updatedAtMs: number;
}>;
executionRevision: ClusterRemoteExecutionOffer['executionRevision'];
placementScore: number;
}>;
stats: RemoteExecutionOfferDeliveryStats;
truncated: boolean;
}>
| Readonly<{
schema: typeof REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA;
status: 'idle';
reason: RemoteExecutionOfferIdleReason;
stats: RemoteExecutionOfferDeliveryStats;
truncated: boolean;
}>;
export class InvalidRemoteExecutionOfferDeliveryError extends TypeError {
readonly code = 'REMOTE_EXECUTION_OFFER_DELIVERY_INVALID';
constructor(message: string) {
super(`Remote execution offer delivery is invalid: ${message}`);
this.name = 'InvalidRemoteExecutionOfferDeliveryError';
}
}
function invalid(message: string): never {
throw new InvalidRemoteExecutionOfferDeliveryError(message);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid(`${label} is not an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const sorted = [...expected].sort();
if (
actual.length !== sorted.length ||
actual.some((key, index) => key !== sorted[index])
) {
invalid(`${label} shape is invalid`);
}
}
function safeInteger(value: unknown, label: string, minimum = 0): number {
if (!Number.isSafeInteger(value) || (value as number) < minimum) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function boolean(value: unknown, label: string): boolean {
if (typeof value !== 'boolean') return invalid(`${label} is invalid`);
return value;
}
function normalizeOffer(
value: ClusterRemoteExecutionOffer,
): ClusterRemoteExecutionOffer {
try {
return createClusterRemoteExecutionOffer(value);
} catch (error) {
if (error instanceof InvalidRemoteExecutionOfferDeliveryError) throw error;
return invalid('offered payload is invalid');
}
}
function normalizeStats(value: unknown): RemoteExecutionOfferDeliveryStats {
const candidate = object(value, 'stats');
const keys = [
'pages',
'candidates',
'plansUnavailable',
'placementMismatches',
'claimAttempts',
'claimRaces',
] as const;
exactKeys(candidate, keys, 'stats');
const normalized = Object.freeze({
pages: safeInteger(candidate.pages, 'stats.pages'),
candidates: safeInteger(candidate.candidates, 'stats.candidates'),
plansUnavailable: safeInteger(
candidate.plansUnavailable,
'stats.plansUnavailable',
),
placementMismatches: safeInteger(
candidate.placementMismatches,
'stats.placementMismatches',
),
claimAttempts: safeInteger(
candidate.claimAttempts,
'stats.claimAttempts',
),
claimRaces: safeInteger(candidate.claimRaces, 'stats.claimRaces'),
});
if (
normalized.pages > 16 ||
normalized.candidates > 1024 ||
normalized.plansUnavailable > normalized.candidates ||
normalized.placementMismatches > normalized.candidates ||
normalized.claimAttempts > 64 ||
normalized.claimRaces > normalized.claimAttempts
) {
invalid('stats exceed the reviewed budget');
}
return normalized;
}
export function normalizeRemoteExecutionOfferClaimAuthority(
value: RemoteExecutionOfferClaimAuthority,
): RemoteExecutionOfferClaimAuthority {
const candidate = object(value, 'claim authority');
exactKeys(candidate, [
'workerId',
'workerSessionId',
'workerGeneration',
'offerId',
'leaseToken',
], 'claim authority');
assertWorkerId(value.workerId);
assertWorkerSessionId(value.workerSessionId);
safeInteger(value.workerGeneration, 'workerGeneration', 1);
assertRunDispatchId('offerId', value.offerId);
assertRunDispatchLeaseToken(value.leaseToken);
return Object.freeze({ ...value });
}
export function createRemoteExecutionOfferPullBody(
result: RemoteExecutionOfferPullResult,
): RemoteExecutionOfferPullBody {
const stats = normalizeStats(result.stats);
if (result.status === 'idle') {
if (!IDLE_REASONS.includes(result.reason)) invalid('idle reason is invalid');
return Object.freeze({
schema: REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA,
status: 'idle' as const,
reason: result.reason,
stats,
truncated: boolean(result.truncated, 'truncated'),
});
}
const offer = normalizeOffer(result.offer);
return Object.freeze({
schema: REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA,
status: 'offered' as const,
offer: Object.freeze({
offerId: offer.offerId,
deliveryKind: offer.deliveryKind,
executionDigest: offer.executionDigest,
candidate: offer.candidate,
worker: offer.worker,
lease: Object.freeze({
version: offer.lease.version,
leaseGeneration: offer.lease.leaseGeneration,
acquiredAtMs: offer.lease.acquiredAtMs,
renewedAtMs: offer.lease.renewedAtMs,
expiresAtMs: offer.lease.expiresAtMs,
updatedAtMs: offer.lease.updatedAtMs,
}),
executionRevision: offer.executionRevision,
placementScore: offer.placementScore,
}),
stats,
truncated: boolean(result.truncated, 'truncated'),
});
}
export function parseRemoteExecutionOfferPullResponse(
serialized: Uint8Array | string,
authorityValue: RemoteExecutionOfferClaimAuthority,
): RemoteExecutionOfferPullResult {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_EXECUTION_OFFER_RESPONSE_BYTES
) {
invalid('response byte size is outside the allowed range');
}
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('response is not valid JSON');
}
const authority = normalizeRemoteExecutionOfferClaimAuthority(authorityValue);
const response = object(parsed, 'response');
if (response.status === 'idle') {
exactKeys(response, [
'schema', 'status', 'reason', 'stats', 'truncated',
], 'idle response');
if (
response.schema !== REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA ||
typeof response.reason !== 'string' ||
!IDLE_REASONS.includes(response.reason as RemoteExecutionOfferIdleReason)
) {
invalid('idle response fence is invalid');
}
return Object.freeze({
status: 'idle' as const,
reason: response.reason as RemoteExecutionOfferIdleReason,
stats: normalizeStats(response.stats),
truncated: boolean(response.truncated, 'truncated'),
});
}
exactKeys(response, [
'schema', 'status', 'offer', 'stats', 'truncated',
], 'offered response');
if (
response.schema !== REMOTE_EXECUTION_OFFER_DELIVERY_SCHEMA ||
response.status !== 'offered'
) {
invalid('response schema or status is invalid');
}
const wire = object(response.offer, 'offer');
exactKeys(wire, [
'offerId', 'deliveryKind', 'executionDigest', 'candidate', 'worker',
'lease', 'executionRevision', 'placementScore',
], 'offer');
if (wire.offerId !== authority.offerId) invalid('offerId does not match claim');
const worker = object(wire.worker, 'offer.worker');
exactKeys(worker, ['workerId', 'sessionId', 'generation'], 'offer.worker');
if (
worker.workerId !== authority.workerId ||
worker.sessionId !== authority.workerSessionId ||
worker.generation !== authority.workerGeneration
) {
invalid('Worker target does not match claim');
}
let candidate: ClusterRemoteExecutionOffer['candidate'];
try {
candidate = normalizeClusterDispatchCandidate(
wire.candidate as ClusterRemoteExecutionOffer['candidate'],
);
} catch {
return invalid('offer candidate is invalid');
}
const lease = object(wire.lease, 'offer.lease');
exactKeys(lease, [
'version', 'leaseGeneration', 'acquiredAtMs', 'renewedAtMs',
'expiresAtMs', 'updatedAtMs',
], 'offer.lease');
const offer = normalizeOffer({
offerId: authority.offerId,
deliveryKind: wire.deliveryKind as ClusterRemoteExecutionOffer['deliveryKind'],
executionDigest: wire.executionDigest as string,
candidate,
worker: {
workerId: authority.workerId,
sessionId: authority.workerSessionId,
generation: authority.workerGeneration,
},
lease: {
attemptId: candidate.attemptId,
runId: candidate.runId,
status: 'leased',
version: safeInteger(lease.version, 'offer.lease.version'),
leaseGeneration: safeInteger(
lease.leaseGeneration,
'offer.lease.leaseGeneration',
1,
),
workerId: authority.workerId,
workerSessionId: authority.workerSessionId,
workerGeneration: authority.workerGeneration,
leaseTokenDigest: digestRunDispatchLeaseToken(authority.leaseToken),
acquiredAtMs: safeInteger(
lease.acquiredAtMs,
'offer.lease.acquiredAtMs',
),
renewedAtMs: safeInteger(
lease.renewedAtMs,
'offer.lease.renewedAtMs',
),
expiresAtMs: safeInteger(
lease.expiresAtMs,
'offer.lease.expiresAtMs',
),
updatedAtMs: safeInteger(
lease.updatedAtMs,
'offer.lease.updatedAtMs',
),
},
leaseToken: authority.leaseToken,
executionRevision:
wire.executionRevision as ClusterRemoteExecutionOffer['executionRevision'],
placementScore: wire.placementScore as number,
});
return Object.freeze({
status: 'offered' as const,
offer,
stats: normalizeStats(response.stats),
truncated: boolean(response.truncated, 'truncated'),
});
}
@@ -0,0 +1,198 @@
import {
assertRunDispatchId,
assertRunDispatchLeaseFence,
} from '../run/runDispatchLease';
import type { RunAttemptStatus, RunStatus } from '../run/run';
export interface RemoteRunActivationFence {
readonly runId: string;
readonly attemptId: string;
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly offerId: string;
readonly leaseGeneration: number;
/** Bearer capability. Persistence implementations must store only its digest. */
readonly leaseToken: string;
readonly expectedLeaseVersion: number;
}
export interface AcknowledgeRemoteRunStartingCommand
extends RemoteRunActivationFence {
readonly eventId: string;
}
export interface AcknowledgeRemoteRunRunningCommand
extends RemoteRunActivationFence {
readonly attemptEventId: string;
readonly runEventId: string;
readonly executorHandle: string;
readonly logArtifactId?: string;
/** Sequence bound to the completion callback capability kept by the Worker. */
readonly callbackSequence: number;
/** Lowercase SHA-256 digest. The raw callback capability never crosses storage. */
readonly callbackTokenDigest: string;
}
export interface FailRemoteRunStartCommand extends RemoteRunActivationFence {
readonly attemptEventId: string;
readonly runEventId: string;
}
export type RemoteRunActivationStatus =
| 'applied'
| 'already_starting'
| 'already_running'
| 'already_terminal';
export interface RemoteRunActivationSnapshot {
readonly runId: string;
readonly attemptId: string;
readonly runStatus: RunStatus;
readonly attemptStatus: RunAttemptStatus;
readonly leaseVersion: number;
readonly leaseGeneration: number;
readonly callbackSequence: number;
/** Database-clock deadline durably bound when starting was acknowledged. */
readonly deadlineAtMs?: number;
readonly startedAtMs?: number;
readonly finishedAtMs?: number;
readonly executorHandle?: string;
readonly logArtifactId?: string;
readonly errorCode?: string;
}
export interface RemoteRunActivationResult {
readonly status: RemoteRunActivationStatus;
readonly snapshot: Readonly<RemoteRunActivationSnapshot>;
}
export interface RemoteRunActivationRepository {
acknowledgeStarting(
command: AcknowledgeRemoteRunStartingCommand,
): Promise<Readonly<RemoteRunActivationResult>>;
acknowledgeRunning(
command: AcknowledgeRemoteRunRunningCommand,
): Promise<Readonly<RemoteRunActivationResult>>;
failStart(
command: FailRemoteRunStartCommand,
): Promise<Readonly<RemoteRunActivationResult>>;
}
export type RemoteRunActivationFenceReason =
| 'missing'
| 'run_mismatch'
| 'execution_owner_mismatch'
| 'executor_mismatch'
| 'attempt_state_mismatch'
| 'run_state_mismatch'
| 'worker_mismatch'
| 'worker_session_mismatch'
| 'worker_generation_mismatch'
| 'lease_generation_mismatch'
| 'lease_token_mismatch'
| 'offer_mismatch'
| 'version_mismatch'
| 'lease_expired'
| 'worker_unavailable'
| 'replay_mismatch';
export class RemoteRunActivationFenceRejectedError extends Error {
readonly code = 'REMOTE_RUN_ACTIVATION_FENCED';
constructor(
readonly attemptId: string,
readonly reason: RemoteRunActivationFenceReason,
) {
super(`Remote Run activation for Attempt ${attemptId} was fenced: ${reason}`);
this.name = 'RemoteRunActivationFenceRejectedError';
}
}
export class RemoteRunActivationUnavailableError extends Error {
readonly code = 'REMOTE_RUN_ACTIVATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Remote Run activation storage is unavailable', options);
this.name = 'RemoteRunActivationUnavailableError';
}
}
function boundedId(name: string, value: string, maximum: number): void {
assertRunDispatchId(name, value);
if (value.length > maximum) {
throw new TypeError(`Remote Run activation ${name} is invalid`);
}
}
export function assertRemoteRunActivationFence(
value: RemoteRunActivationFence,
): void {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Remote Run activation fence is invalid');
}
boundedId('runId', value.runId, 36);
boundedId('attemptId', value.attemptId, 36);
boundedId('offerId', value.offerId, 128);
assertRunDispatchLeaseFence({
workerId: value.workerId,
workerSessionId: value.workerSessionId,
workerGeneration: value.workerGeneration,
leaseGeneration: value.leaseGeneration,
leaseToken: value.leaseToken,
expectedVersion: value.expectedLeaseVersion,
});
for (const number of [
value.workerGeneration,
value.leaseGeneration,
value.expectedLeaseVersion,
]) {
if (number > 2_147_483_647) {
throw new RangeError('Remote Run activation fence version is invalid');
}
}
}
export function assertAcknowledgeRemoteRunStartingCommand(
command: AcknowledgeRemoteRunStartingCommand,
): void {
assertRemoteRunActivationFence(command);
boundedId('eventId', command.eventId, 36);
}
export function assertAcknowledgeRemoteRunRunningCommand(
command: AcknowledgeRemoteRunRunningCommand,
): void {
assertRemoteRunActivationFence(command);
boundedId('attemptEventId', command.attemptEventId, 36);
boundedId('runEventId', command.runEventId, 36);
if (
typeof command.executorHandle !== 'string' ||
command.executorHandle.length < 1 ||
command.executorHandle.length > 512 ||
/[\u0000-\u001f\u007f]/.test(command.executorHandle)
) {
throw new TypeError('Remote Run activation executorHandle is invalid');
}
if (command.logArtifactId !== undefined) {
boundedId('logArtifactId', command.logArtifactId, 36);
}
if (
!Number.isSafeInteger(command.callbackSequence) ||
command.callbackSequence < 1 ||
command.callbackSequence > 2_147_483_647
) {
throw new RangeError('Remote Run activation callbackSequence is invalid');
}
if (!/^[0-9a-f]{64}$/.test(command.callbackTokenDigest)) {
throw new TypeError('Remote Run activation callbackTokenDigest is invalid');
}
}
export function assertFailRemoteRunStartCommand(
command: FailRemoteRunStartCommand,
): void {
assertRemoteRunActivationFence(command);
boundedId('attemptEventId', command.attemptEventId, 36);
boundedId('runEventId', command.runEventId, 36);
}
@@ -0,0 +1,258 @@
import { RUN_ATTEMPT_STATUSES, RUN_STATUSES } from '../run/run';
import type {
RemoteRunActivationResult,
RemoteRunActivationSnapshot,
RemoteRunActivationStatus,
} from './remoteRunActivation';
import { assertRunDispatchId } from '../run/runDispatchLease';
export const REMOTE_RUN_ACTIVATION_DELIVERY_SCHEMA =
'qinglong/remote-run-activation@v1';
export const MAX_REMOTE_RUN_ACTIVATION_RESPONSE_BYTES = 16 * 1024;
export type RemoteRunActivationResponseBody = Readonly<{
schema: typeof REMOTE_RUN_ACTIVATION_DELIVERY_SCHEMA;
status: RemoteRunActivationStatus;
snapshot: Readonly<RemoteRunActivationSnapshot>;
}>;
export class InvalidRemoteRunActivationDeliveryError extends TypeError {
readonly code = 'REMOTE_RUN_ACTIVATION_DELIVERY_INVALID';
constructor(message: string) {
super(`Remote Run activation delivery is invalid: ${message}`);
this.name = 'InvalidRemoteRunActivationDeliveryError';
}
}
const ACTIVATION_STATUSES = new Set<RemoteRunActivationStatus>([
'applied',
'already_starting',
'already_running',
'already_terminal',
]);
const REQUIRED_SNAPSHOT_KEYS = [
'runId',
'attemptId',
'runStatus',
'attemptStatus',
'leaseVersion',
'leaseGeneration',
'callbackSequence',
] as const;
const OPTIONAL_SNAPSHOT_KEYS = [
'deadlineAtMs',
'startedAtMs',
'finishedAtMs',
'executorHandle',
'logArtifactId',
'errorCode',
] as const;
const SNAPSHOT_KEYS = new Set<string>([
...REQUIRED_SNAPSHOT_KEYS,
...OPTIONAL_SNAPSHOT_KEYS,
]);
function invalid(message: string): never {
throw new InvalidRemoteRunActivationDeliveryError(message);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid(`${label} is not an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const sorted = [...expected].sort();
if (
actual.length !== sorted.length ||
actual.some((key, index) => key !== sorted[index])
) {
invalid(`${label} shape is invalid`);
}
}
function boundedId(label: string, value: unknown, maximum: number): string {
if (typeof value !== 'string') return invalid(`${label} is invalid`);
try {
assertRunDispatchId(label, value);
} catch {
return invalid(`${label} is invalid`);
}
if (value.length > maximum) return invalid(`${label} is invalid`);
return value;
}
function boundedInteger(
label: string,
value: unknown,
maximum = 2_147_483_647,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function boundedText(label: string, value: unknown, maximum: number): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > maximum ||
/[\u0000-\u001f\u007f]/.test(value)
) {
return invalid(`${label} is invalid`);
}
return value;
}
function normalizeSnapshot(value: unknown): Readonly<RemoteRunActivationSnapshot> {
const snapshot = object(value, 'snapshot');
const keys = Object.keys(snapshot);
if (
REQUIRED_SNAPSHOT_KEYS.some((key) => !Object.hasOwn(snapshot, key)) ||
keys.some((key) => !SNAPSHOT_KEYS.has(key))
) {
return invalid('snapshot shape is invalid');
}
if (
typeof snapshot.runStatus !== 'string' ||
!RUN_STATUSES.includes(snapshot.runStatus as never) ||
typeof snapshot.attemptStatus !== 'string' ||
!RUN_ATTEMPT_STATUSES.includes(snapshot.attemptStatus as never)
) {
return invalid('snapshot status is invalid');
}
const normalized: RemoteRunActivationSnapshot = {
runId: boundedId('runId', snapshot.runId, 36),
attemptId: boundedId('attemptId', snapshot.attemptId, 36),
runStatus: snapshot.runStatus as RemoteRunActivationSnapshot['runStatus'],
attemptStatus:
snapshot.attemptStatus as RemoteRunActivationSnapshot['attemptStatus'],
leaseVersion: boundedInteger('leaseVersion', snapshot.leaseVersion),
leaseGeneration: boundedInteger(
'leaseGeneration',
snapshot.leaseGeneration,
),
callbackSequence: boundedInteger(
'callbackSequence',
snapshot.callbackSequence,
),
...(snapshot.deadlineAtMs === undefined
? {}
: { deadlineAtMs: boundedInteger('deadlineAtMs', snapshot.deadlineAtMs, Number.MAX_SAFE_INTEGER) }),
...(snapshot.startedAtMs === undefined
? {}
: { startedAtMs: boundedInteger('startedAtMs', snapshot.startedAtMs, Number.MAX_SAFE_INTEGER) }),
...(snapshot.finishedAtMs === undefined
? {}
: { finishedAtMs: boundedInteger('finishedAtMs', snapshot.finishedAtMs, Number.MAX_SAFE_INTEGER) }),
...(snapshot.executorHandle === undefined
? {}
: { executorHandle: boundedText('executorHandle', snapshot.executorHandle, 512) }),
...(snapshot.logArtifactId === undefined
? {}
: { logArtifactId: boundedId('logArtifactId', snapshot.logArtifactId, 36) }),
...(snapshot.errorCode === undefined
? {}
: { errorCode: boundedText('errorCode', snapshot.errorCode, 128) }),
};
return Object.freeze(normalized);
}
function normalizeResult(value: unknown): Readonly<RemoteRunActivationResult> {
const result = object(value, 'result');
exactKeys(result, ['status', 'snapshot'], 'result');
if (
typeof result.status !== 'string' ||
!ACTIVATION_STATUSES.has(result.status as RemoteRunActivationStatus)
) {
return invalid('status is invalid');
}
const normalized = Object.freeze({
status: result.status as RemoteRunActivationStatus,
snapshot: normalizeSnapshot(result.snapshot),
});
const snapshot = normalized.snapshot;
const starting = snapshot.runStatus === 'dispatching' &&
snapshot.attemptStatus === 'starting' &&
snapshot.executorHandle === undefined &&
snapshot.startedAtMs === undefined &&
snapshot.finishedAtMs === undefined &&
snapshot.errorCode === undefined;
const running = snapshot.runStatus === 'running' &&
snapshot.attemptStatus === 'running' &&
snapshot.executorHandle !== undefined &&
snapshot.startedAtMs !== undefined &&
snapshot.finishedAtMs === undefined &&
snapshot.errorCode === undefined;
const terminalStatus = snapshot.runStatus === snapshot.attemptStatus &&
['failed', 'cancelled', 'timed_out'].includes(snapshot.runStatus);
const terminal = terminalStatus &&
snapshot.executorHandle === undefined &&
snapshot.startedAtMs === undefined &&
snapshot.finishedAtMs !== undefined &&
snapshot.errorCode !== undefined;
if (!starting && !running && !terminal) {
return invalid('snapshot state is invalid');
}
if (
(normalized.status === 'already_starting' && !starting) ||
(normalized.status === 'already_running' && !running) ||
(normalized.status === 'already_terminal' && !terminal)
) {
return invalid('status and snapshot state disagree');
}
return normalized;
}
export function createRemoteRunActivationResponseBody(
result: Readonly<RemoteRunActivationResult>,
): RemoteRunActivationResponseBody {
const normalized = normalizeResult(result);
return Object.freeze({
schema: REMOTE_RUN_ACTIVATION_DELIVERY_SCHEMA,
status: normalized.status,
snapshot: normalized.snapshot,
});
}
export function parseRemoteRunActivationResponse(
serialized: Uint8Array | string,
): Readonly<RemoteRunActivationResult> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_RUN_ACTIVATION_RESPONSE_BYTES
) {
return invalid('response byte size is outside the allowed range');
}
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('response is not valid JSON');
}
const response = object(parsed, 'response');
exactKeys(response, ['schema', 'status', 'snapshot'], 'response');
if (response.schema !== REMOTE_RUN_ACTIVATION_DELIVERY_SCHEMA) {
return invalid('response schema is invalid');
}
return normalizeResult({
status: response.status,
snapshot: response.snapshot,
});
}
@@ -0,0 +1,393 @@
import { digestRunDispatchLeaseToken, assertRunDispatchId } from '../run/runDispatchLease';
import { parseSecretRef } from '../secret/secretReference';
import { assertWorkerId, assertWorkerSessionId } from '../worker/workerSession';
export const REMOTE_SECRET_DELIVERY_SCHEMA =
'qinglong/remote-secret-delivery@v1';
export const MAX_REMOTE_SECRET_DELIVERY_REFS = 64;
export const MAX_REMOTE_SECRET_DELIVERY_REQUEST_BYTES = 64 * 1024;
export const MAX_REMOTE_SECRET_DELIVERY_RESPONSE_BYTES = 128 * 1024;
export const MAX_REMOTE_SECRET_VALUE_BYTES = 16 * 1024;
export const MAX_REMOTE_SECRET_DELIVERY_TOTAL_VALUE_BYTES = 64 * 1024;
export interface RemoteWorkerSecretDeliveryCommand {
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly runId: string;
readonly attemptId: string;
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly executionDigest: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseToken: string;
readonly expectedLeaseVersion: number;
readonly secretRefs: readonly string[];
}
export type RemoteWorkerSecretDeliveryRequestBody = Readonly<
Omit<RemoteWorkerSecretDeliveryCommand, 'workerId' | 'workerSessionId'> & {
readonly schema: typeof REMOTE_SECRET_DELIVERY_SCHEMA;
}
>;
export interface RemoteWorkerSecretDeliveryAuthority {
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly runId: string;
readonly attemptId: string;
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly executionDigest: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseVersion: number;
readonly secretRefs: readonly string[];
}
export interface RemoteWorkerSecretValue {
readonly secretRef: string;
readonly value: string;
}
export interface RemoteWorkerSecretResolution {
readonly values: readonly RemoteWorkerSecretValue[];
readonly dispose?: () => Promise<void> | void;
}
export interface RemoteWorkerSecretDeliveryAuthorityRepository {
authorize(
command: RemoteWorkerSecretDeliveryCommand,
): Promise<Readonly<RemoteWorkerSecretDeliveryAuthority>>;
}
export interface RemoteWorkerSecretValueProvider {
resolve(
authority: Readonly<RemoteWorkerSecretDeliveryAuthority>,
): Promise<Readonly<RemoteWorkerSecretResolution> | undefined>;
}
export interface RemoteWorkerSecretDeliveryResult {
readonly runId: string;
readonly attemptId: string;
readonly offerId: string;
readonly executionDigest: string;
readonly values: readonly RemoteWorkerSecretValue[];
readonly dispose?: () => Promise<void> | void;
}
export type RemoteWorkerSecretDeliveryResponseBody = Readonly<
Omit<RemoteWorkerSecretDeliveryResult, 'dispose'> & {
readonly schema: typeof REMOTE_SECRET_DELIVERY_SCHEMA;
}
>;
export class InvalidRemoteWorkerSecretDeliveryError extends TypeError {
readonly code = 'REMOTE_SECRET_DELIVERY_INVALID';
constructor(message: string) {
super(`Remote Worker Secret delivery is invalid: ${message}`);
this.name = 'InvalidRemoteWorkerSecretDeliveryError';
}
}
export class RemoteWorkerSecretDeliveryFenceRejectedError extends Error {
readonly code = 'REMOTE_SECRET_DELIVERY_FENCED';
constructor(readonly reason: 'authority_mismatch' | 'secret_scope_mismatch') {
super(`Remote Worker Secret delivery is fenced: ${reason}`);
this.name = 'RemoteWorkerSecretDeliveryFenceRejectedError';
}
}
export class RemoteWorkerSecretDeliveryUnavailableError extends Error {
readonly code = 'REMOTE_SECRET_DELIVERY_UNAVAILABLE';
constructor() {
super('Remote Worker Secret delivery is unavailable');
this.name = 'RemoteWorkerSecretDeliveryUnavailableError';
}
}
function invalid(message: string): never {
throw new InvalidRemoteWorkerSecretDeliveryError(message);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid(`${label} is not an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const sorted = [...expected].sort();
if (
actual.length !== sorted.length ||
actual.some((key, index) => key !== sorted[index])
) invalid(`${label} shape is invalid`);
}
function identifier(label: string, value: unknown, maximum = 128): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > maximum ||
/[\u0000-\u001f\u007f]/.test(value)
) return invalid(`${label} is invalid`);
return value;
}
function positiveInteger(label: string, value: unknown, minimum = 1): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > 2_147_483_647
) return invalid(`${label} is invalid`);
return value as number;
}
function normalizeSecretRefs(
value: unknown,
projectId: string,
): readonly string[] {
if (
!Array.isArray(value) ||
value.length < 1 ||
value.length > MAX_REMOTE_SECRET_DELIVERY_REFS
) return invalid('secretRefs are invalid');
const seen = new Set<string>();
const refs = value.map((entry) => {
if (typeof entry !== 'string' || seen.has(entry)) {
return invalid('secretRefs are invalid');
}
try {
if (parseSecretRef(entry).projectId !== projectId) {
return invalid('secretRef project is invalid');
}
} catch (error) {
if (error instanceof InvalidRemoteWorkerSecretDeliveryError) throw error;
return invalid('secretRef is invalid');
}
seen.add(entry);
return entry;
});
return Object.freeze(refs);
}
export function normalizeRemoteWorkerSecretDeliveryCommand(
value: RemoteWorkerSecretDeliveryCommand,
): Readonly<RemoteWorkerSecretDeliveryCommand> {
const command = object(value, 'command');
exactKeys(command, [
'attemptId', 'executionDigest', 'expectedLeaseVersion', 'leaseGeneration',
'leaseToken', 'offerId', 'projectId', 'runId', 'secretRefs', 'taskId',
'taskRevision', 'workerGeneration', 'workerId', 'workerSessionId',
], 'command');
try {
assertWorkerId(command.workerId as string);
assertWorkerSessionId(command.workerSessionId as string);
assertRunDispatchId('runId', command.runId as string);
assertRunDispatchId('attemptId', command.attemptId as string);
assertRunDispatchId('offerId', command.offerId as string);
} catch {
return invalid('authority identifier is invalid');
}
const projectId = identifier('projectId', command.projectId);
const normalized = Object.freeze({
workerId: command.workerId as string,
workerSessionId: command.workerSessionId as string,
workerGeneration: positiveInteger('workerGeneration', command.workerGeneration),
runId: command.runId as string,
attemptId: command.attemptId as string,
projectId,
taskId: identifier('taskId', command.taskId),
taskRevision: identifier('taskRevision', command.taskRevision),
executionDigest: identifier('executionDigest', command.executionDigest, 64),
offerId: command.offerId as string,
leaseGeneration: positiveInteger('leaseGeneration', command.leaseGeneration),
leaseToken: identifier('leaseToken', command.leaseToken, 128),
expectedLeaseVersion: positiveInteger(
'expectedLeaseVersion', command.expectedLeaseVersion, 0,
),
secretRefs: normalizeSecretRefs(command.secretRefs, projectId),
});
if (!/^[0-9a-f]{64}$/.test(normalized.executionDigest)) {
return invalid('executionDigest is invalid');
}
try {
digestRunDispatchLeaseToken(normalized.leaseToken);
} catch {
return invalid('leaseToken is invalid');
}
return normalized;
}
export function normalizeRemoteWorkerSecretDeliveryAuthority(
value: RemoteWorkerSecretDeliveryAuthority,
): Readonly<RemoteWorkerSecretDeliveryAuthority> {
const authority = object(value, 'authority');
exactKeys(authority, [
'attemptId', 'executionDigest', 'leaseGeneration', 'leaseVersion',
'offerId', 'projectId', 'runId', 'secretRefs', 'taskId', 'taskRevision',
'workerGeneration', 'workerId', 'workerSessionId',
], 'authority');
try {
assertWorkerId(authority.workerId as string);
assertWorkerSessionId(authority.workerSessionId as string);
assertRunDispatchId('runId', authority.runId as string);
assertRunDispatchId('attemptId', authority.attemptId as string);
assertRunDispatchId('offerId', authority.offerId as string);
} catch {
return invalid('authority identifier is invalid');
}
const projectId = identifier('projectId', authority.projectId);
const normalized = Object.freeze({
workerId: authority.workerId as string,
workerSessionId: authority.workerSessionId as string,
workerGeneration: positiveInteger(
'workerGeneration', authority.workerGeneration,
),
runId: authority.runId as string,
attemptId: authority.attemptId as string,
projectId,
taskId: identifier('taskId', authority.taskId),
taskRevision: identifier('taskRevision', authority.taskRevision),
executionDigest: identifier(
'executionDigest', authority.executionDigest, 64,
),
offerId: authority.offerId as string,
leaseGeneration: positiveInteger(
'leaseGeneration', authority.leaseGeneration,
),
leaseVersion: positiveInteger('leaseVersion', authority.leaseVersion, 0),
secretRefs: normalizeSecretRefs(authority.secretRefs, projectId),
});
if (!/^[0-9a-f]{64}$/.test(normalized.executionDigest)) {
return invalid('executionDigest is invalid');
}
return normalized;
}
export function createRemoteWorkerSecretDeliveryRequestBody(
command: RemoteWorkerSecretDeliveryCommand,
): RemoteWorkerSecretDeliveryRequestBody {
const normalized = normalizeRemoteWorkerSecretDeliveryCommand(command);
const { workerId: _workerId, workerSessionId: _sessionId, ...request } = normalized;
return Object.freeze({ schema: REMOTE_SECRET_DELIVERY_SCHEMA, ...request });
}
function normalizeValues(
value: unknown,
expectedRefs: readonly string[],
): readonly RemoteWorkerSecretValue[] {
if (!Array.isArray(value) || value.length !== expectedRefs.length) {
return invalid('Secret values are invalid');
}
let totalValueBytes = 0;
return Object.freeze(value.map((entry, index) => {
const item = object(entry, `values[${index}]`);
exactKeys(item, ['secretRef', 'value'], `values[${index}]`);
if (
item.secretRef !== expectedRefs[index] ||
typeof item.value !== 'string' ||
item.value.includes('\0') ||
Buffer.byteLength(item.value, 'utf8') > MAX_REMOTE_SECRET_VALUE_BYTES
) return invalid(`values[${index}] is invalid`);
totalValueBytes += Buffer.byteLength(item.value, 'utf8');
if (totalValueBytes > MAX_REMOTE_SECRET_DELIVERY_TOTAL_VALUE_BYTES) {
return invalid('Secret value byte budget exceeded');
}
return Object.freeze({
secretRef: item.secretRef as string,
value: item.value,
});
}));
}
export function createRemoteWorkerSecretDeliveryResponseBody(
result: Readonly<RemoteWorkerSecretDeliveryResult>,
expectedRefs: readonly string[],
): RemoteWorkerSecretDeliveryResponseBody {
const value = object(result, 'result');
const allowed = ['attemptId', 'dispose', 'executionDigest', 'offerId', 'runId', 'values'];
if (Object.keys(value).some((key) => !allowed.includes(key))) {
return invalid('result shape is invalid');
}
const runId = identifier('runId', value.runId, 36);
const attemptId = identifier('attemptId', value.attemptId, 36);
const offerId = identifier('offerId', value.offerId, 128);
const executionDigest = identifier('executionDigest', value.executionDigest, 64);
if (!/^[0-9a-f]{64}$/.test(executionDigest)) invalid('executionDigest is invalid');
return Object.freeze({
schema: REMOTE_SECRET_DELIVERY_SCHEMA,
runId,
attemptId,
offerId,
executionDigest,
values: normalizeValues(value.values, expectedRefs),
});
}
export function parseRemoteWorkerSecretDeliveryResponse(
serialized: Uint8Array | string,
expected: Readonly<{
runId: string;
attemptId: string;
offerId: string;
executionDigest: string;
secretRefs: readonly string[];
}>,
): Readonly<RemoteWorkerSecretDeliveryResult> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_SECRET_DELIVERY_RESPONSE_BYTES
) return invalid('response byte size is outside the allowed range');
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('response is not valid JSON');
} finally {
bytes.fill(0);
}
const response = object(parsed, 'response');
exactKeys(response, [
'attemptId', 'executionDigest', 'offerId', 'runId', 'schema', 'values',
], 'response');
if (response.schema !== REMOTE_SECRET_DELIVERY_SCHEMA) {
return invalid('response schema is invalid');
}
const result = createRemoteWorkerSecretDeliveryResponseBody({
runId: response.runId as string,
attemptId: response.attemptId as string,
offerId: response.offerId as string,
executionDigest: response.executionDigest as string,
values: response.values as readonly RemoteWorkerSecretValue[],
}, expected.secretRefs);
if (
result.runId !== expected.runId ||
result.attemptId !== expected.attemptId ||
result.offerId !== expected.offerId ||
result.executionDigest !== expected.executionDigest
) return invalid('response authority does not match request');
return Object.freeze({
runId: result.runId,
attemptId: result.attemptId,
offerId: result.offerId,
executionDigest: result.executionDigest,
values: result.values,
});
}
@@ -0,0 +1,657 @@
import { assertRunDispatchId, digestRunDispatchLeaseToken } from '../run/runDispatchLease';
import { assertWorkerId, assertWorkerSessionId } from '../worker/workerSession';
export const REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA =
'qinglong/remote-worker-artifact-upload@v1';
export const REMOTE_WORKER_COMPLETION_SCHEMA =
'qinglong/remote-worker-completion@v1';
export const REMOTE_WORKER_ARTIFACT_CONTENT_TYPE =
'application/vnd.qinglong.worker-artifact';
export const MAX_REMOTE_WORKER_ARTIFACT_BYTES = 64 * 1024 * 1024;
export const MAX_REMOTE_WORKER_ARTIFACT_HEADER_BYTES = 4 * 1024;
export const MAX_REMOTE_WORKER_ARTIFACT_RESPONSE_BYTES = 4 * 1024;
export const MAX_REMOTE_WORKER_COMPLETION_REQUEST_BYTES = 16 * 1024;
export const MAX_REMOTE_WORKER_COMPLETION_RESPONSE_BYTES = 4 * 1024;
const SHA256 = /^[a-f0-9]{64}$/;
const LOG_ARTIFACT_ID = /^wlog-[a-f0-9]{30}$/;
const UPLOAD_STATUSES = new Set(['stored', 'already_stored']);
const COMPLETION_STATUSES = new Set([
'applied',
'already_completed',
'already_terminal',
]);
export interface RemoteWorkerExecutionFence {
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly projectId: string;
readonly runId: string;
readonly attemptId: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseToken: string;
readonly expectedLeaseVersion: number;
}
export interface RemoteWorkerArtifactUploadCommand
extends RemoteWorkerExecutionFence {
readonly logArtifactId: string;
readonly byteLength: number;
readonly truncated?: boolean;
}
export type RemoteWorkerArtifactUploadRequestHeader = Readonly<
Omit<
RemoteWorkerArtifactUploadCommand,
'workerId' | 'workerSessionId' | 'truncated'
> & {
readonly schema: typeof REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA;
readonly truncated: boolean | null;
}
>;
export interface RemoteWorkerArtifactReceipt {
readonly status: 'stored' | 'already_stored';
readonly projectId: string;
readonly runId: string;
readonly attemptId: string;
readonly logArtifactId: string;
readonly byteLength: number;
readonly sha256: string;
readonly truncated?: boolean;
}
export type RemoteWorkerArtifactUploadResponseBody = Readonly<
Omit<RemoteWorkerArtifactReceipt, 'truncated'> & {
readonly schema: typeof REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA;
readonly truncated: boolean | null;
}
>;
export interface RemoteWorkerCompletionCommand
extends RemoteWorkerExecutionFence {
readonly callbackSequence: number;
readonly callbackTokenDigest: string;
readonly result: Readonly<{
readonly outcome: 'succeeded' | 'failed';
readonly startedAtMs: number;
readonly finishedAtMs: number;
readonly exitCode: number;
}>;
readonly artifact: Readonly<{
readonly logArtifactId: string;
readonly byteLength: number;
readonly sha256: string;
readonly truncated?: boolean;
}>;
}
export type RemoteWorkerCompletionRequestBody = Readonly<
Omit<
RemoteWorkerCompletionCommand,
'workerId' | 'workerSessionId' | 'artifact'
> & {
readonly schema: typeof REMOTE_WORKER_COMPLETION_SCHEMA;
readonly artifact: Readonly<
Omit<RemoteWorkerCompletionCommand['artifact'], 'truncated'> & {
readonly truncated: boolean | null;
}
>;
}
>;
export interface RemoteWorkerCompletionResult {
readonly status: 'applied' | 'already_completed' | 'already_terminal';
readonly runId: string;
readonly attemptId: string;
readonly callbackSequence: number;
}
export type RemoteWorkerCompletionResponseBody = Readonly<
RemoteWorkerCompletionResult & {
readonly schema: typeof REMOTE_WORKER_COMPLETION_SCHEMA;
}
>;
export interface RemoteWorkerArtifactUploadAuthorityRepository {
authorizeArtifactUpload(
command: RemoteWorkerArtifactUploadCommand,
): Promise<void>;
}
export interface RemoteWorkerCompletionRepository {
complete(
command: RemoteWorkerCompletionCommand & Readonly<{
attemptEventId: string;
runEventId: string;
}>,
): Promise<Readonly<RemoteWorkerCompletionResult>>;
}
export class InvalidRemoteWorkerCompletionError extends TypeError {
readonly code = 'REMOTE_WORKER_COMPLETION_INVALID';
constructor(message: string) {
super(`Remote Worker completion is invalid: ${message}`);
this.name = 'InvalidRemoteWorkerCompletionError';
}
}
export class RemoteWorkerCompletionFenceRejectedError extends Error {
readonly code = 'REMOTE_WORKER_COMPLETION_FENCED';
constructor(
readonly attemptId: string,
readonly reason:
| 'missing'
| 'worker_unavailable'
| 'authority_mismatch'
| 'lease_expired'
| 'state_mismatch'
| 'replay_mismatch',
) {
super(`Remote Worker completion is fenced: ${reason}`);
this.name = 'RemoteWorkerCompletionFenceRejectedError';
}
}
export class RemoteWorkerCompletionUnavailableError extends Error {
readonly code = 'REMOTE_WORKER_COMPLETION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Remote Worker completion is unavailable', options);
this.name = 'RemoteWorkerCompletionUnavailableError';
}
}
function invalid(message: string): never {
throw new InvalidRemoteWorkerCompletionError(message);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid(`${label} is not an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const sorted = [...expected].sort();
if (
actual.length !== sorted.length ||
actual.some((key, index) => key !== sorted[index])
) invalid(`${label} shape is invalid`);
}
function identifier(label: string, value: unknown, maximum = 128): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > maximum ||
/[\u0000-\u001f\u007f]/.test(value)
) return invalid(`${label} is invalid`);
return value;
}
function integer(
label: string,
value: unknown,
minimum = 0,
maximum = Number.MAX_SAFE_INTEGER,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) return invalid(`${label} is invalid`);
return value as number;
}
function nullableBoolean(
label: string,
value: unknown,
): boolean | undefined {
if (value === null) return undefined;
if (typeof value !== 'boolean') return invalid(`${label} is invalid`);
return value;
}
function fence(
value: Record<string, unknown>,
): Readonly<RemoteWorkerExecutionFence> {
try {
assertWorkerId(value.workerId as string);
assertWorkerSessionId(value.workerSessionId as string);
assertRunDispatchId('runId', value.runId as string);
assertRunDispatchId('attemptId', value.attemptId as string);
assertRunDispatchId('offerId', value.offerId as string);
digestRunDispatchLeaseToken(value.leaseToken as string);
} catch {
return invalid('execution authority is invalid');
}
return Object.freeze({
workerId: value.workerId as string,
workerSessionId: value.workerSessionId as string,
workerGeneration: integer(
'workerGeneration', value.workerGeneration, 1, 2_147_483_647,
),
projectId: identifier('projectId', value.projectId),
runId: value.runId as string,
attemptId: value.attemptId as string,
offerId: value.offerId as string,
leaseGeneration: integer(
'leaseGeneration', value.leaseGeneration, 1, 2_147_483_647,
),
leaseToken: value.leaseToken as string,
expectedLeaseVersion: integer(
'expectedLeaseVersion', value.expectedLeaseVersion, 0, 2_147_483_647,
),
});
}
const FENCE_KEYS = [
'workerId', 'workerSessionId', 'workerGeneration', 'projectId', 'runId',
'attemptId', 'offerId', 'leaseGeneration', 'leaseToken',
'expectedLeaseVersion',
] as const;
export function normalizeRemoteWorkerArtifactUploadCommand(
value: RemoteWorkerArtifactUploadCommand,
): Readonly<RemoteWorkerArtifactUploadCommand> {
const command = object(value, 'Artifact upload command');
const required = [...FENCE_KEYS, 'logArtifactId', 'byteLength'];
const keys = Object.keys(command);
if (
required.some((key) => !Object.hasOwn(command, key)) ||
keys.some((key) => ![...required, 'truncated'].includes(key))
) return invalid('Artifact upload command shape is invalid');
const authority = fence(command);
const logArtifactId = identifier('logArtifactId', command.logArtifactId, 36);
if (!LOG_ARTIFACT_ID.test(logArtifactId)) {
return invalid('logArtifactId is invalid');
}
if (
command.truncated !== undefined &&
typeof command.truncated !== 'boolean'
) return invalid('truncated is invalid');
return Object.freeze({
...authority,
logArtifactId,
byteLength: integer(
'byteLength', command.byteLength, 0, MAX_REMOTE_WORKER_ARTIFACT_BYTES,
),
...(command.truncated === undefined
? {}
: { truncated: command.truncated as boolean }),
});
}
export function createRemoteWorkerArtifactUploadRequestHeader(
command: RemoteWorkerArtifactUploadCommand,
): RemoteWorkerArtifactUploadRequestHeader {
const value = normalizeRemoteWorkerArtifactUploadCommand(command);
const { workerId: _workerId, workerSessionId: _sessionId, ...body } = value;
return Object.freeze({
schema: REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA,
...body,
truncated: value.truncated ?? null,
});
}
export function createRemoteWorkerArtifactUploadPreamble(
command: RemoteWorkerArtifactUploadCommand,
): Buffer {
const serialized = Buffer.from(JSON.stringify(
createRemoteWorkerArtifactUploadRequestHeader(command),
), 'utf8');
if (
serialized.byteLength < 2 ||
serialized.byteLength > MAX_REMOTE_WORKER_ARTIFACT_HEADER_BYTES
) {
serialized.fill(0);
return invalid('Artifact upload header exceeds its byte limit');
}
const result = Buffer.allocUnsafe(4 + serialized.byteLength);
result.writeUInt32BE(serialized.byteLength, 0);
serialized.copy(result, 4);
serialized.fill(0);
return result;
}
export function parseRemoteWorkerArtifactUploadHeader(
serialized: Uint8Array | string,
pathAuthority: Readonly<{ workerId: string; workerSessionId: string }>,
): Readonly<RemoteWorkerArtifactUploadCommand> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_WORKER_ARTIFACT_HEADER_BYTES
) return invalid('Artifact upload header byte size is invalid');
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('Artifact upload header is not valid JSON');
}
const header = object(parsed, 'Artifact upload header');
exactKeys(header, [
'schema', 'workerGeneration', 'projectId', 'runId', 'attemptId',
'offerId', 'leaseGeneration', 'leaseToken', 'expectedLeaseVersion',
'logArtifactId', 'byteLength', 'truncated',
], 'Artifact upload header');
if (header.schema !== REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA) {
return invalid('Artifact upload schema is invalid');
}
return normalizeRemoteWorkerArtifactUploadCommand({
workerId: pathAuthority.workerId,
workerSessionId: pathAuthority.workerSessionId,
workerGeneration: header.workerGeneration as number,
projectId: header.projectId as string,
runId: header.runId as string,
attemptId: header.attemptId as string,
offerId: header.offerId as string,
leaseGeneration: header.leaseGeneration as number,
leaseToken: header.leaseToken as string,
expectedLeaseVersion: header.expectedLeaseVersion as number,
logArtifactId: header.logArtifactId as string,
byteLength: header.byteLength as number,
...(nullableBoolean('truncated', header.truncated) === undefined
? {}
: { truncated: header.truncated as boolean }),
});
}
export function normalizeRemoteWorkerArtifactReceipt(
value: RemoteWorkerArtifactReceipt,
): Readonly<RemoteWorkerArtifactReceipt> {
const receipt = object(value, 'Artifact receipt');
const required = [
'status', 'projectId', 'runId', 'attemptId', 'logArtifactId',
'byteLength', 'sha256',
];
const keys = Object.keys(receipt);
if (
required.some((key) => !Object.hasOwn(receipt, key)) ||
keys.some((key) => ![...required, 'truncated'].includes(key)) ||
typeof receipt.status !== 'string' ||
!UPLOAD_STATUSES.has(receipt.status)
) return invalid('Artifact receipt shape is invalid');
try {
assertRunDispatchId('runId', receipt.runId as string);
assertRunDispatchId('attemptId', receipt.attemptId as string);
} catch {
return invalid('Artifact receipt authority is invalid');
}
const logArtifactId = identifier('logArtifactId', receipt.logArtifactId, 36);
if (!LOG_ARTIFACT_ID.test(logArtifactId)) {
return invalid('Artifact receipt identity is invalid');
}
const sha256 = identifier('sha256', receipt.sha256, 64);
if (!SHA256.test(sha256)) return invalid('Artifact receipt digest is invalid');
if (
receipt.truncated !== undefined &&
typeof receipt.truncated !== 'boolean'
) return invalid('Artifact receipt truncation is invalid');
return Object.freeze({
status: receipt.status as RemoteWorkerArtifactReceipt['status'],
projectId: identifier('projectId', receipt.projectId),
runId: receipt.runId as string,
attemptId: receipt.attemptId as string,
logArtifactId,
byteLength: integer(
'byteLength', receipt.byteLength, 0, MAX_REMOTE_WORKER_ARTIFACT_BYTES,
),
sha256,
...(receipt.truncated === undefined
? {}
: { truncated: receipt.truncated as boolean }),
});
}
export function createRemoteWorkerArtifactUploadResponseBody(
receipt: RemoteWorkerArtifactReceipt,
): RemoteWorkerArtifactUploadResponseBody {
const value = normalizeRemoteWorkerArtifactReceipt(receipt);
return Object.freeze({
schema: REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA,
...value,
truncated: value.truncated ?? null,
});
}
export function parseRemoteWorkerArtifactUploadResponse(
serialized: Uint8Array | string,
): Readonly<RemoteWorkerArtifactReceipt> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_WORKER_ARTIFACT_RESPONSE_BYTES
) return invalid('Artifact response byte size is invalid');
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('Artifact response is not valid JSON');
}
const response = object(parsed, 'Artifact response');
exactKeys(response, [
'schema', 'status', 'projectId', 'runId', 'attemptId', 'logArtifactId',
'byteLength', 'sha256', 'truncated',
], 'Artifact response');
if (response.schema !== REMOTE_WORKER_ARTIFACT_UPLOAD_SCHEMA) {
return invalid('Artifact response schema is invalid');
}
const truncated = nullableBoolean('truncated', response.truncated);
return normalizeRemoteWorkerArtifactReceipt({
status: response.status as RemoteWorkerArtifactReceipt['status'],
projectId: response.projectId as string,
runId: response.runId as string,
attemptId: response.attemptId as string,
logArtifactId: response.logArtifactId as string,
byteLength: response.byteLength as number,
sha256: response.sha256 as string,
...(truncated === undefined ? {} : { truncated }),
});
}
export function normalizeRemoteWorkerCompletionCommand(
value: RemoteWorkerCompletionCommand,
): Readonly<RemoteWorkerCompletionCommand> {
const command = object(value, 'completion command');
exactKeys(command, [
...FENCE_KEYS, 'callbackSequence', 'callbackTokenDigest', 'result',
'artifact',
], 'completion command');
const authority = fence(command);
const result = object(command.result, 'completion result');
exactKeys(result, [
'outcome', 'startedAtMs', 'finishedAtMs', 'exitCode',
], 'completion result');
if (
result.outcome !== 'succeeded' &&
result.outcome !== 'failed'
) return invalid('completion outcome is invalid');
const startedAtMs = integer('startedAtMs', result.startedAtMs);
const finishedAtMs = integer('finishedAtMs', result.finishedAtMs);
const exitCode = integer('exitCode', result.exitCode, 0, 255);
if (
finishedAtMs < startedAtMs ||
(result.outcome === 'succeeded') !== (exitCode === 0)
) return invalid('completion result is inconsistent');
const artifact = object(command.artifact, 'completion Artifact');
const requiredArtifact = ['logArtifactId', 'byteLength', 'sha256'];
const artifactKeys = Object.keys(artifact);
if (
requiredArtifact.some((key) => !Object.hasOwn(artifact, key)) ||
artifactKeys.some((key) => ![...requiredArtifact, 'truncated'].includes(key))
) return invalid('completion Artifact shape is invalid');
const logArtifactId = identifier('logArtifactId', artifact.logArtifactId, 36);
const sha256 = identifier('sha256', artifact.sha256, 64);
const callbackTokenDigest = identifier(
'callbackTokenDigest', command.callbackTokenDigest, 64,
);
if (
!LOG_ARTIFACT_ID.test(logArtifactId) ||
!SHA256.test(sha256) ||
!SHA256.test(callbackTokenDigest) ||
(artifact.truncated !== undefined &&
typeof artifact.truncated !== 'boolean')
) return invalid('completion evidence is invalid');
return Object.freeze({
...authority,
callbackSequence: integer(
'callbackSequence', command.callbackSequence, 1, 2_147_483_647,
),
callbackTokenDigest,
result: Object.freeze({
outcome: result.outcome as 'succeeded' | 'failed',
startedAtMs,
finishedAtMs,
exitCode,
}),
artifact: Object.freeze({
logArtifactId,
byteLength: integer(
'byteLength', artifact.byteLength, 0, MAX_REMOTE_WORKER_ARTIFACT_BYTES,
),
sha256,
...(artifact.truncated === undefined
? {}
: { truncated: artifact.truncated as boolean }),
}),
});
}
export function createRemoteWorkerCompletionRequestBody(
command: RemoteWorkerCompletionCommand,
): RemoteWorkerCompletionRequestBody {
const value = normalizeRemoteWorkerCompletionCommand(command);
const { workerId: _workerId, workerSessionId: _sessionId, ...body } = value;
return Object.freeze({
schema: REMOTE_WORKER_COMPLETION_SCHEMA,
...body,
artifact: Object.freeze({
...value.artifact,
truncated: value.artifact.truncated ?? null,
}),
});
}
export function parseRemoteWorkerCompletionRequestBody(
value: unknown,
pathAuthority: Readonly<{ workerId: string; workerSessionId: string }>,
): Readonly<RemoteWorkerCompletionCommand> {
const body = object(value, 'completion request');
exactKeys(body, [
'schema', 'workerGeneration', 'projectId', 'runId', 'attemptId',
'offerId', 'leaseGeneration', 'leaseToken', 'expectedLeaseVersion',
'callbackSequence', 'callbackTokenDigest', 'result', 'artifact',
], 'completion request');
if (body.schema !== REMOTE_WORKER_COMPLETION_SCHEMA) {
return invalid('completion schema is invalid');
}
const artifact = object(body.artifact, 'completion Artifact');
exactKeys(artifact, [
'logArtifactId', 'byteLength', 'sha256', 'truncated',
], 'completion Artifact');
const truncated = nullableBoolean('truncated', artifact.truncated);
return normalizeRemoteWorkerCompletionCommand({
workerId: pathAuthority.workerId,
workerSessionId: pathAuthority.workerSessionId,
workerGeneration: body.workerGeneration as number,
projectId: body.projectId as string,
runId: body.runId as string,
attemptId: body.attemptId as string,
offerId: body.offerId as string,
leaseGeneration: body.leaseGeneration as number,
leaseToken: body.leaseToken as string,
expectedLeaseVersion: body.expectedLeaseVersion as number,
callbackSequence: body.callbackSequence as number,
callbackTokenDigest: body.callbackTokenDigest as string,
result: body.result as RemoteWorkerCompletionCommand['result'],
artifact: {
logArtifactId: artifact.logArtifactId as string,
byteLength: artifact.byteLength as number,
sha256: artifact.sha256 as string,
...(truncated === undefined ? {} : { truncated }),
},
});
}
export function normalizeRemoteWorkerCompletionResult(
value: RemoteWorkerCompletionResult,
): Readonly<RemoteWorkerCompletionResult> {
const result = object(value, 'completion response');
exactKeys(result, [
'status', 'runId', 'attemptId', 'callbackSequence',
], 'completion response');
if (
typeof result.status !== 'string' ||
!COMPLETION_STATUSES.has(result.status)
) return invalid('completion response status is invalid');
try {
assertRunDispatchId('runId', result.runId as string);
assertRunDispatchId('attemptId', result.attemptId as string);
} catch {
return invalid('completion response authority is invalid');
}
return Object.freeze({
status: result.status as RemoteWorkerCompletionResult['status'],
runId: result.runId as string,
attemptId: result.attemptId as string,
callbackSequence: integer(
'callbackSequence', result.callbackSequence, 1, 2_147_483_647,
),
});
}
export function createRemoteWorkerCompletionResponseBody(
value: RemoteWorkerCompletionResult,
): RemoteWorkerCompletionResponseBody {
return Object.freeze({
schema: REMOTE_WORKER_COMPLETION_SCHEMA,
...normalizeRemoteWorkerCompletionResult(value),
});
}
export function parseRemoteWorkerCompletionResponse(
serialized: Uint8Array | string,
): Readonly<RemoteWorkerCompletionResult> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_WORKER_COMPLETION_RESPONSE_BYTES
) return invalid('completion response byte size is invalid');
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('completion response is not valid JSON');
}
const response = object(parsed, 'completion response envelope');
exactKeys(response, [
'schema', 'status', 'runId', 'attemptId', 'callbackSequence',
], 'completion response envelope');
if (response.schema !== REMOTE_WORKER_COMPLETION_SCHEMA) {
return invalid('completion response schema is invalid');
}
return normalizeRemoteWorkerCompletionResult({
status: response.status as RemoteWorkerCompletionResult['status'],
runId: response.runId as string,
attemptId: response.attemptId as string,
callbackSequence: response.callbackSequence as number,
});
}
@@ -0,0 +1,421 @@
import {
assertRunDispatchId,
assertRunDispatchLeaseDuration,
assertRunDispatchLeaseFence,
type RunDispatchLeaseFenceReason,
} from '../run/runDispatchLease';
import { assertWorkerId, assertWorkerSessionId } from '../worker/workerSession';
export const REMOTE_WORKER_LEASE_CONTROL_SCHEMA =
'qinglong/remote-worker-lease-control@v1';
export const MAX_REMOTE_WORKER_LEASE_CONTROL_REQUEST_BYTES = 8 * 1024;
export const MAX_REMOTE_WORKER_LEASE_CONTROL_RESPONSE_BYTES = 4 * 1024;
export const REMOTE_WORKER_STOP_REASONS = [
'user', 'policy', 'shutdown', 'reconcile', 'timeout',
] as const;
export type RemoteWorkerStopReason =
(typeof REMOTE_WORKER_STOP_REASONS)[number];
export const REMOTE_WORKER_TERMINAL_STATUSES = [
'succeeded', 'failed', 'cancelled', 'timed_out', 'lost',
] as const;
export type RemoteWorkerTerminalStatus =
(typeof REMOTE_WORKER_TERMINAL_STATUSES)[number];
export interface RemoteWorkerLeaseControlCommand {
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly projectId: string;
readonly runId: string;
readonly attemptId: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseToken: string;
readonly expectedLeaseVersion: number;
}
export type RemoteWorkerLeaseControlRequestBody = Readonly<
Omit<RemoteWorkerLeaseControlCommand, 'workerId' | 'workerSessionId'> & {
readonly schema: typeof REMOTE_WORKER_LEASE_CONTROL_SCHEMA;
}
>;
export type RemoteWorkerLeaseControlResult = Readonly<{
readonly status: 'renewed' | 'stop_requested' | 'terminal';
readonly projectId: string;
readonly runId: string;
readonly attemptId: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseVersion?: number;
readonly renewedAtMs?: number;
readonly expiresAtMs?: number;
readonly stop?: Readonly<{
readonly reason: RemoteWorkerStopReason;
readonly requestedAtMs: number;
}>;
readonly terminalStatus?: RemoteWorkerTerminalStatus;
}>;
export type RemoteWorkerLeaseControlResponseBody = Readonly<{
readonly schema: typeof REMOTE_WORKER_LEASE_CONTROL_SCHEMA;
readonly status: RemoteWorkerLeaseControlResult['status'];
readonly projectId: string;
readonly runId: string;
readonly attemptId: string;
readonly offerId: string;
readonly leaseGeneration: number;
readonly leaseVersion: number | null;
readonly renewedAtMs: number | null;
readonly expiresAtMs: number | null;
readonly stop: Readonly<{
readonly reason: RemoteWorkerStopReason;
readonly requestedAtMs: number;
}> | null;
readonly terminalStatus: RemoteWorkerTerminalStatus | null;
}>;
export interface RemoteWorkerLeaseControlRepository {
control(
command: RemoteWorkerLeaseControlCommand & Readonly<{
leaseDurationMs: number;
timeoutEventId: string;
}>,
): Promise<Readonly<RemoteWorkerLeaseControlResult>>;
}
export class InvalidRemoteWorkerLeaseControlError extends TypeError {
readonly code = 'REMOTE_WORKER_LEASE_CONTROL_INVALID';
constructor(message: string) {
super(`Remote Worker lease control is invalid: ${message}`);
this.name = 'InvalidRemoteWorkerLeaseControlError';
}
}
export class RemoteWorkerLeaseControlFenceRejectedError extends Error {
readonly code = 'REMOTE_WORKER_LEASE_CONTROL_FENCED';
constructor(
readonly attemptId: string,
readonly reason:
| RunDispatchLeaseFenceReason
| 'project_mismatch'
| 'execution_owner_mismatch'
| 'executor_mismatch'
| 'offer_mismatch'
| 'state_mismatch',
) {
super(`Remote Worker lease control is fenced: ${reason}`);
this.name = 'RemoteWorkerLeaseControlFenceRejectedError';
}
}
export class RemoteWorkerLeaseControlUnavailableError extends Error {
readonly code = 'REMOTE_WORKER_LEASE_CONTROL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Remote Worker lease control is unavailable', options);
this.name = 'RemoteWorkerLeaseControlUnavailableError';
}
}
function invalid(message: string): never {
throw new InvalidRemoteWorkerLeaseControlError(message);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid(`${label} is not an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const sorted = [...expected].sort();
if (
actual.length !== sorted.length ||
actual.some((key, index) => key !== sorted[index])
) return invalid(`${label} shape is invalid`);
}
function integer(
label: string,
value: unknown,
minimum = 0,
maximum = Number.MAX_SAFE_INTEGER,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) return invalid(`${label} is invalid`);
return value as number;
}
function identifier(label: string, value: unknown, maximum = 128): string {
if (
typeof value !== 'string' || value.length < 1 ||
Buffer.byteLength(value, 'utf8') > maximum ||
/[\u0000-\u001f\u007f]/.test(value)
) return invalid(`${label} is invalid`);
return value;
}
export function normalizeRemoteWorkerLeaseControlCommand(
value: RemoteWorkerLeaseControlCommand,
): Readonly<RemoteWorkerLeaseControlCommand> {
const command = object(value, 'lease control command');
exactKeys(command, [
'workerId', 'workerSessionId', 'workerGeneration', 'projectId', 'runId',
'attemptId', 'offerId', 'leaseGeneration', 'leaseToken',
'expectedLeaseVersion',
], 'lease control command');
try {
assertWorkerId(command.workerId as string);
assertWorkerSessionId(command.workerSessionId as string);
assertRunDispatchId('runId', command.runId as string);
assertRunDispatchId('attemptId', command.attemptId as string);
assertRunDispatchId('offerId', command.offerId as string);
assertRunDispatchLeaseFence({
workerId: command.workerId as string,
workerSessionId: command.workerSessionId as string,
workerGeneration: command.workerGeneration as number,
leaseGeneration: command.leaseGeneration as number,
leaseToken: command.leaseToken as string,
expectedVersion: command.expectedLeaseVersion as number,
});
} catch {
return invalid('lease control authority is invalid');
}
return Object.freeze({
workerId: command.workerId as string,
workerSessionId: command.workerSessionId as string,
workerGeneration: integer(
'workerGeneration', command.workerGeneration, 1, 2_147_483_647,
),
projectId: identifier('projectId', command.projectId),
runId: command.runId as string,
attemptId: command.attemptId as string,
offerId: command.offerId as string,
leaseGeneration: integer(
'leaseGeneration', command.leaseGeneration, 1, 2_147_483_647,
),
leaseToken: command.leaseToken as string,
expectedLeaseVersion: integer(
'expectedLeaseVersion', command.expectedLeaseVersion,
0, 2_147_483_647,
),
});
}
export function createRemoteWorkerLeaseControlRequestBody(
value: RemoteWorkerLeaseControlCommand,
): RemoteWorkerLeaseControlRequestBody {
const command = normalizeRemoteWorkerLeaseControlCommand(value);
const { workerId: _workerId, workerSessionId: _sessionId, ...body } = command;
return Object.freeze({ schema: REMOTE_WORKER_LEASE_CONTROL_SCHEMA, ...body });
}
export function parseRemoteWorkerLeaseControlRequestBody(
value: unknown,
pathAuthority: Readonly<{ workerId: string; workerSessionId: string }>,
): Readonly<RemoteWorkerLeaseControlCommand> {
const body = object(value, 'lease control request');
exactKeys(body, [
'schema', 'workerGeneration', 'projectId', 'runId', 'attemptId',
'offerId', 'leaseGeneration', 'leaseToken', 'expectedLeaseVersion',
], 'lease control request');
if (body.schema !== REMOTE_WORKER_LEASE_CONTROL_SCHEMA) {
return invalid('lease control schema is invalid');
}
return normalizeRemoteWorkerLeaseControlCommand({
workerId: pathAuthority.workerId,
workerSessionId: pathAuthority.workerSessionId,
workerGeneration: body.workerGeneration as number,
projectId: body.projectId as string,
runId: body.runId as string,
attemptId: body.attemptId as string,
offerId: body.offerId as string,
leaseGeneration: body.leaseGeneration as number,
leaseToken: body.leaseToken as string,
expectedLeaseVersion: body.expectedLeaseVersion as number,
});
}
export function normalizeRemoteWorkerLeaseControlResult(
value: RemoteWorkerLeaseControlResult,
): Readonly<RemoteWorkerLeaseControlResult> {
const result = object(value, 'lease control result');
const allowed = [
'status', 'projectId', 'runId', 'attemptId', 'offerId', 'leaseGeneration',
'leaseVersion', 'renewedAtMs', 'expiresAtMs', 'stop', 'terminalStatus',
];
if (Object.keys(result).some((key) => !allowed.includes(key))) {
return invalid('lease control result shape is invalid');
}
for (const key of [
'status', 'projectId', 'runId', 'attemptId', 'offerId', 'leaseGeneration',
]) {
if (!Object.hasOwn(result, key)) {
return invalid('lease control result is incomplete');
}
}
const status = result.status;
if (!['renewed', 'stop_requested', 'terminal'].includes(String(status))) {
return invalid('lease control result status is invalid');
}
try {
assertRunDispatchId('runId', result.runId as string);
assertRunDispatchId('attemptId', result.attemptId as string);
assertRunDispatchId('offerId', result.offerId as string);
} catch {
return invalid('lease control result authority is invalid');
}
const common = {
projectId: identifier('projectId', result.projectId),
runId: result.runId as string,
attemptId: result.attemptId as string,
offerId: result.offerId as string,
leaseGeneration: integer(
'leaseGeneration', result.leaseGeneration, 1, 2_147_483_647,
),
};
if (status === 'terminal') {
if (
result.leaseVersion !== undefined || result.renewedAtMs !== undefined ||
result.expiresAtMs !== undefined || result.stop !== undefined ||
typeof result.terminalStatus !== 'string' ||
!REMOTE_WORKER_TERMINAL_STATUSES.includes(
result.terminalStatus as RemoteWorkerTerminalStatus,
)
) return invalid('terminal lease control result is invalid');
return Object.freeze({
status: 'terminal' as const,
...common,
terminalStatus: result.terminalStatus as RemoteWorkerTerminalStatus,
});
}
if (
result.terminalStatus !== undefined || result.leaseVersion === undefined ||
result.renewedAtMs === undefined || result.expiresAtMs === undefined
) return invalid('renewed lease control result is invalid');
const leaseVersion = integer(
'leaseVersion', result.leaseVersion, 1, 2_147_483_647,
);
const renewedAtMs = integer('renewedAtMs', result.renewedAtMs);
const expiresAtMs = integer('expiresAtMs', result.expiresAtMs);
if (expiresAtMs <= renewedAtMs) return invalid('lease expiry is invalid');
if (status === 'renewed') {
if (result.stop !== undefined) return invalid('renewed control is invalid');
return Object.freeze({
status: 'renewed' as const,
...common,
leaseVersion,
renewedAtMs,
expiresAtMs,
});
}
const stop = object(result.stop, 'stop control');
exactKeys(stop, ['reason', 'requestedAtMs'], 'stop control');
if (
typeof stop.reason !== 'string' ||
!REMOTE_WORKER_STOP_REASONS.includes(stop.reason as RemoteWorkerStopReason)
) return invalid('stop reason is invalid');
return Object.freeze({
status: 'stop_requested' as const,
...common,
leaseVersion,
renewedAtMs,
expiresAtMs,
stop: Object.freeze({
reason: stop.reason as RemoteWorkerStopReason,
requestedAtMs: integer('requestedAtMs', stop.requestedAtMs),
}),
});
}
export function createRemoteWorkerLeaseControlResponseBody(
value: RemoteWorkerLeaseControlResult,
): RemoteWorkerLeaseControlResponseBody {
const result = normalizeRemoteWorkerLeaseControlResult(value);
return Object.freeze({
schema: REMOTE_WORKER_LEASE_CONTROL_SCHEMA,
status: result.status,
projectId: result.projectId,
runId: result.runId,
attemptId: result.attemptId,
offerId: result.offerId,
leaseGeneration: result.leaseGeneration,
leaseVersion: result.leaseVersion ?? null,
renewedAtMs: result.renewedAtMs ?? null,
expiresAtMs: result.expiresAtMs ?? null,
stop: result.stop ?? null,
terminalStatus: result.terminalStatus ?? null,
});
}
export function parseRemoteWorkerLeaseControlResponse(
serialized: Uint8Array | string,
): Readonly<RemoteWorkerLeaseControlResult> {
const bytes = typeof serialized === 'string'
? Buffer.from(serialized, 'utf8')
: Buffer.from(serialized);
if (
bytes.byteLength < 2 ||
bytes.byteLength > MAX_REMOTE_WORKER_LEASE_CONTROL_RESPONSE_BYTES
) return invalid('lease control response byte size is invalid');
let parsed: unknown;
try {
parsed = JSON.parse(bytes.toString('utf8')) as unknown;
} catch {
return invalid('lease control response is not valid JSON');
}
const response = object(parsed, 'lease control response');
exactKeys(response, [
'schema', 'status', 'projectId', 'runId', 'attemptId', 'offerId',
'leaseGeneration', 'leaseVersion', 'renewedAtMs', 'expiresAtMs', 'stop',
'terminalStatus',
], 'lease control response');
if (response.schema !== REMOTE_WORKER_LEASE_CONTROL_SCHEMA) {
return invalid('lease control response schema is invalid');
}
return normalizeRemoteWorkerLeaseControlResult({
status: response.status as RemoteWorkerLeaseControlResult['status'],
projectId: response.projectId as string,
runId: response.runId as string,
attemptId: response.attemptId as string,
offerId: response.offerId as string,
leaseGeneration: response.leaseGeneration as number,
...(response.leaseVersion === null
? {}
: { leaseVersion: response.leaseVersion as number }),
...(response.renewedAtMs === null
? {}
: { renewedAtMs: response.renewedAtMs as number }),
...(response.expiresAtMs === null
? {}
: { expiresAtMs: response.expiresAtMs as number }),
...(response.stop === null
? {}
: { stop: response.stop as NonNullable<RemoteWorkerLeaseControlResult['stop']> }),
...(response.terminalStatus === null
? {}
: { terminalStatus: response.terminalStatus as RemoteWorkerTerminalStatus }),
});
}
export function assertRemoteWorkerLeaseControlDuration(value: number): void {
try {
assertRunDispatchLeaseDuration(value);
} catch {
invalid('lease duration is invalid');
}
}
@@ -0,0 +1,666 @@
import { createHash } from 'node:crypto';
import type { WorkerSessionRecord } from '../worker/workerSession';
import { assertWorkerSessionRecord } from '../worker/workerSession';
import { semver } from '../versioning/pinnedSemver';
export const REMOTE_WORKER_EXECUTOR_CAPABILITY = 'remote-worker';
export const MAX_REMOTE_PLACEMENT_VALUES = 16;
export const MAX_REMOTE_PLACEMENT_PREFERENCES = 16;
export const MAX_REMOTE_WORKER_RUNTIMES = 32;
export const MAX_REMOTE_WORKER_LABELS = 32;
export const MAX_REMOTE_WORKER_FEATURES = 32;
export const MAX_REMOTE_WORKER_GPUS = 8;
const CAPABILITY_NAME = /^[a-z0-9][a-z0-9._+-]*$/;
const LABEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
export interface RemoteWorkerRuntimeCapability {
readonly name: string;
readonly version: string;
}
export interface RemoteWorkerCapabilities {
readonly architecture: string;
readonly executors: readonly string[];
readonly operatingSystem?: string;
readonly runtimes?: readonly RemoteWorkerRuntimeCapability[];
readonly labels?: Readonly<Record<string, string>>;
readonly capacity?: Readonly<{
readonly cpuCores?: number;
readonly memoryBytes?: number;
readonly diskBytes?: number;
readonly gpu?: readonly Readonly<{
readonly vendor: string;
readonly model?: string;
readonly memoryBytes?: number;
}>[];
}>;
readonly features?: readonly string[];
}
export interface RemoteWorkerRuntimeRequirement {
readonly name: string;
readonly versionRange?: string;
}
export interface RemoteWorkerPlacementSpec {
readonly required?: Readonly<{
readonly architectures?: readonly string[];
readonly operatingSystems?: readonly string[];
readonly executors?: readonly string[];
readonly runtimes?: readonly RemoteWorkerRuntimeRequirement[];
readonly labels?: Readonly<Record<string, string>>;
readonly minMemoryBytes?: number;
readonly minDiskBytes?: number;
readonly gpuVendor?: string;
readonly features?: readonly string[];
}>;
readonly preferred?: readonly Readonly<{
readonly labels: Readonly<Record<string, string>>;
readonly weight: number;
}>[];
}
export type RemoteWorkerPlacementMismatch =
| 'worker_unavailable'
| 'architecture'
| 'operating_system'
| 'executor'
| 'runtime'
| 'label'
| 'memory'
| 'disk'
| 'gpu'
| 'feature';
export interface RemoteWorkerPlacementDecision {
readonly matches: boolean;
readonly score: number;
readonly mismatches: readonly RemoteWorkerPlacementMismatch[];
}
function invalid(message: string): never {
throw new TypeError(`Remote Worker placement value is invalid: ${message}`);
}
function object(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const allowed = new Set([...required, ...optional]);
if (
required.some((key) => !Object.hasOwn(value, key)) ||
Object.keys(value).some((key) => !allowed.has(key))
)
invalid(`${label} shape is invalid`);
}
function boundedString(
value: unknown,
label: string,
maximum: number,
pattern?: RegExp,
): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > maximum ||
/[\u0000-\u001f\u007f]/.test(value) ||
(pattern !== undefined && !pattern.test(value))
)
invalid(`${label} is invalid`);
return value;
}
function positiveInteger(
value: unknown,
label: string,
maximum = Number.MAX_SAFE_INTEGER,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
invalid(`${label} is invalid`);
}
return value as number;
}
function sortedStrings(
value: unknown,
label: string,
maximum: number,
allowEmpty = true,
): readonly string[] {
if (
!Array.isArray(value) ||
value.length > maximum ||
(!allowEmpty && value.length === 0)
) {
invalid(`${label} is invalid`);
}
const result = value.map((item, index) =>
boundedString(item, `${label}[${index}]`, 64, CAPABILITY_NAME),
);
if (new Set(result).size !== result.length)
invalid(`${label} contains duplicates`);
return Object.freeze(result.sort());
}
function normalizedLabels(
value: unknown,
label: string,
maximum: number,
): Readonly<Record<string, string>> {
const source = object(value, label);
const entries = Object.entries(source);
if (entries.length > maximum) invalid(`${label} exceeds its item budget`);
return Object.freeze(
Object.fromEntries(
entries
.map(
([key, item]) =>
[
boundedString(key, `${label} key`, 128, LABEL_KEY),
boundedString(item, `${label}.${key}`, 256),
] as const,
)
.sort((left, right) => left[0].localeCompare(right[0])),
),
);
}
export function normalizeRemoteWorkerCapabilities(
value: unknown,
): RemoteWorkerCapabilities {
const source = object(value, 'capabilities');
exactKeys(
source,
['architecture', 'executors'],
['capacity', 'features', 'labels', 'operatingSystem', 'runtimes'],
'capabilities',
);
const architecture = boundedString(
source.architecture,
'architecture',
32,
CAPABILITY_NAME,
);
const executors = sortedStrings(source.executors, 'executors', 16, false);
const operatingSystem =
source.operatingSystem === undefined
? undefined
: boundedString(
source.operatingSystem,
'operatingSystem',
32,
CAPABILITY_NAME,
);
let runtimes: readonly RemoteWorkerRuntimeCapability[] | undefined;
if (source.runtimes !== undefined) {
if (
!Array.isArray(source.runtimes) ||
source.runtimes.length > MAX_REMOTE_WORKER_RUNTIMES
)
invalid('runtimes is invalid');
const mapped = source.runtimes.map((item, index) => {
const runtime = object(item, `runtimes[${index}]`);
exactKeys(runtime, ['name', 'version'], [], `runtimes[${index}]`);
const name = boundedString(
runtime.name,
`runtimes[${index}].name`,
64,
CAPABILITY_NAME,
);
const version = boundedString(
runtime.version,
`runtimes[${index}].version`,
64,
);
if (semver().valid(version) === null)
invalid(`runtimes[${index}].version is not semver`);
return Object.freeze({ name, version });
});
if (new Set(mapped.map((item) => item.name)).size !== mapped.length)
invalid('runtimes repeats a runtime name');
runtimes = Object.freeze(
mapped.sort((left, right) => left.name.localeCompare(right.name)),
);
}
const labels =
source.labels === undefined
? undefined
: normalizedLabels(source.labels, 'labels', MAX_REMOTE_WORKER_LABELS);
let capacity: RemoteWorkerCapabilities['capacity'];
if (source.capacity !== undefined) {
const candidate = object(source.capacity, 'capacity');
exactKeys(
candidate,
[],
['cpuCores', 'diskBytes', 'gpu', 'memoryBytes'],
'capacity',
);
let gpu: NonNullable<RemoteWorkerCapabilities['capacity']>['gpu'];
if (candidate.gpu !== undefined) {
if (
!Array.isArray(candidate.gpu) ||
candidate.gpu.length > MAX_REMOTE_WORKER_GPUS
)
invalid('capacity.gpu is invalid');
gpu = Object.freeze(
candidate.gpu.map((item, index) => {
const device = object(item, `capacity.gpu[${index}]`);
exactKeys(
device,
['vendor'],
['memoryBytes', 'model'],
`capacity.gpu[${index}]`,
);
return Object.freeze({
vendor: boundedString(
device.vendor,
`capacity.gpu[${index}].vendor`,
64,
CAPABILITY_NAME,
),
...(device.model === undefined
? {}
: {
model: boundedString(
device.model,
`capacity.gpu[${index}].model`,
128,
),
}),
...(device.memoryBytes === undefined
? {}
: {
memoryBytes: positiveInteger(
device.memoryBytes,
`capacity.gpu[${index}].memoryBytes`,
),
}),
});
}),
);
}
capacity = Object.freeze({
...(candidate.cpuCores === undefined
? {}
: {
cpuCores: positiveInteger(
candidate.cpuCores,
'capacity.cpuCores',
4096,
),
}),
...(candidate.memoryBytes === undefined
? {}
: {
memoryBytes: positiveInteger(
candidate.memoryBytes,
'capacity.memoryBytes',
),
}),
...(candidate.diskBytes === undefined
? {}
: {
diskBytes: positiveInteger(
candidate.diskBytes,
'capacity.diskBytes',
),
}),
...(gpu === undefined ? {} : { gpu }),
});
}
const features =
source.features === undefined
? undefined
: sortedStrings(source.features, 'features', MAX_REMOTE_WORKER_FEATURES);
return Object.freeze({
architecture,
executors,
...(operatingSystem === undefined ? {} : { operatingSystem }),
...(runtimes === undefined ? {} : { runtimes }),
...(labels === undefined ? {} : { labels }),
...(capacity === undefined ? {} : { capacity }),
...(features === undefined ? {} : { features }),
});
}
export function canonicalRemoteWorkerCapabilities(value: unknown): Readonly<{
capabilities: RemoteWorkerCapabilities;
json: string;
hash: string;
}> {
const capabilities = normalizeRemoteWorkerCapabilities(value);
const json = JSON.stringify(capabilities);
return Object.freeze({
capabilities,
json,
hash: createHash('sha256').update(json, 'utf8').digest('hex'),
});
}
export function parseRemoteWorkerCapabilities(
record: WorkerSessionRecord,
): RemoteWorkerCapabilities {
assertWorkerSessionRecord(record);
const canonical = canonicalRemoteWorkerCapabilities(
JSON.parse(record.capabilitiesJson) as unknown,
);
if (
canonical.json !== record.capabilitiesJson ||
canonical.hash !== record.capabilitiesHash
) {
invalid('capabilities snapshot is not canonical');
}
return canonical.capabilities;
}
function optionalStringList(
value: unknown,
label: string,
): readonly string[] | undefined {
return value === undefined
? undefined
: sortedStrings(value, label, MAX_REMOTE_PLACEMENT_VALUES);
}
export function normalizeRemoteWorkerPlacement(
value: unknown,
): RemoteWorkerPlacementSpec {
const source = object(value, 'placement');
exactKeys(source, [], ['preferred', 'required'], 'placement');
let required: RemoteWorkerPlacementSpec['required'];
if (source.required !== undefined) {
const candidate = object(source.required, 'placement.required');
exactKeys(
candidate,
[],
[
'architectures',
'executors',
'features',
'gpuVendor',
'labels',
'minDiskBytes',
'minMemoryBytes',
'operatingSystems',
'runtimes',
],
'placement.required',
);
const architectures = optionalStringList(
candidate.architectures,
'placement.required.architectures',
);
const operatingSystems = optionalStringList(
candidate.operatingSystems,
'placement.required.operatingSystems',
);
const executors = optionalStringList(
candidate.executors,
'placement.required.executors',
);
const features = optionalStringList(
candidate.features,
'placement.required.features',
);
let runtimes: readonly RemoteWorkerRuntimeRequirement[] | undefined;
if (candidate.runtimes !== undefined) {
if (
!Array.isArray(candidate.runtimes) ||
candidate.runtimes.length > MAX_REMOTE_PLACEMENT_VALUES
)
invalid('placement.required.runtimes is invalid');
const mapped = candidate.runtimes.map((item, index) => {
const runtime = object(item, `placement.required.runtimes[${index}]`);
exactKeys(
runtime,
['name'],
['versionRange'],
`placement.required.runtimes[${index}]`,
);
const name = boundedString(
runtime.name,
`placement.required.runtimes[${index}].name`,
64,
CAPABILITY_NAME,
);
const versionRange =
runtime.versionRange === undefined
? undefined
: boundedString(
runtime.versionRange,
`placement.required.runtimes[${index}].versionRange`,
128,
);
if (
versionRange !== undefined &&
semver().validRange(versionRange) === null
)
invalid(
`placement.required.runtimes[${index}].versionRange is not semver`,
);
return Object.freeze({
name,
...(versionRange === undefined ? {} : { versionRange }),
});
});
if (new Set(mapped.map((item) => item.name)).size !== mapped.length)
invalid('placement.required.runtimes repeats a runtime name');
runtimes = Object.freeze(
mapped.sort((left, right) => left.name.localeCompare(right.name)),
);
}
required = Object.freeze({
...(architectures === undefined ? {} : { architectures }),
...(operatingSystems === undefined ? {} : { operatingSystems }),
...(executors === undefined ? {} : { executors }),
...(runtimes === undefined ? {} : { runtimes }),
...(candidate.labels === undefined
? {}
: {
labels: normalizedLabels(
candidate.labels,
'placement.required.labels',
MAX_REMOTE_PLACEMENT_VALUES,
),
}),
...(candidate.minMemoryBytes === undefined
? {}
: {
minMemoryBytes: positiveInteger(
candidate.minMemoryBytes,
'placement.required.minMemoryBytes',
),
}),
...(candidate.minDiskBytes === undefined
? {}
: {
minDiskBytes: positiveInteger(
candidate.minDiskBytes,
'placement.required.minDiskBytes',
),
}),
...(candidate.gpuVendor === undefined
? {}
: {
gpuVendor: boundedString(
candidate.gpuVendor,
'placement.required.gpuVendor',
64,
CAPABILITY_NAME,
),
}),
...(features === undefined ? {} : { features }),
});
}
let preferred: RemoteWorkerPlacementSpec['preferred'];
if (source.preferred !== undefined) {
if (
!Array.isArray(source.preferred) ||
source.preferred.length > MAX_REMOTE_PLACEMENT_PREFERENCES
)
invalid('placement.preferred is invalid');
preferred = Object.freeze(
source.preferred.map((item, index) => {
const preference = object(item, `placement.preferred[${index}]`);
exactKeys(
preference,
['labels', 'weight'],
[],
`placement.preferred[${index}]`,
);
const labels = normalizedLabels(
preference.labels,
`placement.preferred[${index}].labels`,
MAX_REMOTE_PLACEMENT_VALUES,
);
if (Object.keys(labels).length === 0)
invalid(`placement.preferred[${index}].labels is empty`);
return Object.freeze({
labels,
weight: positiveInteger(
preference.weight,
`placement.preferred[${index}].weight`,
100,
),
});
}),
);
}
return Object.freeze({
...(required === undefined ? {} : { required }),
...(preferred === undefined ? {} : { preferred }),
});
}
export function effectiveRemoteWorkerPlacement(
value: unknown,
): RemoteWorkerPlacementSpec {
const placement = normalizeRemoteWorkerPlacement(value ?? {});
const executors = placement.required?.executors;
if (
executors !== undefined &&
!executors.includes(REMOTE_WORKER_EXECUTOR_CAPABILITY)
) {
invalid(`placement must require ${REMOTE_WORKER_EXECUTOR_CAPABILITY}`);
}
return normalizeRemoteWorkerPlacement({
...placement,
required: {
...placement.required,
executors: executors ?? [REMOTE_WORKER_EXECUTOR_CAPABILITY],
},
});
}
function containsLabels(
actual: Readonly<Record<string, string>> | undefined,
expected: Readonly<Record<string, string>>,
): boolean {
return Object.entries(expected).every(
([key, value]) => actual?.[key] === value,
);
}
export function evaluateRemoteWorkerPlacement(
worker: WorkerSessionRecord,
placementValue: unknown,
observedAtMs: number,
): RemoteWorkerPlacementDecision {
assertWorkerSessionRecord(worker);
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0)
invalid('observedAtMs is invalid');
const capabilities = parseRemoteWorkerCapabilities(worker);
const placement = effectiveRemoteWorkerPlacement(placementValue);
const required = placement.required ?? {};
const mismatches: RemoteWorkerPlacementMismatch[] = [];
if (
worker.status !== 'online' ||
worker.availableSlots < 1 ||
worker.leaseExpiresAtMs <= observedAtMs
)
mismatches.push('worker_unavailable');
if (
required.architectures?.length &&
!required.architectures.includes(capabilities.architecture)
)
mismatches.push('architecture');
if (
required.operatingSystems?.length &&
(!capabilities.operatingSystem ||
!required.operatingSystems.includes(capabilities.operatingSystem))
)
mismatches.push('operating_system');
if (
required.executors?.some(
(executor) => !capabilities.executors.includes(executor),
)
)
mismatches.push('executor');
if (
required.runtimes?.some(
(requirement) =>
!(capabilities.runtimes ?? []).some(
(runtime) =>
runtime.name === requirement.name &&
(requirement.versionRange === undefined ||
semver().satisfies(runtime.version, requirement.versionRange, {
includePrerelease: true,
})),
),
)
)
mismatches.push('runtime');
if (required.labels && !containsLabels(capabilities.labels, required.labels))
mismatches.push('label');
if (
required.minMemoryBytes !== undefined &&
(capabilities.capacity?.memoryBytes ?? 0) < required.minMemoryBytes
)
mismatches.push('memory');
if (
required.minDiskBytes !== undefined &&
(capabilities.capacity?.diskBytes ?? 0) < required.minDiskBytes
)
mismatches.push('disk');
if (
required.gpuVendor !== undefined &&
!(capabilities.capacity?.gpu ?? []).some(
(gpu) => gpu.vendor === required.gpuVendor,
)
)
mismatches.push('gpu');
if (
required.features?.some(
(feature) => !(capabilities.features ?? []).includes(feature),
)
)
mismatches.push('feature');
const score = (placement.preferred ?? []).reduce(
(total, preference) =>
total +
(containsLabels(capabilities.labels, preference.labels)
? preference.weight
: 0),
0,
);
return Object.freeze({
matches: mismatches.length === 0,
score,
mismatches: Object.freeze(mismatches),
});
}
@@ -0,0 +1,372 @@
import {
normalizeProjectPolicySubject,
type ProjectRole,
} from '../security/project-policy/projectPolicy';
import {
normalizeSecurityPolicyDecision,
type SecurityPolicyFence,
type SecuritySubject,
} from '../security/security';
import { RUN_STATUSES, type RunStatus } from './run';
export const RUN_CANCELLATION_SCHEMA = 'qinglong/run-cancellation@v1' as const;
/** @deprecated Use RUN_CANCELLATION_SCHEMA from the profile-neutral export. */
export const CLUSTER_RUN_CANCELLATION_SCHEMA = RUN_CANCELLATION_SCHEMA;
export const CLUSTER_RUN_CANCELLATION_STATUSES = [
'accepted',
'already_requested',
'already_terminal',
] as const;
export type ClusterRunCancellationStatus =
(typeof CLUSTER_RUN_CANCELLATION_STATUSES)[number];
export interface ClusterRunCancellationRequestBody {
readonly schema: typeof CLUSTER_RUN_CANCELLATION_SCHEMA;
readonly mutationId: string;
}
export interface ClusterRunCancellationWorkflowTarget {
readonly packageName: string;
readonly workflowId: string;
}
export interface ClusterRunCancellationCommand {
readonly projectId: string;
readonly runId: string;
readonly mutationId: string;
readonly eventId: string;
readonly subject: Readonly<SecuritySubject>;
readonly policyFence: Readonly<SecurityPolicyFence>;
readonly workflowTarget?: Readonly<ClusterRunCancellationWorkflowTarget>;
}
export interface ClusterRunCancellationResult {
readonly status: ClusterRunCancellationStatus;
readonly projectId: string;
readonly runId: string;
readonly runStatus: RunStatus;
readonly runVersion: number;
readonly eventSequence: number;
readonly cancelRequestedAtMs?: number;
readonly cancelReason?: 'user' | 'policy' | 'shutdown' | 'reconcile' | 'timeout';
}
export interface ClusterRunCancellationResponseBody
extends ClusterRunCancellationResult {
readonly schema: typeof CLUSTER_RUN_CANCELLATION_SCHEMA;
}
export interface ClusterRunCancellationRepository {
requestUserCancellation(
command: Readonly<ClusterRunCancellationCommand>,
): Promise<Readonly<ClusterRunCancellationResult>>;
}
export type ClusterRunCancellationFenceReason =
| 'authorization_changed'
| 'project_mismatch'
| 'state_mismatch';
export class InvalidClusterRunCancellationError extends TypeError {
constructor(message: string) {
super(`Cluster Run cancellation is invalid: ${message}`);
this.name = 'InvalidClusterRunCancellationError';
}
}
export class ClusterRunCancellationNotFoundError extends Error {
readonly code = 'CLUSTER_RUN_CANCELLATION_NOT_FOUND';
constructor() {
super('Cluster Run cancellation target does not exist');
this.name = 'ClusterRunCancellationNotFoundError';
}
}
export class ClusterRunCancellationFenceRejectedError extends Error {
readonly code = 'CLUSTER_RUN_CANCELLATION_FENCE_REJECTED';
constructor(readonly reason: ClusterRunCancellationFenceReason) {
super(`Cluster Run cancellation fence rejected: ${reason}`);
this.name = 'ClusterRunCancellationFenceRejectedError';
}
}
export class ClusterRunCancellationUnavailableError extends Error {
readonly code = 'CLUSTER_RUN_CANCELLATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Cluster Run cancellation is unavailable', options);
this.name = 'ClusterRunCancellationUnavailableError';
}
}
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const EVENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,35}$/;
const PACKAGE_NAME_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const WORKFLOW_ID_PATTERN = /^[a-z][a-z0-9-]{0,62}$/;
const TERMINAL = new Set<RunStatus>([
'succeeded',
'failed',
'cancelled',
'timed_out',
]);
const CANCEL_REASONS = new Set([
'user',
'policy',
'shutdown',
'reconcile',
'timeout',
]);
function exactKeys(value: object, expected: readonly string[]): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidClusterRunCancellationError('shape is invalid');
}
}
function identifier(value: unknown, name: string): string {
if (typeof value !== 'string' || !ID_PATTERN.test(value)) {
throw new InvalidClusterRunCancellationError(`${name} is invalid`);
}
return value;
}
function counter(value: unknown, name: string, minimum: number): number {
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < minimum ||
value > 2_147_483_647
) {
throw new InvalidClusterRunCancellationError(`${name} is invalid`);
}
return value;
}
function timestamp(value: unknown, name: string): number {
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 0
) {
throw new InvalidClusterRunCancellationError(`${name} is invalid`);
}
return value;
}
export function parseClusterRunCancellationRequestBody(
value: unknown,
): Readonly<ClusterRunCancellationRequestBody> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterRunCancellationError('request body is invalid');
}
exactKeys(value, ['schema', 'mutationId']);
const body = value as Record<string, unknown>;
if (body.schema !== CLUSTER_RUN_CANCELLATION_SCHEMA) {
throw new InvalidClusterRunCancellationError('schema is invalid');
}
return Object.freeze({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: identifier(body.mutationId, 'mutationId'),
});
}
export function normalizeClusterRunCancellationCommand(
value: ClusterRunCancellationCommand,
): Readonly<ClusterRunCancellationCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterRunCancellationError('command is invalid');
}
const hasWorkflowTarget = value.workflowTarget !== undefined;
exactKeys(
value,
[
'projectId',
'runId',
'mutationId',
'eventId',
'subject',
'policyFence',
...(hasWorkflowTarget ? ['workflowTarget'] : []),
],
);
if (typeof value.eventId !== 'string' || !EVENT_ID_PATTERN.test(value.eventId)) {
throw new InvalidClusterRunCancellationError('eventId is invalid');
}
let subject: Readonly<SecuritySubject>;
let fence: Readonly<SecurityPolicyFence> | null;
try {
subject = normalizeProjectPolicySubject(value.subject);
fence = normalizeSecurityPolicyDecision({
effect: 'allow',
reasons: ['role_grant'],
fence: value.policyFence,
}).fence;
} catch {
throw new InvalidClusterRunCancellationError(
'authorization authority is invalid',
);
}
if (!fence || fence.bindingVersion === null) {
throw new InvalidClusterRunCancellationError(
'authorization fence is incomplete',
);
}
let workflowTarget:
| Readonly<ClusterRunCancellationWorkflowTarget>
| undefined;
if (hasWorkflowTarget) {
const target = value.workflowTarget;
if (!target || typeof target !== 'object' || Array.isArray(target)) {
throw new InvalidClusterRunCancellationError(
'workflowTarget is invalid',
);
}
exactKeys(target, ['packageName', 'workflowId']);
if (
typeof target.packageName !== 'string' ||
!PACKAGE_NAME_PATTERN.test(target.packageName) ||
typeof target.workflowId !== 'string' ||
!WORKFLOW_ID_PATTERN.test(target.workflowId)
) {
throw new InvalidClusterRunCancellationError(
'workflowTarget is invalid',
);
}
workflowTarget = Object.freeze({
packageName: target.packageName,
workflowId: target.workflowId,
});
}
return Object.freeze({
projectId: identifier(value.projectId, 'projectId'),
runId: identifier(value.runId, 'runId'),
mutationId: identifier(value.mutationId, 'mutationId'),
eventId: value.eventId,
subject,
policyFence: fence,
...(workflowTarget === undefined ? {} : { workflowTarget }),
});
}
export function normalizeClusterRunCancellationResult(
value: ClusterRunCancellationResult,
): Readonly<ClusterRunCancellationResult> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterRunCancellationError('result is invalid');
}
const hasCancellation = value.cancelRequestedAtMs !== undefined;
exactKeys(
value,
hasCancellation
? [
'status', 'projectId', 'runId', 'runStatus', 'runVersion',
'eventSequence', 'cancelRequestedAtMs', 'cancelReason',
]
: [
'status', 'projectId', 'runId', 'runStatus', 'runVersion',
'eventSequence',
],
);
if (
!CLUSTER_RUN_CANCELLATION_STATUSES.includes(value.status) ||
!RUN_STATUSES.includes(value.runStatus) ||
(value.status === 'accepted' && !hasCancellation) ||
(value.status === 'already_requested' && !hasCancellation) ||
(value.status === 'already_terminal' && !TERMINAL.has(value.runStatus)) ||
(value.status !== 'already_terminal' && TERMINAL.has(value.runStatus))
) {
throw new InvalidClusterRunCancellationError('result state is invalid');
}
let cancelRequestedAtMs: number | undefined;
let cancelReason: ClusterRunCancellationResult['cancelReason'];
if (hasCancellation) {
cancelRequestedAtMs = timestamp(
value.cancelRequestedAtMs,
'cancelRequestedAtMs',
);
if (!CANCEL_REASONS.has(value.cancelReason ?? '')) {
throw new InvalidClusterRunCancellationError('cancelReason is invalid');
}
cancelReason = value.cancelReason;
} else if (value.cancelReason !== undefined) {
throw new InvalidClusterRunCancellationError('cancellation shape is invalid');
}
return Object.freeze({
status: value.status,
projectId: identifier(value.projectId, 'projectId'),
runId: identifier(value.runId, 'runId'),
runStatus: value.runStatus,
runVersion: counter(value.runVersion, 'runVersion', 1),
eventSequence: counter(value.eventSequence, 'eventSequence', 0),
...(cancelRequestedAtMs === undefined
? {}
: { cancelRequestedAtMs, cancelReason: cancelReason! }),
});
}
export function createClusterRunCancellationResponseBody(
value: ClusterRunCancellationResult,
): Readonly<ClusterRunCancellationResponseBody> {
return Object.freeze({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
...normalizeClusterRunCancellationResult(value),
});
}
export function parseClusterRunCancellationResponseBody(
value: unknown,
): Readonly<ClusterRunCancellationResponseBody> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterRunCancellationError('response body is invalid');
}
const { schema, ...result } = value as Record<string, unknown>;
if (schema !== CLUSTER_RUN_CANCELLATION_SCHEMA) {
throw new InvalidClusterRunCancellationError('schema is invalid');
}
return createClusterRunCancellationResponseBody(
result as unknown as ClusterRunCancellationResult,
);
}
export type ClusterRunCancellationAllowedRole = Extract<
ProjectRole,
'owner' | 'admin' | 'operator'
>;
// Profile-neutral names are canonical for new Local and Cluster consumers.
// Cluster-prefixed names remain source-compatible throughout the 3.0 Alpha.
export const RUN_CANCELLATION_STATUSES = CLUSTER_RUN_CANCELLATION_STATUSES;
export type RunCancellationStatus = ClusterRunCancellationStatus;
export type RunCancellationRequestBody = ClusterRunCancellationRequestBody;
export type RunCancellationWorkflowTarget =
ClusterRunCancellationWorkflowTarget;
export type RunCancellationCommand = ClusterRunCancellationCommand;
export type RunCancellationResult = ClusterRunCancellationResult;
export type RunCancellationResponseBody = ClusterRunCancellationResponseBody;
export type RunCancellationRepository = ClusterRunCancellationRepository;
export type RunCancellationFenceReason = ClusterRunCancellationFenceReason;
export type RunCancellationAllowedRole = ClusterRunCancellationAllowedRole;
export const InvalidRunCancellationError =
InvalidClusterRunCancellationError;
export const RunCancellationNotFoundError =
ClusterRunCancellationNotFoundError;
export const RunCancellationFenceRejectedError =
ClusterRunCancellationFenceRejectedError;
export const RunCancellationUnavailableError =
ClusterRunCancellationUnavailableError;
export const parseRunCancellationRequestBody =
parseClusterRunCancellationRequestBody;
export const normalizeRunCancellationCommand =
normalizeClusterRunCancellationCommand;
export const normalizeRunCancellationResult =
normalizeClusterRunCancellationResult;
export const createRunCancellationResponseBody =
createClusterRunCancellationResponseBody;
export const parseRunCancellationResponseBody =
parseClusterRunCancellationResponseBody;
@@ -0,0 +1,241 @@
import { MAX_STEP_RUNS_PER_RUN } from './stepRun';
export const MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGE_SIZE = 128;
export const MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGES_PER_CYCLE = 64;
export interface ClusterRunCancellationConvergencePageCommand {
readonly limit: number;
}
export interface ClusterRunCancellationConvergencePageResult {
readonly scanned: number;
readonly settledRuns: number;
readonly settledAttempts: number;
readonly blocked: number;
readonly hasMore: boolean;
}
export interface ClusterRunCancellationConvergenceRepository {
convergePage(
command: Readonly<ClusterRunCancellationConvergencePageCommand>,
): Promise<Readonly<ClusterRunCancellationConvergencePageResult>>;
}
export interface ClusterRunCancellationConvergenceCycleResult
extends ClusterRunCancellationConvergencePageResult {
readonly pages: number;
readonly remaining: boolean;
readonly stopReason: 'complete' | 'page_limit' | 'blocked';
}
export interface ClusterRunCancellationConvergenceCoordinatorOptions {
readonly pageSize?: number;
readonly maxPages?: number;
}
export class ClusterRunCancellationConvergenceUnavailableError extends Error {
readonly code = 'CLUSTER_RUN_CANCELLATION_CONVERGENCE_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Cluster Run cancellation convergence is unavailable', options);
this.name = 'ClusterRunCancellationConvergenceUnavailableError';
}
}
function boundedInteger(
name: string,
value: number,
minimum: number,
maximum: number,
): number {
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);
}
return value;
}
export function normalizeClusterRunCancellationConvergencePageCommand(
value: ClusterRunCancellationConvergencePageCommand,
): Readonly<ClusterRunCancellationConvergencePageCommand> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Cluster Run cancellation convergence command is invalid');
}
const keys = Object.keys(value).sort();
if (keys.length !== 1 || keys[0] !== 'limit') {
throw new TypeError('Cluster Run cancellation convergence command shape is invalid');
}
const limit = boundedInteger(
'Cluster Run cancellation convergence page size',
value.limit,
1,
MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGE_SIZE,
);
return Object.freeze({ limit });
}
export function normalizeClusterRunCancellationConvergencePageResult(
value: ClusterRunCancellationConvergencePageResult,
limit = MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGE_SIZE,
): Readonly<ClusterRunCancellationConvergencePageResult> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Cluster Run cancellation convergence result is invalid');
}
const keys = Object.keys(value).sort();
if (
keys.length !== 5 ||
keys.join(',') !== 'blocked,hasMore,scanned,settledAttempts,settledRuns'
) {
throw new TypeError('Cluster Run cancellation convergence result shape is invalid');
}
const maximum = boundedInteger(
'Cluster Run cancellation convergence result limit',
limit,
1,
MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGE_SIZE,
);
const scanned = boundedInteger(
'Cluster Run cancellation convergence scanned count',
value.scanned,
0,
maximum,
);
const settledRuns = boundedInteger(
'Cluster Run cancellation convergence settled Run count',
value.settledRuns,
0,
scanned,
);
const settledAttempts = boundedInteger(
'Cluster Run cancellation convergence settled Attempt count',
value.settledAttempts,
0,
scanned * MAX_STEP_RUNS_PER_RUN,
);
const blocked = boundedInteger(
'Cluster Run cancellation convergence blocked count',
value.blocked,
0,
scanned - settledRuns,
);
if (typeof value.hasMore !== 'boolean') {
throw new TypeError('Cluster Run cancellation convergence continuation is invalid');
}
return Object.freeze({
scanned,
settledRuns,
settledAttempts,
blocked,
hasMore: value.hasMore,
});
}
/**
* Runs a bounded, sequential convergence cycle. It owns no timer or connection;
* deployment profiles choose the cadence and the repository owns row locking.
*/
export class ClusterRunCancellationConvergenceCoordinator {
private readonly pageSize: number;
private readonly maxPages: number;
private inFlight:
| Promise<Readonly<ClusterRunCancellationConvergenceCycleResult>>
| undefined;
constructor(
private readonly repository: ClusterRunCancellationConvergenceRepository,
options: ClusterRunCancellationConvergenceCoordinatorOptions,
) {
if (
typeof repository?.convergePage !== 'function' ||
!options || typeof options !== 'object' || Array.isArray(options)
) {
throw new TypeError('Cluster Run cancellation convergence coordinator is invalid');
}
this.pageSize = boundedInteger(
'Cluster Run cancellation convergence page size',
options.pageSize ?? 32,
1,
MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGE_SIZE,
);
this.maxPages = boundedInteger(
'Cluster Run cancellation convergence page limit',
options.maxPages ?? 4,
1,
MAX_CLUSTER_RUN_CANCELLATION_CONVERGENCE_PAGES_PER_CYCLE,
);
}
reconcile(): Promise<Readonly<ClusterRunCancellationConvergenceCycleResult>> {
if (this.inFlight) return this.inFlight;
const operation = this.reconcileOnce().finally(() => {
if (this.inFlight === operation) this.inFlight = undefined;
});
this.inFlight = operation;
return operation;
}
private async reconcileOnce(): Promise<Readonly<ClusterRunCancellationConvergenceCycleResult>> {
let pages = 0;
let scanned = 0;
let settledRuns = 0;
let settledAttempts = 0;
let blocked = 0;
for (; pages < this.maxPages; pages += 1) {
let page: Readonly<ClusterRunCancellationConvergencePageResult>;
try {
page = normalizeClusterRunCancellationConvergencePageResult(
await this.repository.convergePage({
limit: this.pageSize,
}),
this.pageSize,
);
} catch (error) {
if (error instanceof ClusterRunCancellationConvergenceUnavailableError) {
throw error;
}
throw new ClusterRunCancellationConvergenceUnavailableError({ cause: error });
}
scanned += page.scanned;
settledRuns += page.settledRuns;
settledAttempts += page.settledAttempts;
blocked += page.blocked;
const completedPages = pages + 1;
if (page.blocked > 0) {
return Object.freeze({
pages: completedPages,
scanned,
settledRuns,
settledAttempts,
blocked,
hasMore: page.hasMore,
remaining: true,
stopReason: 'blocked' as const,
});
}
if (!page.hasMore) {
return Object.freeze({
pages: completedPages,
scanned,
settledRuns,
settledAttempts,
blocked,
hasMore: false,
remaining: false,
stopReason: 'complete' as const,
});
}
if (page.scanned === 0 || page.settledRuns === 0) {
throw new ClusterRunCancellationConvergenceUnavailableError();
}
}
return Object.freeze({
pages,
scanned,
settledRuns,
settledAttempts,
blocked,
hasMore: true,
remaining: true,
stopReason: 'page_limit' as const,
});
}
}
@@ -0,0 +1,513 @@
import type {
RunAttemptRecord,
RunEventRecord,
RunRecord,
} from './run';
import {
runRetryDelayMs,
type RunRetryPolicyRecord,
} from './runRetryPolicy';
export const MAX_CLUSTER_RUN_LOST_RETRY_PAGE_SIZE = 64;
export type ClusterRunLostRetryDisposition =
| 'scheduled'
| 'requeued'
| 'failed_disabled'
| 'failed_unsafe'
| 'failed_exhausted';
export interface ClusterRunLostRetryPageCommand {
readonly limit: number;
}
export interface ClusterRunLostRetryPageResult {
readonly scanned: number;
readonly scheduled: number;
readonly requeued: number;
readonly failed: number;
readonly raced: number;
readonly hasMore: boolean;
}
export interface ClusterRunLostRetryRepository {
reconcilePage(
command: Readonly<ClusterRunLostRetryPageCommand>,
): Promise<Readonly<ClusterRunLostRetryPageResult>>;
}
export interface ClusterRunLostRetryCoordinatorOptions {
readonly pageSize?: number;
}
export interface ClusterRunLostRetryTransitionInput {
readonly run: Readonly<RunRecord>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly policy: Readonly<RunRetryPolicyRecord> | null;
readonly observedAtMs: number;
readonly runEventId: string;
readonly attemptId?: string;
readonly attemptEventId?: string;
}
export interface ClusterRunLostRetryTransition {
readonly disposition: ClusterRunLostRetryDisposition;
readonly runTransitions: readonly Readonly<RunRecord>[];
readonly policy?: Readonly<RunRetryPolicyRecord>;
readonly attempt?: Readonly<RunAttemptRecord>;
readonly events: readonly Readonly<RunEventRecord>[];
}
export class ClusterRunLostRetryUnavailableError extends Error {
readonly code = 'CLUSTER_RUN_LOST_RETRY_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Cluster Run lost retry is unavailable', options);
this.name = 'ClusterRunLostRetryUnavailableError';
}
}
export class InvalidClusterRunLostRetryTransitionError extends TypeError {
readonly code = 'CLUSTER_RUN_LOST_RETRY_INVALID';
constructor(message: string) {
super(`Cluster Run lost retry is invalid: ${message}`);
this.name = 'InvalidClusterRunLostRetryTransitionError';
}
}
function invalid(message: string): never {
throw new InvalidClusterRunLostRetryTransitionError(message);
}
function boundedInteger(
name: string,
value: number,
minimum: number,
maximum: number,
): number {
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);
}
return value;
}
function identifier(name: string, value: string | undefined): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 128 ||
/[\u0000-\u001f\u007f]/.test(value)
) {
return invalid(`${name} is invalid`);
}
return value;
}
function reserve(
current: Readonly<RunRecord>,
status: RunRecord['status'],
atMs: number,
error?: Readonly<{ code: string; summary: string }>,
): Readonly<RunRecord> {
const version = current.version + 1;
const eventSequence = current.eventSequence + 1;
if (
!Number.isSafeInteger(version) ||
version < 1 ||
!Number.isSafeInteger(eventSequence) ||
eventSequence < 1
) {
return invalid('Run counter overflowed');
}
const next: RunRecord = {
...current,
status,
version,
eventSequence,
};
if (status === 'queued') {
next.queuedAtMs = atMs;
delete next.errorCode;
delete next.errorSummary;
} else if (error) {
next.errorCode = error.code;
next.errorSummary = error.summary;
}
if (status === 'failed') next.finishedAtMs = atMs;
return Object.freeze(next);
}
function event(
id: string,
run: Readonly<RunRecord>,
attemptId: string,
type: string,
dedupeKey: string,
createdAtMs: number,
payload: Readonly<Record<string, unknown>>,
): Readonly<RunEventRecord> {
return Object.freeze({
id: identifier('event ID', id),
runId: run.id,
sequence: run.eventSequence,
type,
dedupeKey,
actorType: 'reconciler',
attemptId,
payload: Object.freeze({ ...payload, version: run.version }),
createdAtMs,
});
}
function transitionTime(
input: Readonly<ClusterRunLostRetryTransitionInput>,
): number {
const atMs = input.observedAtMs;
if (!Number.isSafeInteger(atMs) || atMs < 0) {
return invalid('observation time is invalid');
}
const lowerBound = Math.max(
input.run.createdAtMs,
input.run.startedAtMs ?? 0,
input.attempt.createdAtMs,
input.attempt.startedAtMs ?? 0,
input.attempt.finishedAtMs ?? 0,
input.policy?.updatedAtMs ?? 0,
);
if (atMs < lowerBound) return invalid('observation precedes durable state');
return atMs;
}
function finish(
input: Readonly<ClusterRunLostRetryTransitionInput>,
atMs: number,
disposition:
| 'failed_disabled'
| 'failed_unsafe'
| 'failed_exhausted',
error: Readonly<{ code: string; summary: string }>,
): Readonly<ClusterRunLostRetryTransition> {
const run = reserve(input.run, 'failed', atMs, error);
let policy = input.policy ?? undefined;
if (input.policy?.nextAttemptAtMs !== undefined) {
const { nextAttemptAtMs: _nextAttemptAtMs, ...withoutNextAttempt } =
input.policy;
policy = Object.freeze({
...withoutNextAttempt,
version: input.policy.version + 1,
updatedAtMs: atMs,
});
}
return Object.freeze({
disposition,
runTransitions: Object.freeze([run]),
...(policy === undefined ? {} : { policy }),
events: Object.freeze([
event(
input.runEventId,
run,
input.attempt.id,
'run.failed',
`cluster-lost-retry:${disposition}:${input.attempt.id}`,
atMs,
{
from_status: input.run.status,
to_status: 'failed',
attempt: input.attempt.attempt,
error_code: error.code,
},
),
]),
});
}
/**
* Pure, profile-neutral lost recovery policy. Storage owns row locking and
* persistence; this function can only schedule, create a fresh Attempt, or
* terminalize an unsafe/exhausted Run.
*/
export function buildClusterRunLostRetryTransition(
input: Readonly<ClusterRunLostRetryTransitionInput>,
): Readonly<ClusterRunLostRetryTransition> {
const { run, attempt, policy } = input;
if (
!run ||
!attempt ||
run.executionOwner !== 'runtime' ||
run.triggerType === 'plugin_package_workflow' ||
(run.status !== 'lost' && run.status !== 'retry_wait') ||
run.cancelRequestedAtMs !== undefined ||
attempt.runId !== run.id ||
attempt.status !== 'lost' ||
attempt.attempt < 1
) {
return invalid('aggregate is not eligible');
}
const atMs = transitionTime(input);
identifier('Run ID', run.id);
identifier('Attempt ID', attempt.id);
identifier('Run event ID', input.runEventId);
if (!policy || !policy.retryOnLost || policy.maxAttempts <= 1) {
return finish(input, atMs, 'failed_disabled', {
code: 'RUN_LOST_RETRY_DISABLED',
summary: 'Run was lost and automatic retry was not enabled at admission',
});
}
if (policy.runId !== run.id) return invalid('retry policy Run mismatches');
if (policy.safety === 'unknown') {
return finish(input, atMs, 'failed_unsafe', {
code: 'RUN_LOST_RETRY_UNSAFE',
summary: 'Run was lost but execution safety was not declared',
});
}
if (attempt.attempt >= policy.maxAttempts) {
return finish(input, atMs, 'failed_exhausted', {
code: 'RUN_LOST_RETRY_EXHAUSTED',
summary: 'Run exhausted its admitted automatic retry attempts',
});
}
if (run.status === 'lost') {
const nextAttemptAtMs =
Math.max(run.createdAtMs, attempt.createdAtMs, attempt.finishedAtMs ?? 0) +
runRetryDelayMs(policy, attempt.attempt);
if (!Number.isSafeInteger(nextAttemptAtMs)) {
return invalid('next Attempt time overflowed');
}
const error = {
code: 'RUN_LOST_RETRY_SCHEDULED',
summary: 'A fresh Attempt will be created after the admitted backoff',
};
const nextRun = reserve(run, 'retry_wait', atMs, error);
const nextPolicy = Object.freeze({
...policy,
nextAttemptAtMs,
version: policy.version + 1,
updatedAtMs: atMs,
});
return Object.freeze({
disposition: 'scheduled',
runTransitions: Object.freeze([nextRun]),
policy: nextPolicy,
events: Object.freeze([
event(
input.runEventId,
nextRun,
attempt.id,
'run.retry_wait',
`cluster-lost-retry:scheduled:${attempt.id}`,
atMs,
{
from_status: 'lost',
to_status: 'retry_wait',
attempt: attempt.attempt,
max_attempts: policy.maxAttempts,
safety: policy.safety,
next_attempt_at_ms: nextAttemptAtMs,
error_code: error.code,
},
),
]),
});
}
if (
policy.nextAttemptAtMs === undefined ||
policy.nextAttemptAtMs > atMs
) {
return invalid('retry_wait policy is not due');
}
const nextAttemptId = identifier('replacement Attempt ID', input.attemptId);
const nextAttemptEventId = identifier(
'Attempt event ID',
input.attemptEventId,
);
const queued = reserve(run, 'queued', atMs);
const claimed = reserve(queued, 'queued', atMs);
const replacement = Object.freeze({
id: nextAttemptId,
runId: run.id,
attempt: attempt.attempt + 1,
status: 'claimed' as const,
executorType: attempt.executorType,
callbackSequence: 0,
createdAtMs: atMs,
});
const { nextAttemptAtMs: _nextAttemptAtMs, ...withoutNextAttempt } = policy;
const nextPolicy = Object.freeze({
...withoutNextAttempt,
version: policy.version + 1,
updatedAtMs: atMs,
});
return Object.freeze({
disposition: 'requeued',
runTransitions: Object.freeze([queued, claimed]),
policy: nextPolicy,
attempt: replacement,
events: Object.freeze([
event(
input.runEventId,
queued,
replacement.id,
'run.queued',
`cluster-lost-retry:queued:${replacement.id}`,
atMs,
{
from_status: 'retry_wait',
to_status: 'queued',
previous_attempt_id: attempt.id,
},
),
event(
nextAttemptEventId,
claimed,
replacement.id,
'attempt.claimed',
`cluster-lost-retry:attempt-claimed:${replacement.id}`,
atMs,
{
attempt: replacement.attempt,
executor_type: replacement.executorType,
previous_attempt_id: attempt.id,
},
),
]),
});
}
export function normalizeClusterRunLostRetryPageCommand(
value: ClusterRunLostRetryPageCommand,
): Readonly<ClusterRunLostRetryPageCommand> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).length !== 1 ||
!Object.prototype.hasOwnProperty.call(value, 'limit')
) {
throw new TypeError('Cluster Run lost retry command is invalid');
}
return Object.freeze({
limit: boundedInteger(
'Cluster Run lost retry page size',
value.limit,
1,
MAX_CLUSTER_RUN_LOST_RETRY_PAGE_SIZE,
),
});
}
export function normalizeClusterRunLostRetryPageResult(
value: ClusterRunLostRetryPageResult,
limit = MAX_CLUSTER_RUN_LOST_RETRY_PAGE_SIZE,
): Readonly<ClusterRunLostRetryPageResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).sort().join(',') !==
'failed,hasMore,raced,requeued,scanned,scheduled'
) {
throw new TypeError('Cluster Run lost retry result is invalid');
}
const maximum = boundedInteger(
'Cluster Run lost retry result limit',
limit,
1,
MAX_CLUSTER_RUN_LOST_RETRY_PAGE_SIZE,
);
const scanned = boundedInteger(
'Cluster Run lost retry scanned count',
value.scanned,
0,
maximum,
);
const scheduled = boundedInteger(
'Cluster Run lost retry scheduled count',
value.scheduled,
0,
scanned,
);
const requeued = boundedInteger(
'Cluster Run lost retry requeued count',
value.requeued,
0,
scanned,
);
const failed = boundedInteger(
'Cluster Run lost retry failed count',
value.failed,
0,
scanned,
);
const raced = boundedInteger(
'Cluster Run lost retry raced count',
value.raced,
0,
scanned,
);
if (
scheduled + requeued + failed + raced !== scanned ||
typeof value.hasMore !== 'boolean'
) {
throw new TypeError('Cluster Run lost retry result counts are invalid');
}
return Object.freeze({
scanned,
scheduled,
requeued,
failed,
raced,
hasMore: value.hasMore,
});
}
/** One non-overlapping bounded page; deployment owns the shared cadence. */
export class ClusterRunLostRetryCoordinator {
private readonly pageSize: number;
private inFlight:
| Promise<Readonly<ClusterRunLostRetryPageResult>>
| undefined;
constructor(
private readonly repository: ClusterRunLostRetryRepository,
options: ClusterRunLostRetryCoordinatorOptions = {},
) {
if (
typeof repository?.reconcilePage !== 'function' ||
!options ||
typeof options !== 'object' ||
Array.isArray(options)
) {
throw new TypeError('Cluster Run lost retry coordinator is invalid');
}
this.pageSize = boundedInteger(
'Cluster Run lost retry page size',
options.pageSize ?? 16,
1,
MAX_CLUSTER_RUN_LOST_RETRY_PAGE_SIZE,
);
}
reconcile(): Promise<Readonly<ClusterRunLostRetryPageResult>> {
if (this.inFlight) return this.inFlight;
const operation = Promise.resolve()
.then(() =>
this.repository.reconcilePage({ limit: this.pageSize }),
)
.then((result) =>
normalizeClusterRunLostRetryPageResult(result, this.pageSize),
)
.catch((error: unknown) => {
if (error instanceof ClusterRunLostRetryUnavailableError) throw error;
throw new ClusterRunLostRetryUnavailableError({ cause: error });
})
.finally(() => {
if (this.inFlight === operation) this.inFlight = undefined;
});
this.inFlight = operation;
return operation;
}
}
@@ -0,0 +1,84 @@
import type { RunRecord } from './run';
export const MAX_PROJECT_RUN_LIST_STORAGE_LIMIT = 65;
export interface ProjectRunListCursor {
readonly createdAtMs: number;
readonly runId: string;
}
export interface ProjectRunListQuery {
readonly projectId: string;
readonly limit: number;
readonly after?: Readonly<ProjectRunListCursor>;
}
export interface ProjectRunListReader {
listRunsByProject(
query: Readonly<ProjectRunListQuery>,
): Promise<readonly RunRecord[]>;
}
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
function boundedText(value: unknown, maximum: number): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value.length <= maximum &&
!CONTROL_PATTERN.test(value)
);
}
export function normalizeProjectRunListQuery(
value: Readonly<ProjectRunListQuery>,
): Readonly<ProjectRunListQuery> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError('Project Run list query is invalid');
}
const keys = Reflect.ownKeys(value);
const afterKeys =
value.after &&
typeof value.after === 'object' &&
!Array.isArray(value.after)
? Reflect.ownKeys(value.after)
: [];
if (
keys.length < 2 ||
keys.length > 3 ||
keys.some(
(key) => key !== 'projectId' && key !== 'limit' && key !== 'after',
) ||
!Object.hasOwn(value, 'projectId') ||
!Object.hasOwn(value, 'limit') ||
!boundedText(value.projectId, 128) ||
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PROJECT_RUN_LIST_STORAGE_LIMIT ||
(value.after !== undefined &&
(!value.after ||
typeof value.after !== 'object' ||
Array.isArray(value.after) ||
afterKeys.length !== 2 ||
afterKeys.some((key) => key !== 'createdAtMs' && key !== 'runId') ||
!Object.hasOwn(value.after, 'createdAtMs') ||
!Object.hasOwn(value.after, 'runId') ||
!Number.isSafeInteger(value.after.createdAtMs) ||
value.after.createdAtMs < 0 ||
!boundedText(value.after.runId, 128)))
) {
throw new TypeError('Project Run list query is invalid');
}
return Object.freeze({
projectId: value.projectId,
limit: value.limit,
...(value.after === undefined
? {}
: {
after: Object.freeze({
createdAtMs: value.after.createdAtMs,
runId: value.after.runId,
}),
}),
});
}
@@ -0,0 +1,192 @@
import {
RUN_EVENT_ACTOR_TYPES,
type RunEventRecord,
type RunRecord,
} from '../run';
import type { RunRepositoryReader } from '../runRepository';
export const DEFAULT_BOUNDED_RUN_EVENT_LIST_LIMIT = 32;
export const MAX_BOUNDED_RUN_EVENT_LIST_LIMIT = 64;
const MAX_INT = 2_147_483_647;
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export interface BoundedRunEventListInput {
readonly afterSequence?: number;
readonly limit?: number;
}
export interface BoundedRunEventListItem {
readonly sequence: number;
readonly type: string;
readonly actorType: RunEventRecord['actorType'];
readonly createdAtMs: number;
}
export interface BoundedRunEventListProjection {
readonly found: boolean;
readonly events: readonly Readonly<BoundedRunEventListItem>[];
readonly hasMore: boolean;
readonly nextAfterSequence: number;
}
export class InvalidBoundedRunEventListProjectionError extends TypeError {
readonly code = 'BOUNDED_RUN_EVENT_LIST_PROJECTION_INVALID';
constructor() {
super('Bounded Run event list projection input is invalid');
this.name = 'InvalidBoundedRunEventListProjectionError';
}
}
export class BoundedRunEventListProjectionUnavailableError extends Error {
readonly code = 'BOUNDED_RUN_EVENT_LIST_PROJECTION_UNAVAILABLE';
constructor() {
super('Bounded Run event list projection is unavailable');
this.name = 'BoundedRunEventListProjectionUnavailableError';
}
}
function boundedText(value: unknown, maximum: number): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value.length <= maximum &&
!CONTROL_PATTERN.test(value)
);
}
function integer(
value: unknown,
minimum: number,
maximum: number,
): value is number {
return (
Number.isSafeInteger(value) &&
Number(value) >= minimum &&
Number(value) <= maximum
);
}
function normalizeInput(value: Readonly<BoundedRunEventListInput>): Readonly<{
afterSequence: number;
limit: number;
}> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidBoundedRunEventListProjectionError();
}
const keys = Reflect.ownKeys(value);
if (
keys.length > 2 ||
keys.some((key) => key !== 'afterSequence' && key !== 'limit') ||
(value.afterSequence !== undefined &&
!integer(value.afterSequence, 0, MAX_INT)) ||
(value.limit !== undefined &&
!integer(value.limit, 1, MAX_BOUNDED_RUN_EVENT_LIST_LIMIT))
) {
throw new InvalidBoundedRunEventListProjectionError();
}
return Object.freeze({
afterSequence: value.afterSequence ?? 0,
limit: value.limit ?? DEFAULT_BOUNDED_RUN_EVENT_LIST_LIMIT,
});
}
function ownsRun(value: RunRecord, projectId: string, runId: string): boolean {
return (
!!value &&
typeof value === 'object' &&
!Array.isArray(value) &&
value.projectId === projectId &&
value.id === runId &&
boundedText(value.projectId, 128) &&
boundedText(value.id, 128)
);
}
function projectEvent(
value: RunEventRecord,
runId: string,
previousSequence: number,
): Readonly<BoundedRunEventListItem> | null {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
value.runId !== runId ||
!integer(value.sequence, previousSequence + 1, MAX_INT) ||
!boundedText(value.type, 128) ||
!RUN_EVENT_ACTOR_TYPES.includes(value.actorType) ||
!integer(value.createdAtMs, 0, Number.MAX_SAFE_INTEGER)
) {
return null;
}
return Object.freeze({
sequence: value.sequence,
type: value.type,
actorType: value.actorType,
createdAtMs: value.createdAtMs,
});
}
export async function executeBoundedRunEventListProjection(
runs: Pick<RunRepositoryReader, 'findRunById' | 'listEvents'>,
projectId: string,
runId: string,
input: Readonly<BoundedRunEventListInput>,
): Promise<Readonly<BoundedRunEventListProjection>> {
if (
!runs ||
typeof runs.findRunById !== 'function' ||
typeof runs.listEvents !== 'function' ||
!boundedText(projectId, 128) ||
!boundedText(runId, 128)
) {
throw new InvalidBoundedRunEventListProjectionError();
}
const normalized = normalizeInput(input);
let run: RunRecord | null;
try {
run = await runs.findRunById(runId);
} catch {
throw new BoundedRunEventListProjectionUnavailableError();
}
if (!run || !ownsRun(run, projectId, runId)) {
return Object.freeze({
found: false,
events: Object.freeze([]),
hasMore: false,
nextAfterSequence: normalized.afterSequence,
});
}
let rows: RunEventRecord[];
try {
rows = await runs.listEvents(runId, {
afterSequence: normalized.afterSequence,
limit: normalized.limit + 1,
});
} catch {
throw new BoundedRunEventListProjectionUnavailableError();
}
if (!Array.isArray(rows) || rows.length > normalized.limit + 1) {
throw new BoundedRunEventListProjectionUnavailableError();
}
const events: Readonly<BoundedRunEventListItem>[] = [];
let previousSequence = normalized.afterSequence;
for (let index = 0; index < rows.length; index += 1) {
const projected = projectEvent(rows[index]!, runId, previousSequence);
if (!projected) throw new BoundedRunEventListProjectionUnavailableError();
previousSequence = projected.sequence;
if (index < normalized.limit) events.push(projected);
}
const lastReturned = events.at(-1);
return Object.freeze({
found: true,
events: Object.freeze(events),
hasMore: rows.length > normalized.limit,
nextAfterSequence: lastReturned?.sequence ?? normalized.afterSequence,
});
}
@@ -0,0 +1,237 @@
import {
EXECUTION_ORIGINS,
RUN_STATUSES,
type ExecutionOrigin,
type ExecutionOwner,
type RunRecord,
type RunStatus,
} from '../run';
import {
normalizeProjectRunListQuery,
type ProjectRunListCursor,
type ProjectRunListReader,
} from '../projectRunList';
export const DEFAULT_BOUNDED_RUN_LIST_LIMIT = 32;
export const MAX_BOUNDED_RUN_LIST_LIMIT = 64;
const MAX_INT = 2_147_483_647;
const MIN_INT = -2_147_483_648;
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export interface BoundedRunListInput {
readonly limit?: number;
readonly after?: Readonly<ProjectRunListCursor>;
}
export interface BoundedRunListItem {
readonly id: string;
readonly taskId: string;
readonly taskRevision: string;
readonly status: RunStatus;
readonly version: number;
readonly eventSequence: number;
readonly priority: number;
readonly executionOrigin: ExecutionOrigin;
readonly executionOwner: ExecutionOwner;
readonly createdAtMs: number;
readonly queuedAtMs?: number;
readonly startedAtMs?: number;
readonly finishedAtMs?: number;
}
export interface BoundedRunListProjection {
readonly runs: readonly Readonly<BoundedRunListItem>[];
readonly hasMore: boolean;
readonly next?: Readonly<ProjectRunListCursor>;
}
export class InvalidBoundedRunListProjectionError extends TypeError {
readonly code = 'BOUNDED_RUN_LIST_PROJECTION_INVALID';
constructor() {
super('Bounded Run list projection input is invalid');
this.name = 'InvalidBoundedRunListProjectionError';
}
}
export class BoundedRunListProjectionUnavailableError extends Error {
readonly code = 'BOUNDED_RUN_LIST_PROJECTION_UNAVAILABLE';
constructor() {
super('Bounded Run list projection is unavailable');
this.name = 'BoundedRunListProjectionUnavailableError';
}
}
function boundedText(value: unknown, maximum: number): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value.length <= maximum &&
!CONTROL_PATTERN.test(value)
);
}
function integer(value: unknown, minimum: number, maximum: number): value is number {
return (
Number.isSafeInteger(value) &&
Number(value) >= minimum &&
Number(value) <= maximum
);
}
function cursor(value: unknown): value is Readonly<ProjectRunListCursor> {
return (
!!value &&
typeof value === 'object' &&
!Array.isArray(value) &&
Reflect.ownKeys(value).length === 2 &&
Object.hasOwn(value, 'createdAtMs') &&
Object.hasOwn(value, 'runId') &&
integer((value as ProjectRunListCursor).createdAtMs, 0, Number.MAX_SAFE_INTEGER) &&
boundedText((value as ProjectRunListCursor).runId, 128)
);
}
function normalizeInput(value: Readonly<BoundedRunListInput>): Readonly<{
limit: number;
after?: Readonly<ProjectRunListCursor>;
}> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidBoundedRunListProjectionError();
}
const keys = Reflect.ownKeys(value);
if (
keys.length > 2 ||
keys.some((key) => key !== 'limit' && key !== 'after') ||
(value.limit !== undefined &&
!integer(value.limit, 1, MAX_BOUNDED_RUN_LIST_LIMIT)) ||
(value.after !== undefined && !cursor(value.after))
) {
throw new InvalidBoundedRunListProjectionError();
}
return Object.freeze({
limit: value.limit ?? DEFAULT_BOUNDED_RUN_LIST_LIMIT,
...(value.after === undefined
? {}
: {
after: Object.freeze({
createdAtMs: value.after.createdAtMs,
runId: value.after.runId,
}),
}),
});
}
function isBefore(
value: Readonly<ProjectRunListCursor>,
boundary: Readonly<ProjectRunListCursor>,
): boolean {
return (
value.createdAtMs < boundary.createdAtMs ||
(value.createdAtMs === boundary.createdAtMs && value.runId < boundary.runId)
);
}
function optionalTimestamp(value: unknown): value is number | undefined {
return value === undefined || integer(value, 0, Number.MAX_SAFE_INTEGER);
}
function projectRun(
value: RunRecord,
projectId: string,
boundary?: Readonly<ProjectRunListCursor>,
): Readonly<BoundedRunListItem> | null {
const rowCursor = { createdAtMs: value?.createdAtMs, runId: value?.id };
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
value.projectId !== projectId ||
!cursor(rowCursor) ||
(boundary !== undefined && !isBefore(rowCursor, boundary)) ||
!boundedText(value.taskId, 255) ||
!boundedText(value.taskRevision, 255) ||
!RUN_STATUSES.includes(value.status) ||
!EXECUTION_ORIGINS.includes(value.executionOrigin) ||
(value.executionOwner !== 'legacy' && value.executionOwner !== 'runtime') ||
!integer(value.version, 0, MAX_INT) ||
!integer(value.eventSequence, 0, MAX_INT) ||
!integer(value.priority, MIN_INT, MAX_INT) ||
!optionalTimestamp(value.queuedAtMs) ||
!optionalTimestamp(value.startedAtMs) ||
!optionalTimestamp(value.finishedAtMs)
) {
return null;
}
return Object.freeze({
id: value.id,
taskId: value.taskId,
taskRevision: value.taskRevision,
status: value.status,
version: value.version,
eventSequence: value.eventSequence,
priority: value.priority,
executionOrigin: value.executionOrigin,
executionOwner: value.executionOwner,
createdAtMs: value.createdAtMs,
...(value.queuedAtMs === undefined ? {} : { queuedAtMs: value.queuedAtMs }),
...(value.startedAtMs === undefined ? {} : { startedAtMs: value.startedAtMs }),
...(value.finishedAtMs === undefined ? {} : { finishedAtMs: value.finishedAtMs }),
});
}
export async function executeBoundedRunListProjection(
runs: ProjectRunListReader,
projectId: string,
input: Readonly<BoundedRunListInput>,
): Promise<Readonly<BoundedRunListProjection>> {
if (
!runs ||
typeof runs.listRunsByProject !== 'function' ||
!boundedText(projectId, 128)
) {
throw new InvalidBoundedRunListProjectionError();
}
const normalized = normalizeInput(input);
const query = normalizeProjectRunListQuery({
projectId,
limit: normalized.limit + 1,
...(normalized.after === undefined ? {} : { after: normalized.after }),
});
let rows: readonly RunRecord[];
try {
rows = await runs.listRunsByProject(query);
} catch {
throw new BoundedRunListProjectionUnavailableError();
}
if (!Array.isArray(rows) || rows.length > normalized.limit + 1) {
throw new BoundedRunListProjectionUnavailableError();
}
const projected: Readonly<BoundedRunListItem>[] = [];
let boundary = normalized.after;
for (let index = 0; index < rows.length; index += 1) {
const row = rows[index]!;
const item = projectRun(row, projectId, boundary);
if (!item) throw new BoundedRunListProjectionUnavailableError();
boundary = Object.freeze({ createdAtMs: row.createdAtMs, runId: row.id });
if (index < normalized.limit) projected.push(item);
}
const hasMore = rows.length > normalized.limit;
const lastReturned = projected.at(-1);
return Object.freeze({
runs: Object.freeze(projected),
hasMore,
...(hasMore && lastReturned
? {
next: Object.freeze({
createdAtMs: lastReturned.createdAtMs,
runId: lastReturned.id,
}),
}
: {}),
});
}
@@ -0,0 +1,121 @@
import { EXECUTION_ORIGINS, RUN_STATUSES, type RunRecord } from '../run';
import type { RunRepositoryReader } from '../runRepository';
const MAX_INT = 2_147_483_647;
const MIN_INT = -2_147_483_648;
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export type BoundedRunReadProjection = Readonly<
Record<string, boolean | string | number>
>;
export class BoundedRunReadProjectionUnavailableError extends Error {
readonly code = 'BOUNDED_RUN_READ_PROJECTION_UNAVAILABLE';
constructor() {
super('Bounded Run read projection is unavailable');
this.name = 'BoundedRunReadProjectionUnavailableError';
}
}
function boundedText(value: unknown, maximum: number): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value.length <= maximum &&
!CONTROL_PATTERN.test(value)
);
}
function integer(
value: unknown,
minimum: number,
maximum: number,
): value is number {
return (
Number.isSafeInteger(value) &&
Number(value) >= minimum &&
Number(value) <= maximum
);
}
function optionalTimestamp(value: unknown): value is number | undefined {
return value === undefined || integer(value, 0, Number.MAX_SAFE_INTEGER);
}
function projectRun(
value: RunRecord,
projectId: string,
runId: string,
): BoundedRunReadProjection | null {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
value.projectId !== projectId ||
value.id !== runId ||
!boundedText(value.id, 128) ||
!boundedText(value.projectId, 128) ||
!boundedText(value.taskId, 255) ||
!boundedText(value.taskRevision, 255) ||
!RUN_STATUSES.includes(value.status) ||
!EXECUTION_ORIGINS.includes(value.executionOrigin) ||
(value.executionOwner !== 'legacy' && value.executionOwner !== 'runtime') ||
!integer(value.version, 0, MAX_INT) ||
!integer(value.eventSequence, 0, MAX_INT) ||
!integer(value.priority, MIN_INT, MAX_INT) ||
!integer(value.createdAtMs, 0, Number.MAX_SAFE_INTEGER) ||
!optionalTimestamp(value.queuedAtMs) ||
!optionalTimestamp(value.startedAtMs) ||
!optionalTimestamp(value.finishedAtMs)
) {
return null;
}
return Object.freeze({
found: true,
id: value.id,
taskId: value.taskId,
taskRevision: value.taskRevision,
status: value.status,
version: value.version,
eventSequence: value.eventSequence,
priority: value.priority,
executionOrigin: value.executionOrigin,
executionOwner: value.executionOwner,
createdAtMs: value.createdAtMs,
...(value.queuedAtMs === undefined ? {} : { queuedAtMs: value.queuedAtMs }),
...(value.startedAtMs === undefined
? {}
: { startedAtMs: value.startedAtMs }),
...(value.finishedAtMs === undefined
? {}
: { finishedAtMs: value.finishedAtMs }),
});
}
export async function executeBoundedRunReadProjection(
runs: Pick<RunRepositoryReader, 'findRunById'>,
projectId: string,
runId: string,
): Promise<BoundedRunReadProjection> {
if (
!runs ||
typeof runs.findRunById !== 'function' ||
!boundedText(projectId, 128) ||
!boundedText(runId, 128)
) {
throw new TypeError('Bounded Run read projection input is invalid');
}
let run: RunRecord | null;
try {
run = await runs.findRunById(runId);
} catch {
throw new BoundedRunReadProjectionUnavailableError();
}
if (!run || run.projectId !== projectId) {
return Object.freeze({ found: false });
}
const projection = projectRun(run, projectId, runId);
if (!projection) throw new BoundedRunReadProjectionUnavailableError();
return projection;
}
@@ -0,0 +1,230 @@
import type { RunRecord } from '../run';
import type { RunRepositoryReader } from '../runRepository';
import {
normalizeListStepRunsResult,
type StepRunKind,
type StepRunRecord,
type StepRunRepository,
type StepRunStatus,
} from '../stepRun';
export const DEFAULT_BOUNDED_RUN_STEP_LIST_LIMIT = 32;
export const MAX_BOUNDED_RUN_STEP_LIST_LIMIT = 64;
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export interface BoundedRunStepListCursor {
readonly stepKey: string;
readonly stepRunId: string;
}
export interface BoundedRunStepListInput {
readonly after?: Readonly<BoundedRunStepListCursor>;
readonly limit?: number;
}
export interface BoundedRunStepListItem {
readonly id: string;
readonly parentStepRunId: string | null;
readonly stepKey: string;
readonly kind: StepRunKind;
readonly required: boolean;
readonly status: StepRunStatus;
readonly version: number;
readonly attemptCount: number;
readonly readyAtMs: number | null;
readonly startedAtMs: number | null;
readonly finishedAtMs: number | null;
readonly resultCode: string | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
}
export interface BoundedRunStepListProjection {
readonly found: boolean;
readonly steps: readonly Readonly<BoundedRunStepListItem>[];
readonly hasMore: boolean;
readonly next: Readonly<BoundedRunStepListCursor> | null;
}
export class InvalidBoundedRunStepListProjectionError extends TypeError {
readonly code = 'BOUNDED_RUN_STEP_LIST_PROJECTION_INVALID';
constructor() {
super('Bounded Run Step list projection input is invalid');
this.name = 'InvalidBoundedRunStepListProjectionError';
}
}
export class BoundedRunStepListProjectionUnavailableError extends Error {
readonly code = 'BOUNDED_RUN_STEP_LIST_PROJECTION_UNAVAILABLE';
constructor() {
super('Bounded Run Step list projection is unavailable');
this.name = 'BoundedRunStepListProjectionUnavailableError';
}
}
function boundedText(value: unknown, maximum: number): value is string {
return (
typeof value === 'string' &&
value.length > 0 &&
value.length <= maximum &&
!CONTROL_PATTERN.test(value)
);
}
function normalizeInput(value: Readonly<BoundedRunStepListInput>): Readonly<{
after?: Readonly<BoundedRunStepListCursor>;
limit: number;
}> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidBoundedRunStepListProjectionError();
}
const keys = Reflect.ownKeys(value);
if (
keys.length > 2 ||
keys.some((key) => key !== 'after' && key !== 'limit') ||
(value.limit !== undefined &&
(!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_BOUNDED_RUN_STEP_LIST_LIMIT))
) {
throw new InvalidBoundedRunStepListProjectionError();
}
let after: Readonly<BoundedRunStepListCursor> | undefined;
if (value.after !== undefined) {
if (
!value.after ||
typeof value.after !== 'object' ||
Array.isArray(value.after) ||
Reflect.ownKeys(value.after).length !== 2 ||
!Object.hasOwn(value.after, 'stepKey') ||
!Object.hasOwn(value.after, 'stepRunId') ||
!boundedText(value.after.stepKey, 128) ||
!boundedText(value.after.stepRunId, 128)
) {
throw new InvalidBoundedRunStepListProjectionError();
}
after = Object.freeze({
stepKey: value.after.stepKey,
stepRunId: value.after.stepRunId,
});
}
return Object.freeze({
...(after === undefined ? {} : { after }),
limit: value.limit ?? DEFAULT_BOUNDED_RUN_STEP_LIST_LIMIT,
});
}
function ownsRun(value: RunRecord, projectId: string, runId: string): boolean {
return (
!!value &&
typeof value === 'object' &&
!Array.isArray(value) &&
value.projectId === projectId &&
value.id === runId &&
boundedText(value.projectId, 128) &&
boundedText(value.id, 128)
);
}
function projectStep(
value: Readonly<StepRunRecord>,
): Readonly<BoundedRunStepListItem> {
return Object.freeze({
id: value.id,
parentStepRunId: value.parentStepRunId,
stepKey: value.stepKey,
kind: value.kind,
required: value.required,
status: value.status,
version: value.version,
attemptCount: value.attemptCount,
readyAtMs: value.readyAtMs,
startedAtMs: value.startedAtMs,
finishedAtMs: value.finishedAtMs,
resultCode: value.resultCode,
createdAtMs: value.createdAtMs,
updatedAtMs: value.updatedAtMs,
});
}
export async function executeBoundedRunStepListProjection(
runs: Pick<RunRepositoryReader, 'findRunById'>,
stepRuns: Pick<StepRunRepository, 'listByRun'>,
projectId: string,
runId: string,
input: Readonly<BoundedRunStepListInput>,
): Promise<Readonly<BoundedRunStepListProjection>> {
if (
!runs ||
typeof runs.findRunById !== 'function' ||
!stepRuns ||
typeof stepRuns.listByRun !== 'function' ||
!boundedText(projectId, 128) ||
!boundedText(runId, 128)
) {
throw new InvalidBoundedRunStepListProjectionError();
}
const normalized = normalizeInput(input);
let run: RunRecord | null;
try {
run = await runs.findRunById(runId);
} catch {
throw new BoundedRunStepListProjectionUnavailableError();
}
if (!run || !ownsRun(run, projectId, runId)) {
return Object.freeze({
found: false,
steps: Object.freeze([]),
hasMore: false,
next: null,
});
}
const query = Object.freeze({
runId,
limit: normalized.limit,
...(normalized.after === undefined
? {}
: {
after: Object.freeze({
stepKey: normalized.after.stepKey,
id: normalized.after.stepRunId,
}),
}),
});
try {
const page = normalizeListStepRunsResult(
await stepRuns.listByRun(query),
query,
);
const ids = new Set<string>();
const stepKeys = new Set<string>();
for (const step of page.stepRuns) {
if (ids.has(step.id) || stepKeys.has(step.stepKey)) {
throw new BoundedRunStepListProjectionUnavailableError();
}
ids.add(step.id);
stepKeys.add(step.stepKey);
}
return Object.freeze({
found: true,
steps: Object.freeze(page.stepRuns.map(projectStep)),
hasMore: page.truncated,
next:
page.next === undefined
? null
: Object.freeze({
stepKey: page.next.stepKey,
stepRunId: page.next.id,
}),
});
} catch (error) {
if (error instanceof BoundedRunStepListProjectionUnavailableError) {
throw error;
}
throw new BoundedRunStepListProjectionUnavailableError();
}
}
@@ -0,0 +1,87 @@
export class RunRepositoryError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly retryable = false,
public readonly cause?: unknown,
) {
super(message);
this.name = new.target.name;
}
}
export class DuplicateIdempotencyKeyError extends RunRepositoryError {
constructor(
public readonly projectId: string,
public readonly idempotencyKey: string,
) {
super(
'A Run with the same project idempotency key already exists',
'DUPLICATE_RUN_IDEMPOTENCY_KEY',
);
}
}
export class DuplicateRunAttemptError extends RunRepositoryError {
constructor(public readonly runId: string, public readonly attempt: number) {
super(
'A RunAttempt with the same run and attempt number already exists',
'DUPLICATE_RUN_ATTEMPT',
);
}
}
export class DuplicateRunEventError extends RunRepositoryError {
constructor(
public readonly runId: string,
public readonly dedupeKey?: string,
) {
super(
'A RunEvent with the same sequence or dedupe key already exists',
'DUPLICATE_RUN_EVENT',
);
}
}
export class RunRepositoryConstraintError extends RunRepositoryError {
constructor(
message = 'Run repository constraint violation',
cause?: unknown,
) {
super(message, 'RUN_REPOSITORY_CONSTRAINT', false, cause);
}
}
export class RunRepositoryBusyError extends RunRepositoryError {
constructor(cause?: unknown) {
super(
'Run repository is temporarily busy',
'RUN_REPOSITORY_BUSY',
true,
cause,
);
}
}
export class RunRepositoryOperationError extends RunRepositoryError {
constructor(cause?: unknown) {
super(
'Run repository operation failed',
'RUN_REPOSITORY_OPERATION_FAILED',
false,
cause,
);
}
}
export class RunEventPayloadTooLargeError extends RunRepositoryError {
constructor(
public readonly actualBytes: number,
public readonly maxBytes: number,
) {
super(
'RunEvent payload exceeds the configured size limit',
'RUN_EVENT_PAYLOAD_TOO_LARGE',
);
}
}
+150
View File
@@ -0,0 +1,150 @@
export const RUN_STATUSES = [
'created',
'queued',
'dispatching',
'running',
'waiting_approval',
'retry_wait',
'lost',
'succeeded',
'failed',
'cancelled',
'timed_out',
] as const;
export type RunStatus = (typeof RUN_STATUSES)[number];
export const RUN_ATTEMPT_STATUSES = [
'claimed',
'starting',
'running',
'succeeded',
'failed',
'cancelled',
'timed_out',
'lost',
] as const;
export type RunAttemptStatus = (typeof RUN_ATTEMPT_STATUSES)[number];
export const EXECUTION_ORIGINS = [
'manual',
'scheduled_system',
'scheduled_node',
'once',
'boot',
'grpc',
'subscription',
'system',
'script',
'legacy_import',
] as const;
export type ExecutionOrigin = (typeof EXECUTION_ORIGINS)[number];
export type ExecutionOwner = 'legacy' | 'runtime';
export const RUN_CANCELLATION_REASONS = [
'user',
'policy',
'shutdown',
'reconcile',
'timeout',
] as const;
export type RunCancellationReason = (typeof RUN_CANCELLATION_REASONS)[number];
export const RUN_EVENT_ACTOR_TYPES = [
'user',
'api_app',
'trigger',
'agent',
'mcp_client',
'worker',
'executor',
'system',
'legacy_shell',
'scheduler',
'reconciler',
'compatibility',
] as const;
export type RunEventActorType = (typeof RUN_EVENT_ACTOR_TYPES)[number];
export interface RunRecord {
id: string;
projectId: string;
taskId: string;
taskRevision: string;
taskName?: string;
taskSnapshotRef?: string;
legacyCronId?: number;
parentRunId?: string;
retryOfRunId?: string;
triggerId?: string;
triggerType: string;
executionOrigin: ExecutionOrigin;
executionOwner: ExecutionOwner;
triggeredBy?: string;
requestId?: string;
scheduledForMs?: number;
status: RunStatus;
version: number;
eventSequence: number;
priority: number;
idempotencyKey?: string;
inputRef?: string;
outputRef?: string;
createdAtMs: number;
queuedAtMs?: number;
startedAtMs?: number;
finishedAtMs?: number;
cancelRequestedAtMs?: number;
cancelReason?: RunCancellationReason;
errorCode?: string;
errorSummary?: string;
}
export interface RunAttemptRecord {
id: string;
runId: string;
stepRunId?: string;
attempt: number;
status: RunAttemptStatus;
executorType: string;
workerId?: string;
workerSessionId?: string;
workerGeneration?: number;
executorHandle?: string;
pid?: number;
logArtifactId?: string;
leaseToken?: string;
leaseTokenDigest?: string;
leaseGeneration?: number;
leaseVersion?: number;
leaseExpiresAtMs?: number;
offerId?: string;
deadlineAtMs?: number;
callbackTokenHash?: string;
callbackSequence: number;
createdAtMs: number;
startedAtMs?: number;
finishedAtMs?: number;
exitCode?: number;
errorCode?: string;
errorSummary?: string;
}
export interface RunEventRecord {
id: string;
runId: string;
sequence: number;
type: string;
dedupeKey?: string;
actorType: RunEventActorType;
actorId?: string;
attemptId?: string;
stepRunId?: string;
payload: Readonly<Record<string, unknown>>;
createdAtMs: number;
}
@@ -0,0 +1,240 @@
import { createHash } from 'node:crypto';
import {
assertWorkerId,
assertWorkerSessionId,
} from '../worker/workerSession';
export const RUN_DISPATCH_LEASE_STATUSES = [
'leased',
'released',
'completed',
] as const;
export type RunDispatchLeaseStatus =
(typeof RUN_DISPATCH_LEASE_STATUSES)[number];
export const RUN_DISPATCH_RELEASE_REASONS = [
'declined',
'shutdown',
'start_failed',
'capacity_changed',
'lease_expired',
] as const;
export type RunDispatchReleaseReason =
(typeof RUN_DISPATCH_RELEASE_REASONS)[number];
export const MIN_RUN_DISPATCH_LEASE_DURATION_MS = 5_000;
export const MAX_RUN_DISPATCH_LEASE_DURATION_MS = 10 * 60_000;
export interface RunDispatchLeaseRecord {
readonly attemptId: string;
readonly runId: string;
readonly status: RunDispatchLeaseStatus;
readonly version: number;
readonly leaseGeneration: number;
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
/** The database never persists or returns the bearer lease token. */
readonly leaseTokenDigest: string;
readonly acquiredAtMs: number;
readonly renewedAtMs: number;
readonly expiresAtMs: number;
readonly releasedAtMs?: number;
readonly releaseReason?: RunDispatchReleaseReason;
readonly completedAtMs?: number;
readonly updatedAtMs: number;
}
export class InvalidRunDispatchLeaseValueError extends TypeError {
constructor(message: string) {
super(`Run dispatch lease value is invalid: ${message}`);
this.name = 'InvalidRunDispatchLeaseValueError';
}
}
export type RunDispatchLeaseFenceReason =
| 'missing'
| 'run_mismatch'
| 'not_leased'
| 'worker_mismatch'
| 'worker_session_mismatch'
| 'worker_generation_mismatch'
| 'lease_generation_mismatch'
| 'lease_token_mismatch'
| 'version_mismatch'
| 'lease_expired'
| 'worker_unavailable';
export class RunDispatchLeaseFenceRejectedError extends Error {
constructor(
readonly attemptId: string,
readonly reason: RunDispatchLeaseFenceReason,
) {
super(`Run dispatch lease for Attempt ${attemptId} was fenced: ${reason}`);
this.name = 'RunDispatchLeaseFenceRejectedError';
}
}
function invalid(message: string): never {
throw new InvalidRunDispatchLeaseValueError(message);
}
export function assertRunDispatchId(name: string, value: string): void {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 128 ||
/[\u0000-\u001f\u007f]/.test(value)
) {
invalid(`${name} is invalid`);
}
}
export function assertRunDispatchLeaseToken(value: string): void {
if (
typeof value !== 'string' ||
value.length < 32 ||
value.length > 128 ||
!/^[A-Za-z0-9_-]+$/.test(value)
) {
invalid('leaseToken is invalid');
}
}
export function digestRunDispatchLeaseToken(value: string): string {
assertRunDispatchLeaseToken(value);
return createHash('sha256').update(value, 'utf8').digest('hex');
}
export function assertRunDispatchLeaseDuration(value: number): void {
if (
!Number.isSafeInteger(value) ||
value < MIN_RUN_DISPATCH_LEASE_DURATION_MS ||
value > MAX_RUN_DISPATCH_LEASE_DURATION_MS
) {
invalid(
`leaseDurationMs must be between ${MIN_RUN_DISPATCH_LEASE_DURATION_MS} and ${MAX_RUN_DISPATCH_LEASE_DURATION_MS}`,
);
}
}
export function assertRunDispatchLeaseFence(value: {
workerId: string;
workerSessionId: string;
workerGeneration: number;
leaseGeneration: number;
leaseToken: string;
expectedVersion: number;
}): void {
assertWorkerId(value.workerId);
assertWorkerSessionId(value.workerSessionId);
for (const [name, number, minimum] of [
['workerGeneration', value.workerGeneration, 1],
['leaseGeneration', value.leaseGeneration, 1],
['expectedVersion', value.expectedVersion, 0],
] as const) {
if (!Number.isSafeInteger(number) || number < minimum) invalid(`${name} is invalid`);
}
assertRunDispatchLeaseToken(value.leaseToken);
}
export function assertRunDispatchLeaseRecord(
value: RunDispatchLeaseRecord,
): void {
assertRunDispatchId('attemptId', value.attemptId);
assertRunDispatchId('runId', value.runId);
if (!RUN_DISPATCH_LEASE_STATUSES.includes(value.status)) invalid('status is invalid');
assertWorkerId(value.workerId);
assertWorkerSessionId(value.workerSessionId);
if (!/^[0-9a-f]{64}$/.test(value.leaseTokenDigest)) {
invalid('leaseTokenDigest is invalid');
}
for (const [name, number, minimum] of [
['version', value.version, 0],
['leaseGeneration', value.leaseGeneration, 1],
['workerGeneration', value.workerGeneration, 1],
['acquiredAtMs', value.acquiredAtMs, 0],
['renewedAtMs', value.renewedAtMs, 0],
['expiresAtMs', value.expiresAtMs, 0],
['updatedAtMs', value.updatedAtMs, 0],
] as const) {
if (!Number.isSafeInteger(number) || number < minimum) invalid(`${name} is invalid`);
}
if (
value.renewedAtMs < value.acquiredAtMs ||
value.expiresAtMs <= value.renewedAtMs ||
value.updatedAtMs < value.acquiredAtMs
) {
invalid('timestamps are inconsistent');
}
if (value.status === 'leased') {
if (
value.releasedAtMs !== undefined ||
value.releaseReason !== undefined ||
value.completedAtMs !== undefined
) invalid('active lease has terminal metadata');
return;
}
if (value.status === 'released') {
if (
value.releasedAtMs === undefined ||
value.releaseReason === undefined ||
!RUN_DISPATCH_RELEASE_REASONS.includes(value.releaseReason) ||
value.completedAtMs !== undefined
) invalid('released lease metadata is inconsistent');
return;
}
if (
value.completedAtMs === undefined ||
value.releasedAtMs !== undefined ||
value.releaseReason !== undefined
) invalid('completed lease metadata is inconsistent');
}
export interface ClaimRunDispatchLeaseCommand {
readonly runId: string;
readonly attemptId: string;
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly leaseToken: string;
readonly leaseDurationMs: number;
readonly eventId: string;
readonly offerId: string;
}
export type ClaimRunDispatchLeaseResult =
| { readonly status: 'claimed'; readonly lease: RunDispatchLeaseRecord }
| { readonly status: 'idempotent' | 'leased'; readonly lease: RunDispatchLeaseRecord }
| { readonly status: 'not_eligible' | 'worker_unavailable' | 'capacity_exhausted' };
export interface RenewRunDispatchLeaseCommand {
readonly attemptId: string;
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly leaseGeneration: number;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly leaseDurationMs: number;
}
export interface ReleaseRunDispatchLeaseCommand {
readonly runId: string;
readonly attemptId: string;
readonly workerId: string;
readonly workerSessionId: string;
readonly workerGeneration: number;
readonly leaseGeneration: number;
readonly leaseToken: string;
readonly expectedVersion: number;
readonly reason: Exclude<RunDispatchReleaseReason, 'lease_expired'>;
readonly eventId: string;
}
export interface RunDispatchLeaseRepository {
findByAttemptId(attemptId: string): Promise<RunDispatchLeaseRecord | null>;
claim(command: ClaimRunDispatchLeaseCommand): Promise<ClaimRunDispatchLeaseResult>;
renew(command: RenewRunDispatchLeaseCommand): Promise<RunDispatchLeaseRecord>;
release(command: ReleaseRunDispatchLeaseCommand): Promise<RunDispatchLeaseRecord>;
}
@@ -0,0 +1,59 @@
import type {
RunAttemptRecord,
RunAttemptStatus,
RunEventRecord,
RunRecord,
} from './run';
import type { RunRetryPolicyRecord } from './runRetryPolicy';
export const MAX_RUN_EVENT_PAYLOAD_BYTES = 16 * 1024;
export const MAX_RUN_EVENT_PAGE_SIZE = 500;
export const MAX_CANCELLATION_RECOVERY_PAGE_SIZE = 500;
export interface RunRepositoryReader {
findRunById(runId: string): Promise<RunRecord | null>;
findAttemptById(attemptId: string): Promise<RunAttemptRecord | null>;
findLatestAttemptByRunId(runId: string): Promise<RunAttemptRecord | null>;
findRetryPolicyByRunId(runId: string): Promise<RunRetryPolicyRecord | null>;
listEvents(
runId: string,
options?: { afterSequence?: number; limit?: number },
): Promise<RunEventRecord[]>;
listCancellationRequested(options?: {
beforeMs?: number;
limit?: number;
}): Promise<RunRecord[]>;
}
export interface RunRepositoryTransaction extends RunRepositoryReader {
insertRun(run: RunRecord): Promise<void>;
insertAttempt(attempt: RunAttemptRecord): Promise<void>;
insertRetryPolicy(policy: RunRetryPolicyRecord): Promise<void>;
/**
* Replaces a Run only when its persisted version still equals
* `expectedVersion`. The supplied Run must carry `expectedVersion + 1`.
*/
compareAndSetRun(run: RunRecord, expectedVersion: number): Promise<boolean>;
/**
* Replaces an Attempt only when both state and callback sequence still match.
* The Run aggregate version remains the primary serialization boundary.
*/
compareAndSetAttempt(
attempt: RunAttemptRecord,
expected: {
status: RunAttemptStatus;
callbackSequence: number;
},
): Promise<boolean>;
compareAndSetRetryPolicy(
policy: RunRetryPolicyRecord,
expectedVersion: number,
): Promise<boolean>;
appendEvent(event: RunEventRecord): Promise<void>;
}
export interface RunRepository extends RunRepositoryReader {
transaction<T>(
work: (transaction: RunRepositoryTransaction) => Promise<T>,
): Promise<T>;
}
@@ -0,0 +1,6 @@
export * from './repositoryErrors';
export * from './run';
export * from './runRepository';
export * from './projectRunList';
export * from './runRetryPolicy';
export * from './clusterRunLostRetry';
@@ -0,0 +1,138 @@
export const RUN_RETRY_SAFETIES = [
'unknown',
'idempotent',
'deduplicated',
] as const;
export type RunRetrySafety = (typeof RUN_RETRY_SAFETIES)[number];
export const MAX_RUN_ATTEMPTS = 16;
export const MAX_RUN_RETRY_BACKOFF_MS = 24 * 60 * 60 * 1000;
export interface RunRetryPolicyDefinition {
maxAttempts: number;
retryOnLost: boolean;
safety: RunRetrySafety;
backoffBaseMs: number;
backoffMaxMs: number;
}
export interface RunRetryPolicyRecord extends RunRetryPolicyDefinition {
runId: string;
nextAttemptAtMs?: number;
version: number;
createdAtMs: number;
updatedAtMs: number;
}
export const NO_AUTOMATIC_RUN_RETRY: Readonly<RunRetryPolicyDefinition> = {
maxAttempts: 1,
retryOnLost: false,
safety: 'unknown',
backoffBaseMs: 0,
backoffMaxMs: 0,
};
export class InvalidRunRetryPolicyError extends TypeError {
readonly code = 'INVALID_RUN_RETRY_POLICY';
constructor(message: string) {
super(message);
this.name = 'InvalidRunRetryPolicyError';
}
}
function assertNonNegativeTime(name: string, value: number): void {
if (!Number.isSafeInteger(value) || value < 0) {
throw new InvalidRunRetryPolicyError(
`${name} must be a non-negative safe integer`,
);
}
}
export function assertRunRetryPolicyDefinition(
policy: RunRetryPolicyDefinition,
): void {
if (
!Number.isSafeInteger(policy.maxAttempts) ||
policy.maxAttempts < 1 ||
policy.maxAttempts > MAX_RUN_ATTEMPTS
) {
throw new InvalidRunRetryPolicyError(
`maxAttempts must be between 1 and ${MAX_RUN_ATTEMPTS}`,
);
}
if (typeof policy.retryOnLost !== 'boolean') {
throw new InvalidRunRetryPolicyError('retryOnLost must be boolean');
}
if (!RUN_RETRY_SAFETIES.includes(policy.safety)) {
throw new InvalidRunRetryPolicyError('safety is not supported');
}
assertNonNegativeTime('backoffBaseMs', policy.backoffBaseMs);
assertNonNegativeTime('backoffMaxMs', policy.backoffMaxMs);
if (
policy.backoffBaseMs > MAX_RUN_RETRY_BACKOFF_MS ||
policy.backoffMaxMs > MAX_RUN_RETRY_BACKOFF_MS
) {
throw new InvalidRunRetryPolicyError(
`retry backoff cannot exceed ${MAX_RUN_RETRY_BACKOFF_MS}ms`,
);
}
if (policy.backoffMaxMs < policy.backoffBaseMs) {
throw new InvalidRunRetryPolicyError(
'backoffMaxMs cannot be smaller than backoffBaseMs',
);
}
}
export function assertAdmittedRunRetryPolicy(
policy: RunRetryPolicyDefinition,
): void {
assertRunRetryPolicyDefinition(policy);
if (
policy.retryOnLost &&
policy.maxAttempts > 1 &&
policy.safety === 'unknown'
) {
throw new InvalidRunRetryPolicyError(
'automatic lost retry requires idempotent or deduplicated safety',
);
}
}
export function assertRunRetryPolicyRecord(policy: RunRetryPolicyRecord): void {
assertRunRetryPolicyDefinition(policy);
if (!policy.runId) {
throw new InvalidRunRetryPolicyError('runId is required');
}
if (!Number.isSafeInteger(policy.version) || policy.version < 0) {
throw new InvalidRunRetryPolicyError(
'version must be a non-negative safe integer',
);
}
assertNonNegativeTime('createdAtMs', policy.createdAtMs);
assertNonNegativeTime('updatedAtMs', policy.updatedAtMs);
if (policy.updatedAtMs < policy.createdAtMs) {
throw new InvalidRunRetryPolicyError(
'updatedAtMs cannot be earlier than createdAtMs',
);
}
if (policy.nextAttemptAtMs !== undefined) {
assertNonNegativeTime('nextAttemptAtMs', policy.nextAttemptAtMs);
}
}
export function runRetryDelayMs(
policy: RunRetryPolicyDefinition,
lostAttempt: number,
): number {
assertRunRetryPolicyDefinition(policy);
if (!Number.isSafeInteger(lostAttempt) || lostAttempt < 1) {
throw new InvalidRunRetryPolicyError(
'lostAttempt must be a positive safe integer',
);
}
if (policy.backoffBaseMs === 0) return 0;
const exponent = Math.min(lostAttempt - 1, MAX_RUN_ATTEMPTS - 1);
return Math.min(policy.backoffMaxMs, policy.backoffBaseMs * 2 ** exponent);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,316 @@
import {
normalizeLocalScheduleCandidate,
resolveLocalScheduleDecision,
type LocalCronNextOccurrence,
type LocalScheduleCandidate,
type LocalScheduleDecision,
} from './localScheduler';
export const MAX_CLUSTER_SCHEDULE_CLAIM_LEASE_MS = 60_000;
export const MIN_CLUSTER_SCHEDULE_CLAIM_LEASE_MS = 1_000;
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const OWNER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export interface ClusterScheduleClaim extends LocalScheduleCandidate {
readonly claimOwner: string;
readonly claimToken: string;
readonly claimVersion: number;
readonly claimAcquiredAtMs: number;
readonly claimExpiresAtMs: number;
}
export interface ClaimClusterScheduleCommand {
readonly ownerId: string;
readonly claimToken: string;
readonly leaseMs: number;
}
export interface CommitClusterScheduleDecisionCommand {
readonly claim: ClusterScheduleClaim;
readonly decision: LocalScheduleDecision;
readonly runId?: string;
readonly attemptId?: string;
readonly createdEventId?: string;
readonly queuedEventId?: string;
}
export type CommitClusterScheduleDecisionResult = Readonly<
| { status: 'advanced'; disposition: 'initialize' | 'skip' }
| {
status: 'admitted';
disposition: 'admit';
runId: string;
attemptId: string;
}
| { status: 'raced' }
>;
export interface ClusterScheduleStore {
claimNextClusterSchedule(
command: ClaimClusterScheduleCommand,
): Promise<ClusterScheduleClaim | null>;
commitClusterScheduleDecision(
command: CommitClusterScheduleDecisionCommand,
): Promise<CommitClusterScheduleDecisionResult>;
}
export class InvalidClusterScheduleError extends TypeError {
readonly code = 'CLUSTER_SCHEDULE_INVALID';
constructor(message: string) {
super(`Cluster schedule is invalid: ${message}`);
this.name = 'InvalidClusterScheduleError';
}
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidClusterScheduleError(`${label} is invalid`);
}
return value as number;
}
export function normalizeClusterScheduleClaim(
value: ClusterScheduleClaim,
): ClusterScheduleClaim {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterScheduleError('claim shape is invalid');
}
const candidate = normalizeLocalScheduleCandidate({
projectId: value.projectId,
triggerId: value.triggerId,
triggerRevision: value.triggerRevision,
triggerContentDigest: value.triggerContentDigest,
triggerUpdatedAtMs: value.triggerUpdatedAtMs,
taskId: value.taskId,
taskRevision: value.taskRevision,
taskContentDigest: value.taskContentDigest,
expression: value.expression,
timezone: value.timezone,
misfirePolicy: value.misfirePolicy,
stateVersion: value.stateVersion,
nextFireAtMs: value.nextFireAtMs,
});
const expectedKeys = new Set([
...Object.keys(candidate),
'claimAcquiredAtMs',
'claimExpiresAtMs',
'claimOwner',
'claimToken',
'claimVersion',
]);
if (
Object.keys(value).some((key) => !expectedKeys.has(key)) ||
typeof value.claimOwner !== 'string' ||
!OWNER_PATTERN.test(value.claimOwner) ||
typeof value.claimToken !== 'string' ||
!UUID_PATTERN.test(value.claimToken) ||
!Number.isSafeInteger(value.claimVersion) ||
value.claimVersion < 1 ||
value.claimVersion > 2_147_483_647
) {
throw new InvalidClusterScheduleError('claim fence is invalid');
}
const claimExpiresAtMs = timestamp(
value.claimExpiresAtMs,
'claimExpiresAtMs',
);
const claimAcquiredAtMs = timestamp(
value.claimAcquiredAtMs,
'claimAcquiredAtMs',
);
const leaseMs = claimExpiresAtMs - claimAcquiredAtMs;
if (
claimAcquiredAtMs < value.triggerUpdatedAtMs ||
!Number.isSafeInteger(leaseMs) ||
leaseMs < MIN_CLUSTER_SCHEDULE_CLAIM_LEASE_MS ||
leaseMs > MAX_CLUSTER_SCHEDULE_CLAIM_LEASE_MS
) {
throw new InvalidClusterScheduleError('claim expiry is invalid');
}
return Object.freeze({
...candidate,
claimOwner: value.claimOwner,
claimToken: value.claimToken,
claimVersion: value.claimVersion,
claimAcquiredAtMs,
claimExpiresAtMs,
});
}
export function normalizeClaimClusterScheduleCommand(
value: ClaimClusterScheduleCommand,
): ClaimClusterScheduleCommand {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).sort().join(',') !== 'claimToken,leaseMs,ownerId' ||
!OWNER_PATTERN.test(value.ownerId) ||
!UUID_PATTERN.test(value.claimToken) ||
!Number.isSafeInteger(value.leaseMs) ||
value.leaseMs < MIN_CLUSTER_SCHEDULE_CLAIM_LEASE_MS ||
value.leaseMs > MAX_CLUSTER_SCHEDULE_CLAIM_LEASE_MS
) {
throw new InvalidClusterScheduleError('claim command is invalid');
}
return Object.freeze({
ownerId: value.ownerId,
claimToken: value.claimToken,
leaseMs: value.leaseMs,
});
}
function uuid(value: unknown, label: string): string {
if (typeof value !== 'string' || !UUID_PATTERN.test(value)) {
throw new InvalidClusterScheduleError(`${label} is invalid`);
}
return value;
}
export function normalizeCommitClusterScheduleDecisionCommand(
value: CommitClusterScheduleDecisionCommand,
): CommitClusterScheduleDecisionCommand {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidClusterScheduleError('commit command shape is invalid');
}
const allowed = new Set([
'attemptId',
'claim',
'createdEventId',
'decision',
'queuedEventId',
'runId',
]);
const keys = Object.keys(value);
if (
!keys.includes('claim') ||
!keys.includes('decision') ||
keys.some((key) => !allowed.has(key))
) {
throw new InvalidClusterScheduleError('commit command shape is invalid');
}
const claim = normalizeClusterScheduleClaim(value.claim);
const decision = value.decision;
if (!decision || typeof decision !== 'object' || Array.isArray(decision)) {
throw new InvalidClusterScheduleError('decision shape is invalid');
}
const admitted = decision.disposition === 'admit';
const decisionKeys = Object.keys(decision).sort().join(',');
if (
(admitted &&
decisionKeys !==
'candidate,disposition,nextFireAtMs,observedAtMs,scheduledForMs') ||
(!admitted &&
decisionKeys !== 'candidate,disposition,nextFireAtMs,observedAtMs') ||
(!admitted &&
decision.disposition !== 'initialize' &&
decision.disposition !== 'skip')
) {
throw new InvalidClusterScheduleError('decision shape is invalid');
}
const candidate = normalizeLocalScheduleCandidate(decision.candidate);
const observedAtMs = timestamp(
decision.observedAtMs,
'decision.observedAtMs',
);
const nextFireAtMs = timestamp(
decision.nextFireAtMs,
'decision.nextFireAtMs',
);
if (
JSON.stringify(candidate) !==
JSON.stringify({
projectId: claim.projectId,
triggerId: claim.triggerId,
triggerRevision: claim.triggerRevision,
triggerContentDigest: claim.triggerContentDigest,
triggerUpdatedAtMs: claim.triggerUpdatedAtMs,
taskId: claim.taskId,
taskRevision: claim.taskRevision,
taskContentDigest: claim.taskContentDigest,
expression: claim.expression,
timezone: claim.timezone,
misfirePolicy: claim.misfirePolicy,
stateVersion: claim.stateVersion,
nextFireAtMs: claim.nextFireAtMs,
}) ||
observedAtMs !== claim.claimAcquiredAtMs ||
nextFireAtMs <= observedAtMs ||
(decision.disposition === 'initialize' && candidate.nextFireAtMs !== null)
) {
throw new InvalidClusterScheduleError('decision fence is invalid');
}
if (admitted) {
const scheduledForMs = timestamp(
decision.scheduledForMs,
'decision.scheduledForMs',
);
if (scheduledForMs > observedAtMs) {
throw new InvalidClusterScheduleError('scheduled occurrence is invalid');
}
return Object.freeze({
claim,
decision: Object.freeze({
candidate,
observedAtMs,
nextFireAtMs,
scheduledForMs,
disposition: 'admit' as const,
}),
runId: uuid(value.runId, 'runId'),
attemptId: uuid(value.attemptId, 'attemptId'),
createdEventId: uuid(value.createdEventId, 'createdEventId'),
queuedEventId: uuid(value.queuedEventId, 'queuedEventId'),
});
}
if (
value.runId !== undefined ||
value.attemptId !== undefined ||
value.createdEventId !== undefined ||
value.queuedEventId !== undefined
) {
throw new InvalidClusterScheduleError(
'non-admission decision carries identities',
);
}
return Object.freeze({
claim,
decision: Object.freeze({
candidate,
observedAtMs,
nextFireAtMs,
disposition: decision.disposition,
}),
});
}
export function resolveClusterScheduleDecision(
claim: ClusterScheduleClaim,
misfireGraceMs: number,
nextOccurrence: LocalCronNextOccurrence,
): LocalScheduleDecision {
const normalized = normalizeClusterScheduleClaim(claim);
return resolveLocalScheduleDecision(
{
projectId: normalized.projectId,
triggerId: normalized.triggerId,
triggerRevision: normalized.triggerRevision,
triggerContentDigest: normalized.triggerContentDigest,
triggerUpdatedAtMs: normalized.triggerUpdatedAtMs,
taskId: normalized.taskId,
taskRevision: normalized.taskRevision,
taskContentDigest: normalized.taskContentDigest,
expression: normalized.expression,
timezone: normalized.timezone,
misfirePolicy: normalized.misfirePolicy,
stateVersion: normalized.stateVersion,
nextFireAtMs: normalized.nextFireAtMs,
},
normalized.claimAcquiredAtMs,
misfireGraceMs,
nextOccurrence,
);
}
@@ -0,0 +1,278 @@
export const MAX_LOCAL_SCHEDULE_PAGE_SIZE = 256;
export const MAX_LOCAL_SCHEDULE_MISFIRE_GRACE_MS = 5 * 60_000;
export type LocalCronMisfirePolicy = 'skip' | 'fire_once';
export interface LocalCronSchedule {
readonly expression: string;
readonly timezone: string;
}
export type LocalCronNextOccurrence = (
schedule: LocalCronSchedule,
afterMs: number,
) => number;
export interface LocalScheduleCandidate {
readonly projectId: string;
readonly triggerId: string;
readonly triggerRevision: number;
readonly triggerContentDigest: string;
readonly triggerUpdatedAtMs: number;
readonly taskId: string;
readonly taskRevision: number;
readonly taskContentDigest: string;
readonly expression: string;
readonly timezone: string;
readonly misfirePolicy: LocalCronMisfirePolicy;
readonly stateVersion: number;
readonly nextFireAtMs: number | null;
}
export interface LocalScheduleDecision {
readonly candidate: LocalScheduleCandidate;
readonly observedAtMs: number;
readonly nextFireAtMs: number;
readonly scheduledForMs?: number;
readonly disposition: 'initialize' | 'skip' | 'admit';
}
export interface LocalScheduleCandidatePage {
readonly candidates: readonly LocalScheduleCandidate[];
readonly truncated: boolean;
}
export interface CommitLocalScheduleDecisionCommand {
readonly decision: LocalScheduleDecision;
readonly runId?: string;
readonly attemptId?: string;
readonly createdEventId?: string;
readonly queuedEventId?: string;
}
export type CommitLocalScheduleDecisionResult = Readonly<
| { status: 'advanced'; disposition: 'initialize' | 'skip' }
| {
status: 'admitted';
disposition: 'admit';
runId: string;
attemptId: string;
}
| { status: 'raced' }
>;
export interface LocalScheduleStore {
listLocalScheduleCandidates(options: {
readonly observedAtMs: number;
readonly limit: number;
}): Promise<LocalScheduleCandidatePage>;
commitLocalScheduleDecision(
command: CommitLocalScheduleDecisionCommand,
): Promise<CommitLocalScheduleDecisionResult>;
}
export class InvalidLocalScheduleError extends TypeError {
readonly code = 'LOCAL_SCHEDULE_INVALID';
constructor(message: string) {
super(`Local schedule is invalid: ${message}`);
this.name = 'InvalidLocalScheduleError';
}
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidLocalScheduleError(`${label} is invalid`);
}
return value as number;
}
function positiveRevision(value: unknown, label: string): number {
const result = timestamp(value, label);
if (result < 1 || result > 2_147_483_647) {
throw new InvalidLocalScheduleError(`${label} is invalid`);
}
return result;
}
function text(value: unknown, label: string, maximumBytes = 128): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new InvalidLocalScheduleError(`${label} is invalid`);
}
return value;
}
export function assertLocalSchedulePageSize(limit: number): void {
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > MAX_LOCAL_SCHEDULE_PAGE_SIZE
) {
throw new RangeError(
`Local schedule page size must be between 1 and ${MAX_LOCAL_SCHEDULE_PAGE_SIZE}`,
);
}
}
export function normalizeLocalScheduleCandidate(
value: LocalScheduleCandidate,
): LocalScheduleCandidate {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).sort().join(',') !==
'expression,misfirePolicy,nextFireAtMs,projectId,stateVersion,taskContentDigest,taskId,taskRevision,timezone,triggerContentDigest,triggerId,triggerRevision,triggerUpdatedAtMs'
) {
throw new InvalidLocalScheduleError('candidate shape is invalid');
}
const triggerContentDigest = text(
value.triggerContentDigest,
'triggerContentDigest',
64,
);
const taskContentDigest = text(
value.taskContentDigest,
'taskContentDigest',
64,
);
if (
!/^[0-9a-f]{64}$/.test(triggerContentDigest) ||
!/^[0-9a-f]{64}$/.test(taskContentDigest) ||
(value.misfirePolicy !== 'skip' && value.misfirePolicy !== 'fire_once') ||
(value.nextFireAtMs !== null &&
(!Number.isSafeInteger(value.nextFireAtMs) || value.nextFireAtMs < 0))
) {
throw new InvalidLocalScheduleError('candidate content is invalid');
}
return Object.freeze({
projectId: text(value.projectId, 'projectId'),
triggerId: text(value.triggerId, 'triggerId'),
triggerRevision: positiveRevision(value.triggerRevision, 'triggerRevision'),
triggerContentDigest,
triggerUpdatedAtMs: timestamp(
value.triggerUpdatedAtMs,
'triggerUpdatedAtMs',
),
taskId: text(value.taskId, 'taskId'),
taskRevision: positiveRevision(value.taskRevision, 'taskRevision'),
taskContentDigest,
expression: text(value.expression, 'expression', 768),
timezone: text(value.timezone, 'timezone'),
misfirePolicy: value.misfirePolicy,
stateVersion: timestamp(value.stateVersion, 'stateVersion'),
nextFireAtMs: value.nextFireAtMs === null ? null : value.nextFireAtMs,
});
}
function cronNext(
candidate: LocalScheduleCandidate,
afterMs: number,
nextOccurrence: LocalCronNextOccurrence,
): number {
try {
if (
candidate.expression.startsWith('@') ||
typeof nextOccurrence !== 'function'
) {
throw new Error('cron provider is invalid');
}
const value = timestamp(
nextOccurrence(
Object.freeze({
expression: candidate.expression,
timezone: candidate.timezone,
}),
afterMs,
),
'next cron occurrence',
);
if (value <= afterMs) {
throw new Error('cron provider did not advance time');
}
return value;
} catch {
throw new InvalidLocalScheduleError('cron calculation failed');
}
}
export function initialLocalCronNextFireAt(
candidate: Pick<
LocalScheduleCandidate,
'expression' | 'timezone' | 'triggerUpdatedAtMs'
>,
nextOccurrence: LocalCronNextOccurrence,
): number {
const normalized = normalizeLocalScheduleCandidate({
projectId: '_',
triggerId: '_',
triggerRevision: 1,
triggerContentDigest: '0'.repeat(64),
triggerUpdatedAtMs: candidate.triggerUpdatedAtMs,
taskId: '_',
taskRevision: 1,
taskContentDigest: '0'.repeat(64),
expression: candidate.expression,
timezone: candidate.timezone,
misfirePolicy: 'skip',
stateVersion: 0,
nextFireAtMs: null,
});
return cronNext(
normalized,
Math.max(0, normalized.triggerUpdatedAtMs - 1),
nextOccurrence,
);
}
export function resolveLocalScheduleDecision(
value: LocalScheduleCandidate,
observedAtMs: number,
misfireGraceMs: number,
nextOccurrence: LocalCronNextOccurrence,
): LocalScheduleDecision {
const candidate = normalizeLocalScheduleCandidate(value);
const observed = timestamp(observedAtMs, 'observedAtMs');
if (
!Number.isSafeInteger(misfireGraceMs) ||
misfireGraceMs < 0 ||
misfireGraceMs > MAX_LOCAL_SCHEDULE_MISFIRE_GRACE_MS
) {
throw new RangeError(
`Local schedule misfire grace must be between 0 and ${MAX_LOCAL_SCHEDULE_MISFIRE_GRACE_MS}`,
);
}
const dueAtMs =
candidate.nextFireAtMs ??
initialLocalCronNextFireAt(candidate, nextOccurrence);
if (dueAtMs > observed) {
return Object.freeze({
candidate,
observedAtMs: observed,
nextFireAtMs: dueAtMs,
disposition: 'initialize' as const,
});
}
const late = observed - dueAtMs > misfireGraceMs;
if (late && candidate.misfirePolicy === 'skip') {
return Object.freeze({
candidate,
observedAtMs: observed,
nextFireAtMs: cronNext(candidate, observed, nextOccurrence),
disposition: 'skip' as const,
});
}
const scheduledForMs = dueAtMs;
return Object.freeze({
candidate,
observedAtMs: observed,
scheduledForMs,
nextFireAtMs: cronNext(candidate, observed, nextOccurrence),
disposition: 'admit' as const,
});
}
@@ -0,0 +1,691 @@
import { createHash } from 'node:crypto';
export const BUILT_IN_CRON_TRIGGER_SPEC_SCHEMA = 'qinglong/cron@v1';
export const MAX_TRIGGER_PAGE_SIZE = 256;
export const MAX_TRIGGER_SPEC_BYTES = 16 * 1024;
export const MAX_TRIGGER_SPEC_SEMANTIC_SCHEMAS = 32;
const TRIGGER_SPEC_SCHEMA_PATTERN =
/^[a-z][a-z0-9.-]{0,63}\/[a-z][a-z0-9.-]{0,63}@v[1-9][0-9]{0,5}$/;
const MUTATION_ID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const CRON_FIELD_PATTERN = /^[0-9A-Za-z*?,/#LW-]+$/;
export type TriggerSpecJson =
| null
| boolean
| number
| string
| readonly TriggerSpecJson[]
| Readonly<{ [key: string]: TriggerSpecJson }>;
export interface TriggerSpec {
readonly schema: string;
readonly config: Readonly<{ [key: string]: TriggerSpecJson }>;
}
export interface TriggerRecord {
readonly projectId: string;
readonly triggerId: string;
readonly revision: number;
readonly mutationId: string;
readonly taskId: string;
readonly taskRevision: number;
readonly taskContentDigest: string;
readonly spec: TriggerSpec;
readonly enabled: boolean;
readonly contentDigest: string;
readonly createdAtMs: number;
readonly updatedAtMs: number;
}
export interface AppendTriggerRevisionCommand {
readonly projectId: string;
readonly triggerId: string;
readonly expectedRevision: number | null;
readonly mutationId: string;
readonly taskId: string;
readonly taskRevision: number;
readonly taskContentDigest: string;
readonly spec: TriggerSpec;
readonly enabled: boolean;
readonly occurredAtMs: number;
}
export interface TriggerCursor {
readonly triggerId: string;
}
export interface TriggerPage {
readonly triggers: readonly TriggerRecord[];
readonly truncated: boolean;
readonly next?: TriggerCursor;
}
export interface TriggerSource {
findCurrentTrigger(
projectId: string,
triggerId: string,
): Promise<TriggerRecord | null>;
findTriggerRevision(
projectId: string,
triggerId: string,
revision: number,
): Promise<TriggerRecord | null>;
listTriggers(options: {
readonly projectId: string;
readonly limit: number;
readonly after?: TriggerCursor;
}): Promise<TriggerPage>;
}
export interface TriggerRepository extends TriggerSource {
appendTriggerRevision(command: AppendTriggerRevisionCommand): Promise<
Readonly<{
status: 'created' | 'updated' | 'existing';
trigger: TriggerRecord;
}>
>;
}
export interface TriggerSpecSemanticDescriptor {
readonly schema: string;
normalizeConfig(
config: Readonly<Record<string, TriggerSpecJson>>,
context: Readonly<{
projectId: string;
triggerId: string;
taskId: string;
taskRevision: number;
}>,
): Readonly<Record<string, TriggerSpecJson>>;
}
export interface TriggerSpecSemanticMetadata {
readonly schema: string;
}
export class InvalidTriggerError extends TypeError {
readonly code = 'TRIGGER_INVALID';
constructor(message: string) {
super(`Trigger is invalid: ${message}`);
this.name = 'InvalidTriggerError';
}
}
export class UnsupportedTriggerSpecError extends Error {
readonly code = 'TRIGGER_SPEC_UNSUPPORTED';
constructor() {
super('Trigger spec schema is unsupported');
this.name = 'UnsupportedTriggerSpecError';
}
}
export class InvalidTriggerSpecSemanticError extends TypeError {
readonly code = 'TRIGGER_SPEC_SEMANTIC_INVALID';
constructor(message: string) {
super(`Trigger spec semantics are invalid: ${message}`);
this.name = 'InvalidTriggerSpecSemanticError';
}
}
export class TriggerConflictError extends Error {
readonly code = 'TRIGGER_CONFLICT';
constructor() {
super('Trigger mutation conflicts with durable state');
this.name = 'TriggerConflictError';
}
}
export class TriggerUnavailableError extends Error {
readonly code = 'TRIGGER_UNAVAILABLE';
constructor() {
super('Trigger storage is unavailable');
this.name = 'TriggerUnavailableError';
}
}
function exactKeys(
value: unknown,
required: readonly string[],
optional: readonly string[],
label: string,
ErrorType: typeof InvalidTriggerError | typeof InvalidTriggerSpecSemanticError =
InvalidTriggerError,
): asserts value is Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new ErrorType(`${label} must be an object`);
}
const keys = Object.keys(value);
const allowed = new Set([...required, ...optional]);
if (
required.some((key) => !keys.includes(key)) ||
keys.some((key) => !allowed.has(key))
) {
throw new ErrorType(`${label} has an invalid shape`);
}
}
function boundedText(
value: unknown,
label: string,
maximumBytes: number,
): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
/[\u0001-\u001f\u007f]/.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new InvalidTriggerError(`${label} is invalid`);
}
return value;
}
function identifier(value: unknown, label: string): string {
return boundedText(value, label, 128);
}
function revision(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > 2_147_483_647
) {
throw new InvalidTriggerError(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidTriggerError(`${label} is invalid`);
}
return value as number;
}
function normalizeJson(
value: unknown,
budget: { nodes: number },
depth: number,
): TriggerSpecJson {
budget.nodes += 1;
if (budget.nodes > 512 || depth > 8) {
throw new InvalidTriggerError('spec exceeds its structure budget');
}
if (value === null || typeof value === 'boolean') return value;
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
throw new InvalidTriggerError('spec contains an invalid number');
}
return Object.is(value, -0) ? 0 : value;
}
if (typeof value === 'string') {
if (value.includes('\0') || Buffer.byteLength(value, 'utf8') > 4096) {
throw new InvalidTriggerError('spec contains invalid text');
}
return value;
}
if (Array.isArray(value)) {
if (value.length > 128) {
throw new InvalidTriggerError('spec array is too large');
}
return Object.freeze(
value.map((entry) => normalizeJson(entry, budget, depth + 1)),
);
}
if (!value || typeof value !== 'object') {
throw new InvalidTriggerError('spec contains a non-JSON value');
}
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
throw new InvalidTriggerError('spec object prototype is invalid');
}
const keys = Object.keys(value).sort();
if (keys.length > 128) {
throw new InvalidTriggerError('spec object is too large');
}
const normalized = Object.create(null) as Record<string, TriggerSpecJson>;
for (const key of keys) {
boundedText(key, 'spec key', 128);
normalized[key] = normalizeJson(
(value as Record<string, unknown>)[key],
budget,
depth + 1,
);
}
return Object.freeze(normalized);
}
export function assertTriggerIdentifier(
value: unknown,
label = 'identifier',
): asserts value is string {
identifier(value, label);
}
export function assertTriggerRevision(
value: unknown,
label = 'revision',
): asserts value is number {
revision(value, label);
}
export function normalizeTriggerSpec(value: TriggerSpec): TriggerSpec {
exactKeys(value, ['config', 'schema'], [], 'spec');
if (
typeof value.schema !== 'string' ||
!TRIGGER_SPEC_SCHEMA_PATTERN.test(value.schema)
) {
throw new InvalidTriggerError('spec schema is invalid');
}
const config = normalizeJson(value.config, { nodes: 0 }, 0);
if (!config || typeof config !== 'object' || Array.isArray(config)) {
throw new InvalidTriggerError('spec config must be an object');
}
const normalized = Object.freeze({
schema: value.schema,
config: config as Readonly<Record<string, TriggerSpecJson>>,
});
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_TRIGGER_SPEC_BYTES
) {
throw new InvalidTriggerError('spec exceeds its byte budget');
}
return normalized;
}
function normalizeCronConfig(
value: Readonly<Record<string, TriggerSpecJson>>,
): Readonly<Record<string, TriggerSpecJson>> {
exactKeys(
value,
['expression', 'misfirePolicy', 'timezone'],
[],
'cron config',
InvalidTriggerSpecSemanticError,
);
if (typeof value.expression !== 'string') {
throw new InvalidTriggerSpecSemanticError('cron expression is invalid');
}
const fields = value.expression.trim().split(/\s+/u);
if (
(fields.length !== 5 && fields.length !== 6) ||
fields.some(
(field) =>
field.length < 1 ||
Buffer.byteLength(field, 'utf8') > 128 ||
!CRON_FIELD_PATTERN.test(field),
)
) {
throw new InvalidTriggerSpecSemanticError(
'cron expression must contain five or six bounded fields',
);
}
if (
typeof value.timezone !== 'string' ||
value.timezone.length < 1 ||
Buffer.byteLength(value.timezone, 'utf8') > 128
) {
throw new InvalidTriggerSpecSemanticError('timezone is invalid');
}
let timezone: string;
try {
timezone = new Intl.DateTimeFormat('en-US', {
timeZone: value.timezone,
}).resolvedOptions().timeZone;
} catch {
throw new InvalidTriggerSpecSemanticError('timezone is unsupported');
}
if (value.misfirePolicy !== 'skip' && value.misfirePolicy !== 'fire_once') {
throw new InvalidTriggerSpecSemanticError('misfirePolicy is invalid');
}
return Object.freeze({
expression: fields.join(' '),
timezone,
misfirePolicy: value.misfirePolicy,
});
}
const BUILT_IN_DESCRIPTORS: readonly TriggerSpecSemanticDescriptor[] =
Object.freeze([
Object.freeze({
schema: BUILT_IN_CRON_TRIGGER_SPEC_SCHEMA,
normalizeConfig: normalizeCronConfig,
}),
]);
export class TriggerSpecSemanticRegistry {
readonly #descriptors: ReadonlyMap<string, TriggerSpecSemanticDescriptor>;
readonly #metadata: readonly TriggerSpecSemanticMetadata[];
constructor(descriptors: readonly TriggerSpecSemanticDescriptor[]) {
if (
!Array.isArray(descriptors) ||
descriptors.length < 1 ||
descriptors.length > MAX_TRIGGER_SPEC_SEMANTIC_SCHEMAS
) {
throw new InvalidTriggerSpecSemanticError(
'registry descriptor count is invalid',
);
}
const bySchema = new Map<string, TriggerSpecSemanticDescriptor>();
for (const descriptor of descriptors) {
const descriptorSchema = descriptor?.schema;
const normalizeConfig = descriptor?.normalizeConfig;
exactKeys(
descriptor,
['normalizeConfig', 'schema'],
[],
'registry descriptor',
InvalidTriggerSpecSemanticError,
);
let schema: string;
try {
schema = normalizeTriggerSpec({
schema: descriptorSchema,
config: {},
}).schema;
} catch {
throw new InvalidTriggerSpecSemanticError(
'registry descriptor schema is invalid',
);
}
if (typeof normalizeConfig !== 'function' || bySchema.has(schema)) {
throw new InvalidTriggerSpecSemanticError(
'registry descriptor is invalid or duplicated',
);
}
bySchema.set(
schema,
Object.freeze({
schema,
normalizeConfig,
}),
);
}
this.#descriptors = bySchema;
this.#metadata = Object.freeze(
[...bySchema.keys()]
.sort()
.map((schema) => Object.freeze({ schema })),
);
Object.freeze(this);
}
list(): readonly TriggerSpecSemanticMetadata[] {
return this.#metadata;
}
supports(schema: string): boolean {
return this.#descriptors.has(schema);
}
normalize(context: {
readonly projectId: string;
readonly triggerId: string;
readonly taskId: string;
readonly taskRevision: number;
readonly spec: TriggerSpec;
}): TriggerSpec {
exactKeys(
context,
['projectId', 'spec', 'taskId', 'taskRevision', 'triggerId'],
[],
'semantic context',
InvalidTriggerSpecSemanticError,
);
const projectId = identifier(context.projectId, 'projectId');
const triggerId = identifier(context.triggerId, 'triggerId');
const taskId = identifier(context.taskId, 'taskId');
const taskRevision = revision(context.taskRevision, 'taskRevision');
const spec = normalizeTriggerSpec(context.spec);
const descriptor = this.#descriptors.get(spec.schema);
if (!descriptor) throw new UnsupportedTriggerSpecError();
let config: Readonly<Record<string, TriggerSpecJson>>;
try {
config = descriptor.normalizeConfig(
spec.config,
Object.freeze({ projectId, triggerId, taskId, taskRevision }),
);
} catch (error) {
if (error instanceof InvalidTriggerSpecSemanticError) throw error;
throw new InvalidTriggerSpecSemanticError('validator rejected the config');
}
return normalizeTriggerSpec({ schema: spec.schema, config });
}
}
export function createBuiltInTriggerSpecSemanticRegistry(): TriggerSpecSemanticRegistry {
return new TriggerSpecSemanticRegistry(BUILT_IN_DESCRIPTORS);
}
export function createTriggerSpecSemanticRegistry(
extensions: readonly TriggerSpecSemanticDescriptor[] = [],
): TriggerSpecSemanticRegistry {
if (
!Array.isArray(extensions) ||
extensions.some(
(descriptor) =>
!descriptor ||
typeof descriptor !== 'object' ||
typeof descriptor.schema !== 'string' ||
descriptor.schema.startsWith('qinglong/'),
)
) {
throw new InvalidTriggerSpecSemanticError(
'extension descriptor uses the reserved qinglong namespace',
);
}
return new TriggerSpecSemanticRegistry([
...BUILT_IN_DESCRIPTORS,
...extensions,
]);
}
function semanticTrigger(value: {
readonly projectId: string;
readonly triggerId: string;
readonly revision: number;
readonly taskId: string;
readonly taskRevision: number;
readonly taskContentDigest: string;
readonly spec: TriggerSpec;
readonly enabled: boolean;
}): object {
return {
projectId: value.projectId,
triggerId: value.triggerId,
revision: value.revision,
taskId: value.taskId,
taskRevision: value.taskRevision,
taskContentDigest: value.taskContentDigest,
spec: value.spec,
enabled: value.enabled,
};
}
export function triggerContentDigest(
value: Parameters<typeof semanticTrigger>[0],
): string {
return createHash('sha256')
.update('qinglong.trigger-definition.v1\0')
.update(JSON.stringify(semanticTrigger(value)))
.digest('hex');
}
function normalizeTriggerFields(value: {
readonly projectId: unknown;
readonly triggerId: unknown;
readonly revision: unknown;
readonly taskId: unknown;
readonly taskRevision: unknown;
readonly taskContentDigest: unknown;
readonly spec: TriggerSpec;
readonly enabled: unknown;
}): Omit<
TriggerRecord,
'mutationId' | 'contentDigest' | 'createdAtMs' | 'updatedAtMs'
> {
if (
typeof value.taskContentDigest !== 'string' ||
!DIGEST_PATTERN.test(value.taskContentDigest)
) {
throw new InvalidTriggerError('taskContentDigest is invalid');
}
if (typeof value.enabled !== 'boolean') {
throw new InvalidTriggerError('enabled is invalid');
}
return Object.freeze({
projectId: identifier(value.projectId, 'projectId'),
triggerId: identifier(value.triggerId, 'triggerId'),
revision: revision(value.revision, 'revision'),
taskId: identifier(value.taskId, 'taskId'),
taskRevision: revision(value.taskRevision, 'taskRevision'),
taskContentDigest: value.taskContentDigest,
spec: normalizeTriggerSpec(value.spec),
enabled: value.enabled,
});
}
export function normalizeAppendTriggerRevisionCommand(
value: AppendTriggerRevisionCommand,
): Readonly<AppendTriggerRevisionCommand> {
exactKeys(
value,
[
'enabled',
'expectedRevision',
'mutationId',
'occurredAtMs',
'projectId',
'spec',
'taskContentDigest',
'taskId',
'taskRevision',
'triggerId',
],
[],
'command',
);
const expectedRevision =
value.expectedRevision === null
? null
: revision(value.expectedRevision, 'expectedRevision');
if (
typeof value.mutationId !== 'string' ||
!MUTATION_ID_PATTERN.test(value.mutationId)
) {
throw new InvalidTriggerError('mutationId is invalid');
}
const fields = normalizeTriggerFields({
...value,
revision: expectedRevision === null ? 1 : expectedRevision + 1,
});
return Object.freeze({
projectId: fields.projectId,
triggerId: fields.triggerId,
expectedRevision,
mutationId: value.mutationId,
taskId: fields.taskId,
taskRevision: fields.taskRevision,
taskContentDigest: fields.taskContentDigest,
spec: fields.spec,
enabled: fields.enabled,
occurredAtMs: timestamp(value.occurredAtMs, 'occurredAtMs'),
});
}
export function normalizeTriggerRecord(value: TriggerRecord): TriggerRecord {
exactKeys(
value,
[
'contentDigest',
'createdAtMs',
'enabled',
'mutationId',
'projectId',
'revision',
'spec',
'taskContentDigest',
'taskId',
'taskRevision',
'triggerId',
'updatedAtMs',
],
[],
'record',
);
const fields = normalizeTriggerFields(value);
if (
typeof value.mutationId !== 'string' ||
!MUTATION_ID_PATTERN.test(value.mutationId) ||
typeof value.contentDigest !== 'string' ||
!DIGEST_PATTERN.test(value.contentDigest)
) {
throw new InvalidTriggerError('record identity is invalid');
}
const createdAtMs = timestamp(value.createdAtMs, 'createdAtMs');
const updatedAtMs = timestamp(value.updatedAtMs, 'updatedAtMs');
if (updatedAtMs < createdAtMs) {
throw new InvalidTriggerError('record time order is invalid');
}
if (value.contentDigest !== triggerContentDigest(fields)) {
throw new InvalidTriggerError('content digest did not match');
}
return Object.freeze({
...fields,
mutationId: value.mutationId,
contentDigest: value.contentDigest,
createdAtMs,
updatedAtMs,
});
}
export function createTriggerRecord(
command: AppendTriggerRevisionCommand,
createdAtMs: number,
): TriggerRecord {
const normalized = normalizeAppendTriggerRevisionCommand(command);
const fields = normalizeTriggerFields({
...normalized,
revision:
normalized.expectedRevision === null
? 1
: normalized.expectedRevision + 1,
});
return normalizeTriggerRecord({
...fields,
mutationId: normalized.mutationId,
contentDigest: triggerContentDigest(fields),
createdAtMs: timestamp(createdAtMs, 'createdAtMs'),
updatedAtMs: normalized.occurredAtMs,
});
}
export function assertTriggerPageSize(limit: number): void {
if (
!Number.isSafeInteger(limit) ||
limit < 1 ||
limit > MAX_TRIGGER_PAGE_SIZE
) {
throw new RangeError(
`Trigger page size must be between 1 and ${MAX_TRIGGER_PAGE_SIZE}`,
);
}
}
export function normalizeTriggerCursor(cursor: TriggerCursor): TriggerCursor {
exactKeys(cursor, ['triggerId'], [], 'cursor');
return Object.freeze({
triggerId: identifier(cursor.triggerId, 'cursor.triggerId'),
});
}
@@ -0,0 +1,292 @@
import {
assertTriggerIdentifier,
assertTriggerPageSize,
normalizeAppendTriggerRevisionCommand,
normalizeTriggerCursor,
type AppendTriggerRevisionCommand,
type TriggerCursor,
type TriggerPage,
type TriggerRecord,
} from './trigger';
import { normalizeProjectPolicySubject } from '../security/project-policy/projectPolicy';
import type { SecurityPolicyFence, SecuritySubject } from '../security/security';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../security/audit/securityAudit';
export interface AuthorizedTriggerRevisionMutation {
readonly command: AppendTriggerRevisionCommand;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface TriggerAdministrationRepository {
appendAuthorizedTriggerRevision(
mutation: AuthorizedTriggerRevisionMutation,
): Promise<
Readonly<{
status: 'created' | 'updated' | 'existing';
trigger: TriggerRecord;
}>
>;
}
export interface AuthorizedTriggerInspection {
readonly projectId: string;
readonly triggerId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface AuthorizedTriggerList {
readonly projectId: string;
readonly limit: number;
readonly after?: TriggerCursor;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface TriggerAdministrationSource {
findAuthorizedCurrentTrigger(
inspection: AuthorizedTriggerInspection,
): Promise<TriggerRecord | null>;
listAuthorizedTriggers(query: AuthorizedTriggerList): Promise<TriggerPage>;
}
export class InvalidTriggerAdministrationMutationError extends TypeError {
readonly code = 'TRIGGER_ADMINISTRATION_MUTATION_INVALID';
constructor(message: string) {
super(`Trigger administration mutation is invalid: ${message}`);
this.name = 'InvalidTriggerAdministrationMutationError';
}
}
export class TriggerAdministrationAuthorizationFenceConflictError extends Error {
readonly code = 'TRIGGER_ADMINISTRATION_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Trigger administration authorization fence changed');
this.name = 'TriggerAdministrationAuthorizationFenceConflictError';
}
}
export class TriggerAdministrationMutationConflictError extends Error {
readonly code = 'TRIGGER_ADMINISTRATION_MUTATION_CONFLICT';
constructor() {
super('Trigger administration mutation conflicts with durable state');
this.name = 'TriggerAdministrationMutationConflictError';
}
}
export class InvalidTriggerAdministrationReadError extends TypeError {
readonly code = 'TRIGGER_ADMINISTRATION_READ_INVALID';
constructor(message: string) {
super(`Trigger administration read is invalid: ${message}`);
this.name = 'InvalidTriggerAdministrationReadError';
}
}
export class TriggerAdministrationReadConflictError extends Error {
readonly code = 'TRIGGER_ADMINISTRATION_READ_CONFLICT';
constructor() {
super('Trigger administration read conflicts with durable state');
this.name = 'TriggerAdministrationReadConflictError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
actual.length === canonical.length &&
actual.every((key, index) => key === canonical[index])
);
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function normalizeFence(value: SecurityPolicyFence): SecurityPolicyFence {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['bindingVersion', 'projectVersion']) ||
!Number.isSafeInteger(value.projectVersion) ||
value.projectVersion < 1 ||
!Number.isSafeInteger(value.bindingVersion) ||
(value.bindingVersion as number) < 1
) {
throw new InvalidTriggerAdministrationMutationError(
'authorization fence is invalid',
);
}
return Object.freeze({
projectVersion: value.projectVersion,
bindingVersion: value.bindingVersion,
});
}
export function normalizeAuthorizedTriggerRevisionMutation(
value: AuthorizedTriggerRevisionMutation,
): Readonly<AuthorizedTriggerRevisionMutation> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['actor', 'audit', 'command', 'fence'])
) {
throw new InvalidTriggerAdministrationMutationError(
'mutation shape is invalid',
);
}
try {
const command = normalizeAppendTriggerRevisionCommand(value.command);
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
const operationId =
command.expectedRevision === null ? 'trigger.create' : 'trigger.update';
if (
audit.eventId !== command.mutationId ||
audit.operationId !== operationId ||
audit.projectId !== command.projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidTriggerAdministrationMutationError(
'audit binding is invalid',
);
}
return Object.freeze({ command, actor, fence, audit });
} catch (error) {
if (error instanceof InvalidTriggerAdministrationMutationError) {
throw error;
}
throw new InvalidTriggerAdministrationMutationError(
'mutation value is invalid',
);
}
}
function normalizeTriggerReadAuthority(
value: Readonly<{
projectId: string;
actor: SecuritySubject;
fence: SecurityPolicyFence;
audit: SecurityAuditRecord;
}>,
): Readonly<{
projectId: string;
actor: SecuritySubject;
fence: SecurityPolicyFence;
audit: SecurityAuditRecord;
}> {
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'trigger.read' ||
audit.projectId !== value.projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidTriggerAdministrationReadError(
'audit binding is invalid',
);
}
return Object.freeze({
projectId: value.projectId,
actor,
fence,
audit,
});
}
export function normalizeAuthorizedTriggerInspection(
value: AuthorizedTriggerInspection,
): Readonly<AuthorizedTriggerInspection> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['actor', 'audit', 'fence', 'projectId', 'triggerId'])
) {
throw new InvalidTriggerAdministrationReadError(
'inspection shape is invalid',
);
}
try {
assertTriggerIdentifier(value.projectId, 'projectId');
assertTriggerIdentifier(value.triggerId, 'triggerId');
return Object.freeze({
...normalizeTriggerReadAuthority(value),
triggerId: value.triggerId,
});
} catch (error) {
if (error instanceof InvalidTriggerAdministrationReadError) throw error;
throw new InvalidTriggerAdministrationReadError(
'inspection value is invalid',
);
}
}
export function normalizeAuthorizedTriggerList(
value: AuthorizedTriggerList,
): Readonly<AuthorizedTriggerList> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidTriggerAdministrationReadError('list shape is invalid');
}
const keys = Object.keys(value);
if (
!['actor', 'audit', 'fence', 'limit', 'projectId'].every((key) =>
keys.includes(key),
) ||
keys.some(
(key) =>
!['actor', 'after', 'audit', 'fence', 'limit', 'projectId'].includes(
key,
),
)
) {
throw new InvalidTriggerAdministrationReadError('list shape is invalid');
}
try {
assertTriggerIdentifier(value.projectId, 'projectId');
assertTriggerPageSize(value.limit);
const authority = normalizeTriggerReadAuthority(value);
const after = Object.hasOwn(value, 'after')
? normalizeTriggerCursor(value.after as TriggerCursor)
: undefined;
return Object.freeze({
...authority,
limit: value.limit,
...(after ? { after } : {}),
});
} catch (error) {
if (error instanceof InvalidTriggerAdministrationReadError) throw error;
throw new InvalidTriggerAdministrationReadError('list value is invalid');
}
}
@@ -0,0 +1,316 @@
import type { LocalDispatchCandidate } from '../local-runtime/localDispatch';
import {
MAX_SECRET_REF_BYTES,
createSecretRef,
parseSecretRef,
type SecretReference,
} from './secretReference';
export const LOCAL_SECRET_ALGORITHM = 'aes-256-gcm';
export const MAX_LOCAL_SECRET_NAME_BYTES = 128;
export const MAX_LOCAL_SECRET_VERSION = 2_147_483_647;
export const MAX_LOCAL_SECRET_REF_BYTES = MAX_SECRET_REF_BYTES;
export const MAX_LOCAL_SECRET_MUTATION_ID_BYTES = 64;
export const MAX_LOCAL_SECRET_KEY_ID_BYTES = 128;
export const MAX_LOCAL_SECRET_PLAINTEXT_BYTES = 16 * 1024;
export const MAX_LOCAL_SECRET_BATCH_SIZE = 64;
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
const KEY_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
/** @deprecated Use the profile-neutral SecretReference contract. */
export type LocalSecretReference = SecretReference;
export interface LocalSecretEnvelope {
readonly projectId: string;
readonly name: string;
readonly version: number;
readonly mutationId: string;
readonly keyId: string;
readonly algorithm: typeof LOCAL_SECRET_ALGORITHM;
readonly nonce: string;
readonly ciphertext: string;
readonly authTag: string;
readonly createdAtMs: number;
}
export interface AppendLocalSecretEnvelopeCommand {
readonly envelope: LocalSecretEnvelope;
readonly expectedCurrentVersion: number;
}
export type AppendLocalSecretEnvelopeResult = Readonly<{
status: 'inserted' | 'existing';
envelope: LocalSecretEnvelope;
}>;
export interface LocalSecretEnvelopeRepository {
appendLocalSecretEnvelope(
command: AppendLocalSecretEnvelopeCommand,
): Promise<AppendLocalSecretEnvelopeResult>;
findLocalSecretEnvelopeByMutation(
projectId: string,
name: string,
mutationId: string,
): Promise<LocalSecretEnvelope | null>;
resolveLocalSecretEnvelopes(
references: readonly LocalSecretReference[],
): Promise<readonly (LocalSecretEnvelope | null)[]>;
}
export interface LocalSecretKeyMaterial {
readonly keyId: string;
/** Exactly 32 bytes. The consumer owns this copy and must wipe it. */
readonly key: Uint8Array;
}
export interface LocalSecretKeyProvider {
active(): Promise<LocalSecretKeyMaterial>;
resolve(keyId: string): Promise<LocalSecretKeyMaterial | null>;
}
export interface LocalSecretEnvironmentProvider {
resolveLocalSecretEnvironment(request: {
readonly candidate: LocalDispatchCandidate;
readonly secretRefs: readonly string[];
}): Promise<readonly string[] | null>;
}
export interface PutEncryptedLocalSecretCommand {
readonly projectId: string;
readonly name: string;
readonly plaintext: string;
readonly mutationId: string;
readonly expectedCurrentVersion: number;
readonly createdAtMs: number;
}
export interface PutEncryptedLocalSecretResult {
readonly status: 'inserted' | 'existing';
readonly version: number;
readonly secretRef: string;
}
export class InvalidLocalSecretError extends TypeError {
readonly code = 'LOCAL_SECRET_INVALID';
constructor(message: string) {
super(`Local Secret value is invalid: ${message}`);
this.name = 'InvalidLocalSecretError';
}
}
export class LocalSecretUnavailableError extends Error {
readonly code = 'LOCAL_SECRET_UNAVAILABLE';
constructor() {
super('Local Secret is unavailable');
this.name = 'LocalSecretUnavailableError';
}
}
export class LocalSecretVersionConflictError extends Error {
readonly code = 'LOCAL_SECRET_VERSION_CONFLICT';
constructor() {
super('Local Secret current version changed');
this.name = 'LocalSecretVersionConflictError';
}
}
export class LocalSecretMutationConflictError extends Error {
readonly code = 'LOCAL_SECRET_MUTATION_CONFLICT';
constructor() {
super('Local Secret mutation does not match its previous request');
this.name = 'LocalSecretMutationConflictError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const sortedExpected = [...expected].sort();
return (
actual.length === sortedExpected.length &&
actual.every((key, index) => key === sortedExpected[index])
);
}
function assertIdentifier(
name: string,
value: unknown,
maximumBytes: number,
): asserts value is string {
if (
typeof value !== 'string' ||
value.length === 0 ||
Buffer.byteLength(value, 'utf8') > maximumBytes ||
/[\u0000-\u001f\u007f]/.test(value)
) {
throw new InvalidLocalSecretError(`${name} is invalid`);
}
}
export function assertLocalSecretProjectId(value: unknown): asserts value is string {
assertIdentifier('projectId', value, 128);
}
export function assertLocalSecretName(value: unknown): asserts value is string {
assertIdentifier('name', value, MAX_LOCAL_SECRET_NAME_BYTES);
}
export function assertLocalSecretVersion(value: unknown): asserts value is number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > MAX_LOCAL_SECRET_VERSION
) {
throw new InvalidLocalSecretError('version is invalid');
}
}
export function assertLocalSecretMutationId(value: unknown): asserts value is string {
assertIdentifier('mutationId', value, MAX_LOCAL_SECRET_MUTATION_ID_BYTES);
}
export function assertLocalSecretKeyId(value: unknown): asserts value is string {
if (
typeof value !== 'string' ||
value.length === 0 ||
Buffer.byteLength(value, 'utf8') > MAX_LOCAL_SECRET_KEY_ID_BYTES ||
!KEY_ID_PATTERN.test(value)
) {
throw new InvalidLocalSecretError('keyId is invalid');
}
}
export function assertLocalSecretPlaintext(value: unknown): asserts value is string {
if (
typeof value !== 'string' ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > MAX_LOCAL_SECRET_PLAINTEXT_BYTES
) {
throw new InvalidLocalSecretError('plaintext is invalid');
}
}
export function assertLocalSecretExpectedVersion(value: unknown): asserts value is number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) >= MAX_LOCAL_SECRET_VERSION
) {
throw new InvalidLocalSecretError('expectedCurrentVersion is invalid');
}
}
function decodeBase64Url(name: string, value: unknown, bytes?: number): Buffer {
if (
typeof value !== 'string' ||
(value.length > 0 && !BASE64URL_PATTERN.test(value))
) {
throw new InvalidLocalSecretError(`${name} is invalid`);
}
const decoded = Buffer.from(value, 'base64url');
if (
decoded.toString('base64url') !== value ||
(bytes !== undefined && decoded.length !== bytes)
) {
decoded.fill(0);
throw new InvalidLocalSecretError(`${name} is invalid`);
}
return decoded;
}
export function localSecretBinary(
name: 'nonce' | 'ciphertext' | 'authTag',
value: unknown,
): Buffer {
const decoded = decodeBase64Url(
name,
value,
name === 'nonce' ? 12 : name === 'authTag' ? 16 : undefined,
);
if (
name === 'ciphertext' &&
decoded.length > MAX_LOCAL_SECRET_PLAINTEXT_BYTES
) {
decoded.fill(0);
throw new InvalidLocalSecretError('ciphertext is too large');
}
return decoded;
}
export function createLocalSecretRef(reference: LocalSecretReference): string {
try {
return createSecretRef(reference);
} catch {
throw new InvalidLocalSecretError('reference is invalid');
}
}
export function parseLocalSecretRef(value: unknown): LocalSecretReference {
try {
return parseSecretRef(value);
} catch {
throw new InvalidLocalSecretError('reference is invalid');
}
}
export function normalizeLocalSecretEnvelope(
envelope: LocalSecretEnvelope,
): LocalSecretEnvelope {
if (
!envelope ||
typeof envelope !== 'object' ||
Array.isArray(envelope) ||
!exactKeys(envelope, [
'projectId',
'name',
'version',
'mutationId',
'keyId',
'algorithm',
'nonce',
'ciphertext',
'authTag',
'createdAtMs',
])
) {
throw new InvalidLocalSecretError('envelope is invalid');
}
assertLocalSecretProjectId(envelope.projectId);
assertLocalSecretName(envelope.name);
assertLocalSecretVersion(envelope.version);
assertLocalSecretMutationId(envelope.mutationId);
assertLocalSecretKeyId(envelope.keyId);
if (envelope.algorithm !== LOCAL_SECRET_ALGORITHM) {
throw new InvalidLocalSecretError('algorithm is invalid');
}
for (const name of ['nonce', 'ciphertext', 'authTag'] as const) {
localSecretBinary(name, envelope[name]).fill(0);
}
if (!Number.isSafeInteger(envelope.createdAtMs) || envelope.createdAtMs < 0) {
throw new InvalidLocalSecretError('createdAtMs is invalid');
}
return Object.freeze({ ...envelope });
}
export function localSecretEnvelopeAad(
envelope: Pick<
LocalSecretEnvelope,
'projectId' | 'name' | 'version' | 'mutationId' | 'keyId' | 'algorithm'
>,
): Buffer {
return Buffer.from(
JSON.stringify({
projectId: envelope.projectId,
name: envelope.name,
version: envelope.version,
mutationId: envelope.mutationId,
keyId: envelope.keyId,
algorithm: envelope.algorithm,
}),
'utf8',
);
}
@@ -0,0 +1,52 @@
import type {
AppendLocalSecretEnvelopeResult,
LocalSecretEnvelope,
} from './localSecret';
import type { SecurityPolicyFence, SecuritySubject } from '../security/security';
import type {
SecurityAuditRecord,
SecurityAuditSink,
} from '../security/audit/securityAudit';
export interface LocalSecretAdministrationMutation {
readonly envelope: LocalSecretEnvelope;
readonly audit: SecurityAuditRecord;
}
export interface AppendAuthorizedLocalSecretEnvelopeCommand {
readonly expectedCurrentVersion: number;
readonly envelope: LocalSecretEnvelope;
readonly subject: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface AppendAuthorizedLocalSecretEnvelopeResult
extends AppendLocalSecretEnvelopeResult {
readonly audit: Readonly<SecurityAuditRecord>;
}
/**
* Short-lived management authority. Implementations must revalidate the
* Project/RoleBinding fence and append the envelope plus audit atomically.
*/
export interface LocalSecretAdministrationRepository
extends SecurityAuditSink {
resolveLocalSecretAdministrationMutation(
projectId: string,
name: string,
mutationId: string,
): Promise<Readonly<LocalSecretAdministrationMutation> | null>;
appendAuthorizedLocalSecretEnvelope(
command: AppendAuthorizedLocalSecretEnvelopeCommand,
): Promise<AppendAuthorizedLocalSecretEnvelopeResult>;
}
export class LocalSecretAuthorizationFenceConflictError extends Error {
readonly code = 'LOCAL_SECRET_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Local Secret authorization changed');
this.name = 'LocalSecretAuthorizationFenceConflictError';
}
}
@@ -0,0 +1,132 @@
export const SECRET_REF_PREFIX = 'qlsecret:v1:';
export const MAX_SECRET_REF_BYTES = 512;
export const MAX_SECRET_NAME_BYTES = 128;
export const MAX_SECRET_VERSION = 2_147_483_647;
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
export interface SecretReference {
readonly projectId: string;
readonly name: string;
readonly version?: number;
}
export class InvalidSecretReferenceError extends TypeError {
readonly code = 'SECRET_REFERENCE_INVALID';
constructor(message: string) {
super(`Secret reference is invalid: ${message}`);
this.name = 'InvalidSecretReferenceError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const sortedExpected = [...expected].sort();
return (
actual.length === sortedExpected.length &&
actual.every((key, index) => key === sortedExpected[index])
);
}
function boundedIdentifier(
value: unknown,
label: string,
maximumBytes: number,
): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
Buffer.byteLength(value, 'utf8') > maximumBytes ||
/[\u0000-\u001f\u007f]/.test(value)
) {
throw new InvalidSecretReferenceError(`${label} is invalid`);
}
return value;
}
function secretVersion(value: unknown): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > MAX_SECRET_VERSION
) {
throw new InvalidSecretReferenceError('version is invalid');
}
return value as number;
}
export function createSecretRef(reference: SecretReference): string {
if (
!reference ||
typeof reference !== 'object' ||
Array.isArray(reference) ||
!exactKeys(
reference,
reference.version === undefined
? ['projectId', 'name']
: ['projectId', 'name', 'version'],
)
) {
throw new InvalidSecretReferenceError('shape is invalid');
}
const projectId = boundedIdentifier(reference.projectId, 'projectId', 128);
const name = boundedIdentifier(reference.name, 'name', MAX_SECRET_NAME_BYTES);
const version =
reference.version === undefined
? undefined
: secretVersion(reference.version);
const payload = JSON.stringify({
projectId,
name,
...(version === undefined ? {} : { version }),
});
const result = `${SECRET_REF_PREFIX}${Buffer.from(payload, 'utf8').toString(
'base64url',
)}`;
if (Buffer.byteLength(result, 'utf8') > MAX_SECRET_REF_BYTES) {
throw new InvalidSecretReferenceError('byte budget exceeded');
}
return result;
}
export function parseSecretRef(value: unknown): SecretReference {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > MAX_SECRET_REF_BYTES ||
!value.startsWith(SECRET_REF_PREFIX)
) {
throw new InvalidSecretReferenceError('encoding is invalid');
}
const encoded = value.slice(SECRET_REF_PREFIX.length);
if (encoded.length === 0 || !BASE64URL_PATTERN.test(encoded)) {
throw new InvalidSecretReferenceError('encoding is invalid');
}
const decoded = Buffer.from(encoded, 'base64url');
try {
if (decoded.toString('base64url') !== encoded) {
throw new InvalidSecretReferenceError('encoding is not canonical');
}
const parsed = JSON.parse(decoded.toString('utf8')) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new InvalidSecretReferenceError('payload is invalid');
}
const record = parsed as Record<string, unknown>;
const reference: SecretReference = {
projectId: record.projectId as string,
name: record.name as string,
...(record.version === undefined
? {}
: { version: record.version as number }),
};
if (createSecretRef(reference) !== value) {
throw new InvalidSecretReferenceError('encoding is not canonical');
}
return Object.freeze(reference);
} catch (error) {
if (error instanceof InvalidSecretReferenceError) throw error;
throw new InvalidSecretReferenceError('payload is invalid');
} finally {
decoded.fill(0);
}
}
@@ -0,0 +1,49 @@
import type { SecurityPolicyFence, SecuritySubject } from '../security';
import type { SecurityAuditRecord, SecurityAuditSink } from './securityAudit';
import type {
SecurityAuditQuery,
SecurityAuditQueryPage,
} from './securityAuditQuery';
export const MAX_LOCAL_SECURITY_AUDIT_QUERY_PAGE_SIZE = 64;
export interface LocalSecurityAuditQueryAuthorization {
readonly authorityProjectId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
}
export interface ListAuthorizedLocalSecurityAuditCommand {
readonly query: SecurityAuditQuery;
readonly authorization: LocalSecurityAuditQueryAuthorization;
readonly audit: SecurityAuditRecord;
}
export interface ListAuthorizedLocalSecurityAuditResult
extends SecurityAuditQueryPage {
readonly audit: Readonly<SecurityAuditRecord>;
}
export interface LocalSecurityAuditQueryRepository extends SecurityAuditSink {
listAuthorized(
command: ListAuthorizedLocalSecurityAuditCommand,
): Promise<ListAuthorizedLocalSecurityAuditResult>;
}
export class LocalSecurityAuditQueryAuthorizationFenceConflictError extends Error {
readonly code = 'LOCAL_SECURITY_AUDIT_QUERY_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Local security audit query authorization fence changed');
this.name = 'LocalSecurityAuditQueryAuthorizationFenceConflictError';
}
}
export class LocalSecurityAuditQueryUnavailableError extends Error {
readonly code = 'LOCAL_SECURITY_AUDIT_QUERY_UNAVAILABLE';
constructor() {
super('Local security audit query is unavailable');
this.name = 'LocalSecurityAuditQueryUnavailableError';
}
}
@@ -0,0 +1,131 @@
import { createHash } from 'node:crypto';
import type { SecurityPolicyFence, SecuritySubject } from '../security';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
type SecurityAuditSink,
} from './securityAudit';
import type { SecurityAuditQueryCursor } from './securityAuditQuery';
export const MIN_LOCAL_SECURITY_AUDIT_RETENTION_MS = 30 * 24 * 60 * 60 * 1_000;
export const MAX_LOCAL_SECURITY_AUDIT_RETENTION_MS =
10 * 365 * 24 * 60 * 60 * 1_000;
export const MAX_EDGE_SECURITY_AUDIT_COMPACTION_BATCH_SIZE = 64;
export const MAX_STANDALONE_SECURITY_AUDIT_COMPACTION_BATCH_SIZE = 512;
export const MAX_LOCAL_SECURITY_AUDIT_COMPACTION_PAYLOAD_BYTES =
16 * 1024 * 1024;
export interface LocalSecurityAuditRetentionAuthorization {
readonly authorityProjectId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
}
export interface LocalSecurityAuditCompactionRecord {
readonly mutationId: string;
readonly requestId: string;
readonly authorityProjectId: string;
readonly retentionMs: number;
readonly eligibleBeforeMs: number;
readonly batchLimit: number;
readonly deletedCount: number;
readonly deletedPayloadBytes: number;
readonly first: Readonly<SecurityAuditQueryCursor> | null;
readonly last: Readonly<SecurityAuditQueryCursor> | null;
readonly recordsDigest: string;
readonly createdAtMs: number;
}
export interface CompactAuthorizedLocalSecurityAuditCommand {
readonly mutationId: string;
readonly requestId: string;
readonly retentionMs: number;
readonly eligibleBeforeMs: number;
readonly limit: number;
readonly authorization: LocalSecurityAuditRetentionAuthorization;
readonly audit: SecurityAuditRecord;
}
export interface CompactAuthorizedLocalSecurityAuditResult {
readonly status: 'inserted' | 'existing';
readonly record: Readonly<LocalSecurityAuditCompactionRecord>;
readonly audit: Readonly<SecurityAuditRecord>;
}
export interface LocalSecurityAuditRetentionRepository
extends SecurityAuditSink {
resolveCompaction(
mutationId: string,
): Promise<Readonly<LocalSecurityAuditCompactionRecord> | null>;
compactAuthorized(
command: CompactAuthorizedLocalSecurityAuditCommand,
): Promise<CompactAuthorizedLocalSecurityAuditResult>;
}
export class InvalidLocalSecurityAuditRetentionValueError extends TypeError {
constructor(message: string) {
super(`Local security audit retention value is invalid: ${message}`);
this.name = 'InvalidLocalSecurityAuditRetentionValueError';
}
}
export class LocalSecurityAuditRetentionAuthorizationFenceConflictError extends Error {
readonly code = 'LOCAL_SECURITY_AUDIT_RETENTION_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Local security audit retention authorization fence changed');
this.name = 'LocalSecurityAuditRetentionAuthorizationFenceConflictError';
}
}
export class LocalSecurityAuditCompactionMutationConflictError extends Error {
readonly code = 'LOCAL_SECURITY_AUDIT_COMPACTION_MUTATION_CONFLICT';
constructor() {
super('Local security audit compaction mutation conflicts');
this.name = 'LocalSecurityAuditCompactionMutationConflictError';
}
}
export class LocalSecurityAuditRetentionUnavailableError extends Error {
readonly code = 'LOCAL_SECURITY_AUDIT_RETENTION_UNAVAILABLE';
constructor() {
super('Local security audit retention is unavailable');
this.name = 'LocalSecurityAuditRetentionUnavailableError';
}
}
export function localSecurityAuditCompactionPayload(
records: readonly Readonly<SecurityAuditRecord>[],
): Readonly<{ recordsDigest: string; payloadBytes: number }> {
if (!Array.isArray(records)) {
throw new InvalidLocalSecurityAuditRetentionValueError(
'records must be an array',
);
}
let normalized: Readonly<SecurityAuditRecord>[];
try {
normalized = records.map((record) => normalizeSecurityAuditRecord(record));
} catch {
throw new InvalidLocalSecurityAuditRetentionValueError(
'records contain an invalid audit value',
);
}
const payload = JSON.stringify(normalized);
const payloadBytes =
normalized.length === 0 ? 0 : Buffer.byteLength(payload, 'utf8');
if (payloadBytes > MAX_LOCAL_SECURITY_AUDIT_COMPACTION_PAYLOAD_BYTES) {
throw new InvalidLocalSecurityAuditRetentionValueError(
'records exceed the payload limit',
);
}
return Object.freeze({
recordsDigest: createHash('sha256')
.update('qinglong.local-security-audit-compaction.records.v1\0', 'utf8')
.update(payload, 'utf8')
.digest('hex'),
payloadBytes,
});
}
Loaded 100 of 2817 files, more files were not shown because too many files have changed in this diff. Show more