@proofoftech/flowsafe 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +106 -0
- package/README.md +68 -6
- package/deployment-identity-protocol.d.mts +70 -1
- package/deployment-identity-protocol.mjs +423 -5
- package/dist/agent-host/index.d.ts +1 -1
- package/dist/agent-host/index.d.ts.map +1 -1
- package/dist/agent-host/index.js.map +1 -1
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +17 -4
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +14 -1
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +865 -308
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +43 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +301 -28
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +427 -55
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +1 -1
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +4 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +53 -5
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +6 -3
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/principal-identity.d.ts +32 -0
- package/dist/approval-api/principal-identity.d.ts.map +1 -0
- package/dist/approval-api/principal-identity.js +69 -0
- package/dist/approval-api/principal-identity.js.map +1 -0
- package/dist/approval-api/principal.d.ts +10 -13
- package/dist/approval-api/principal.d.ts.map +1 -1
- package/dist/approval-api/principal.js +10 -46
- package/dist/approval-api/principal.js.map +1 -1
- package/dist/approval-api/retention.d.ts +1 -2
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +9 -1
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +29 -14
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +83 -25
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/types.d.ts +12 -0
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +12 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/audit-export/index.d.ts +2 -2
- package/dist/audit-export/index.js +2 -2
- package/dist/background-tasks/d1-storage.d.ts +4 -3
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -13
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/background-tasks/host.d.ts +127 -14
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +579 -50
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/background-tasks/index.d.ts +2 -2
- package/dist/background-tasks/index.d.ts.map +1 -1
- package/dist/background-tasks/index.js +11 -6
- package/dist/background-tasks/index.js.map +1 -1
- package/dist/background-tasks/routes.d.ts +19 -2
- package/dist/background-tasks/routes.d.ts.map +1 -1
- package/dist/background-tasks/routes.js +4 -4
- package/dist/background-tasks/routes.js.map +1 -1
- package/dist/deployment-identity-protocol.d.ts +2 -2
- package/dist/deployment-identity-protocol.d.ts.map +1 -1
- package/dist/deployment-identity-protocol.js +1 -1
- package/dist/deployment-identity-protocol.js.map +1 -1
- package/dist/do-runner/cause-chain.d.ts +53 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -0
- package/dist/do-runner/cause-chain.js +96 -0
- package/dist/do-runner/cause-chain.js.map +1 -0
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -0
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +47 -69
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +972 -196
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/deployment-identity.d.ts +29 -5
- package/dist/do-runner/deployment-identity.d.ts.map +1 -1
- package/dist/do-runner/deployment-identity.js +23 -6
- package/dist/do-runner/deployment-identity.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts +4 -23
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +19 -24
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/do-status-error.d.ts +37 -0
- package/dist/do-runner/do-status-error.d.ts.map +1 -0
- package/dist/do-runner/do-status-error.js +42 -0
- package/dist/do-runner/do-status-error.js.map +1 -0
- package/dist/do-runner/durable-object.d.ts +2 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +617 -144
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-admission.d.ts +114 -0
- package/dist/do-runner/execution-admission.d.ts.map +1 -0
- package/dist/do-runner/execution-admission.js +206 -0
- package/dist/do-runner/execution-admission.js.map +1 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +1 -0
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +379 -0
- package/dist/do-runner/execution-fence.d.ts.map +1 -0
- package/dist/do-runner/execution-fence.js +1098 -0
- package/dist/do-runner/execution-fence.js.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.js +3 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.js +894 -0
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
- package/dist/do-runner/index.d.ts +20 -8
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +21 -4
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +82 -1
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +58 -3
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
- package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
- package/dist/do-runner/initial-admission-refusal.js +41 -0
- package/dist/do-runner/initial-admission-refusal.js.map +1 -0
- package/dist/do-runner/inventory.d.ts +295 -0
- package/dist/do-runner/inventory.d.ts.map +1 -0
- package/dist/do-runner/inventory.js +800 -0
- package/dist/do-runner/inventory.js.map +1 -0
- package/dist/do-runner/notification-predicate.d.ts +8 -0
- package/dist/do-runner/notification-predicate.d.ts.map +1 -0
- package/dist/do-runner/notification-predicate.js +136 -0
- package/dist/do-runner/notification-predicate.js.map +1 -0
- package/dist/do-runner/run-lifecycle.d.ts +20 -1
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +67 -13
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-provenance.d.ts +38 -0
- package/dist/do-runner/run-provenance.d.ts.map +1 -0
- package/dist/do-runner/run-provenance.js +152 -0
- package/dist/do-runner/run-provenance.js.map +1 -0
- package/dist/do-runner/run-storage-tables.d.ts +2 -0
- package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
- package/dist/do-runner/run-storage-tables.js +4 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -0
- package/dist/do-runner/run-terminal-state.d.ts +29 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
- package/dist/do-runner/run-terminal-state.js +105 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +191 -46
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +994 -378
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +285 -0
- package/dist/do-runner/start-idempotency.d.ts.map +1 -0
- package/dist/do-runner/start-idempotency.js +994 -0
- package/dist/do-runner/start-idempotency.js.map +1 -0
- package/dist/do-runner/start-reservation-contract.d.ts +103 -0
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
- package/dist/do-runner/start-reservation-contract.js +338 -0
- package/dist/do-runner/start-reservation-contract.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +4 -11
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +8 -12
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/table-prefix.d.ts.map +1 -1
- package/dist/do-runner/table-prefix.js +2 -1
- package/dist/do-runner/table-prefix.js.map +1 -1
- package/dist/do-runner/testing.d.ts +3 -0
- package/dist/do-runner/testing.d.ts.map +1 -0
- package/dist/do-runner/testing.js +3 -0
- package/dist/do-runner/testing.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +2 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +14 -10
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
- package/dist/do-runner/workflow-snapshot-row.js +97 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +15 -5
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +64 -64
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +10 -7
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts +16 -0
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +181 -0
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +3 -0
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +36 -8
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +5 -6
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +49 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +409 -111
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +24 -14
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +29 -40
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +9 -3
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +5 -1
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +8 -4
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +14 -11
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +63 -2
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +167 -45
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-router.js +18 -9
- package/dist/host-kit/stream-router.js.map +1 -1
- package/dist/host-kit/thread-topology.d.ts +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +7 -3
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/internal-error-response.d.ts.map +1 -1
- package/dist/internal-error-response.js +16 -6
- package/dist/internal-error-response.js.map +1 -1
- package/dist/schedules/index.d.ts +1 -0
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +1 -7
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +38 -0
- package/dist/schedules/mutation-contract.d.ts.map +1 -0
- package/dist/schedules/mutation-contract.js +21 -0
- package/dist/schedules/mutation-contract.js.map +1 -0
- package/dist/schedules/router.d.ts +15 -8
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +170 -59
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +11 -5
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +570 -143
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/storage.d.ts +0 -7
- package/dist/schedules/storage.d.ts.map +1 -1
- package/dist/schedules/storage.js +0 -27
- package/dist/schedules/storage.js.map +1 -1
- package/dist/schedules/tick.d.ts +13 -0
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +66 -40
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/host-do.d.ts +12 -1
- package/dist/signal-providers/host-do.d.ts.map +1 -1
- package/dist/signal-providers/host-do.js +28 -3
- package/dist/signal-providers/host-do.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +15 -1
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +126 -113
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/d1-shared.d.ts +11 -8
- package/dist/signals/d1-shared.d.ts.map +1 -1
- package/dist/signals/d1-shared.js +1 -6
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/index.d.ts +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +1 -1
- package/dist/signals/index.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +109 -5
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +430 -46
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +14 -1
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +229 -18
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +6 -4
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/router.js +49 -84
- package/dist/signals/router.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +2 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +330 -83
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
- package/patches/@mastra__core@1.53.0.patch +54 -0
- package/scripts/seed-deployment-identity.mjs +34 -9
|
@@ -1,24 +1,17 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
// createFlowsafeWorker — the whole production-Worker skeleton the deploy
|
|
3
|
-
// template and the showcase host previously carried as near-byte copies:
|
|
4
|
-
// the /healthz → routers → 404 fetch pipeline over one actor resolver, the
|
|
5
|
-
// alarm-driven maintenance (deadline, sweep, purge, and optional schedule tick
|
|
6
|
-
// never share an invocation). Hosts stay thin shells: they supply workflows,
|
|
7
|
-
// their identity seam (buildVerifier), and their deployment-specific hooks —
|
|
8
|
-
// preRoutes (extra unauthenticated/authenticated mounts), beforeStart/
|
|
9
|
-
// beforeResume (e.g. a budget charge), notify (reviewer-facing transport), and
|
|
10
|
-
// extraPurgeDuties (e.g. a host-specific purge). Everything here is structural:
|
|
11
|
-
// host-kit never imports @cloudflare/workers-types.
|
|
12
2
|
import { APPROVAL_ROLES, createActorResolver, createApprovalRouter, createResourceOwnershipSchema, RESOURCE_OWNERSHIP_TABLE, trustAutomationPrincipal, } from '../approval-api/index.js';
|
|
13
3
|
import { createAuditProxyDurableObjectBinding, createAuditProxyQueue, } from '../audit-export/index.js';
|
|
4
|
+
import { parseRunRetentionCursor } from '../do-runner/d1-storage.js';
|
|
14
5
|
import { credentialsMatch } from '../do-runner/deployment-identity.js';
|
|
15
|
-
import {
|
|
6
|
+
import { InvalidMutationEpochError, normalizeMutationEpoch, } from '../do-runner/execution-admission.js';
|
|
7
|
+
import { assertExecutionFenceState, DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, DeploymentInventory, DoStatusError, deploymentIdentityHeaders, ensureDeploymentIdentityBindings, executionFenceFor, executionFenceReadingPayload, InvalidInventoryRequestError, isInventoryCategory, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, START_IDEMPOTENCY_TABLE, startIdempotencyFor, sweepExpiredRunDeadlines, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
|
|
16
8
|
import { validateTablePrefix } from '../do-runner/table-prefix.js';
|
|
9
|
+
import { readBoundedBody } from '../http-body.js';
|
|
17
10
|
import { abandonApprovalsForRun } from './approval-bridge.js';
|
|
18
11
|
import { bearerActorAuthenticator } from './bearer-auth.js';
|
|
19
12
|
import { createDoRunTopology, } from './do-run-topology.js';
|
|
20
13
|
import { numberVar, optionalNumberVar, selfDecisionPolicyVar, } from './env-vars.js';
|
|
21
|
-
import { approvalStoreFactoryFor, buildHostApprovalService, maintenancePrincipal, reconcileApprovalsOnStatusDetached, runApprovalRetentionPurge, runSlaSweepMaintenance, } from './host-approval-service.js';
|
|
14
|
+
import { approvalStoreFactoryFor, buildHostApprovalService, hostErrorText, maintenancePrincipal, reconcileApprovalsOnStatusDetached, runApprovalRetentionPurge, runSlaSweepMaintenance, } from './host-approval-service.js';
|
|
22
15
|
import { createHubTopology } from './hub-topology.js';
|
|
23
16
|
import { MAINTENANCE_RECEIPT_HEADER, mintMaintenanceReceipt, verifyAsymmetricMaintenanceCapability, verifyMaintenanceCapability, } from './maintenance-capability.js';
|
|
24
17
|
import { createRunRouter } from './run-router.js';
|
|
@@ -39,6 +32,8 @@ function buildConfiguredApprovalService(config, env, topology, options) {
|
|
|
39
32
|
notify: options.notify,
|
|
40
33
|
allowSelfDecision: options.allowSelfDecision,
|
|
41
34
|
stream: options.stream,
|
|
35
|
+
executionFence: options.executionFence,
|
|
36
|
+
workflowTablePrefix: options.workflowTablePrefix,
|
|
42
37
|
});
|
|
43
38
|
}
|
|
44
39
|
/**
|
|
@@ -55,6 +50,8 @@ export function createFlowsafeRunnerLifecycle(config, env, options = {}) {
|
|
|
55
50
|
: undefined;
|
|
56
51
|
const service = buildConfiguredApprovalService(config, env, topology, {
|
|
57
52
|
store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
|
|
53
|
+
executionFence: executionFenceForEnv(env),
|
|
54
|
+
workflowTablePrefix: (storageTablePrefix ?? '').toLowerCase(),
|
|
58
55
|
waitUntil: options.waitUntil,
|
|
59
56
|
notify: config.notify?.(env),
|
|
60
57
|
allowSelfDecision,
|
|
@@ -134,6 +131,10 @@ async function validateFleetChannelTopology(env) {
|
|
|
134
131
|
throw new Error('external fleet release has a direct audit queue binding');
|
|
135
132
|
}
|
|
136
133
|
}
|
|
134
|
+
const RETENTION_CURSOR_SEAM_REASON = 'retention purge requires advanceRetentionCursor';
|
|
135
|
+
function hasRetentionCursorSeam(context) {
|
|
136
|
+
return typeof context?.advanceRetentionCursor === 'function';
|
|
137
|
+
}
|
|
137
138
|
function json(payload, status = 200) {
|
|
138
139
|
return new Response(JSON.stringify(payload), {
|
|
139
140
|
status,
|
|
@@ -142,6 +143,53 @@ function json(payload, status = 200) {
|
|
|
142
143
|
}
|
|
143
144
|
const MAINTENANCE_ADMIN_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
|
|
144
145
|
const FLEET_SPEC_DIGEST_PATTERN = /^[a-f0-9]{64}$/;
|
|
146
|
+
async function authorizeAdminCredential(request, env, options) {
|
|
147
|
+
const { surface } = options;
|
|
148
|
+
const unavailable = (reason) => {
|
|
149
|
+
console.error(JSON.stringify({
|
|
150
|
+
type: 'config-error',
|
|
151
|
+
var: 'MAINTENANCE_ADMIN_SECRET',
|
|
152
|
+
reason,
|
|
153
|
+
}));
|
|
154
|
+
return {
|
|
155
|
+
authorized: false,
|
|
156
|
+
response: json({ error: `${surface} unavailable` }, 503),
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
const unauthenticated = () => ({
|
|
160
|
+
authorized: false,
|
|
161
|
+
response: json({ error: 'authentication required' }, 401),
|
|
162
|
+
});
|
|
163
|
+
const expected = env.MAINTENANCE_ADMIN_SECRET;
|
|
164
|
+
const delegating = options.delegateCapability;
|
|
165
|
+
if (expected === undefined) {
|
|
166
|
+
if (!delegating)
|
|
167
|
+
return unavailable(`${surface} is not configured`);
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
if (!MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
|
|
171
|
+
return unavailable(`${surface} is not configured`);
|
|
172
|
+
}
|
|
173
|
+
if (await credentialsMatch(expected, env.DEPLOYMENT_IDENTITY_SECRET)) {
|
|
174
|
+
return unavailable('maintenance and deployment identity credentials must differ');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const credential = bearerCredential(request);
|
|
178
|
+
const maximumCredentialLength = delegating ? 2_048 : 256;
|
|
179
|
+
if (!credential || credential.length > maximumCredentialLength) {
|
|
180
|
+
return unauthenticated();
|
|
181
|
+
}
|
|
182
|
+
if (!delegating &&
|
|
183
|
+
expected !== undefined &&
|
|
184
|
+
!(await credentialsMatch(credential, expected))) {
|
|
185
|
+
return unauthenticated();
|
|
186
|
+
}
|
|
187
|
+
return { authorized: true, credential, delegated: delegating };
|
|
188
|
+
}
|
|
189
|
+
/** The Bearer credential a request presents, if it presents a well-formed one. */
|
|
190
|
+
function bearerCredential(request) {
|
|
191
|
+
return request.headers.get('authorization')?.match(/^Bearer\s+(.+)$/i)?.[1];
|
|
192
|
+
}
|
|
145
193
|
async function maintenanceAdminResponse(request, env) {
|
|
146
194
|
const url = new URL(request.url);
|
|
147
195
|
const operation = url.pathname === '/admin/ensure-maintenance'
|
|
@@ -155,44 +203,12 @@ async function maintenanceAdminResponse(request, env) {
|
|
|
155
203
|
if (request.method !== expectedMethod) {
|
|
156
204
|
return json({ error: 'method not allowed' }, 405);
|
|
157
205
|
}
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
env.FLEET_MAINTENANCE_CAPABILITIES
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
reason: 'maintenance administration is not configured',
|
|
165
|
-
}));
|
|
166
|
-
return json({ error: 'maintenance administration unavailable' }, 503);
|
|
167
|
-
}
|
|
168
|
-
if (expected !== undefined &&
|
|
169
|
-
!MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
|
|
170
|
-
console.error(JSON.stringify({
|
|
171
|
-
type: 'config-error',
|
|
172
|
-
var: 'MAINTENANCE_ADMIN_SECRET',
|
|
173
|
-
reason: 'maintenance administration is not configured',
|
|
174
|
-
}));
|
|
175
|
-
return json({ error: 'maintenance administration unavailable' }, 503);
|
|
176
|
-
}
|
|
177
|
-
if (expected !== undefined &&
|
|
178
|
-
(await credentialsMatch(expected, env.DEPLOYMENT_IDENTITY_SECRET))) {
|
|
179
|
-
console.error(JSON.stringify({
|
|
180
|
-
type: 'config-error',
|
|
181
|
-
var: 'MAINTENANCE_ADMIN_SECRET',
|
|
182
|
-
reason: 'maintenance and deployment identity credentials must differ',
|
|
183
|
-
}));
|
|
184
|
-
return json({ error: 'maintenance administration unavailable' }, 503);
|
|
185
|
-
}
|
|
186
|
-
const actual = request.headers
|
|
187
|
-
.get('authorization')
|
|
188
|
-
?.match(/^Bearer\s+(.+)$/i)?.[1];
|
|
189
|
-
const maximumCredentialLength = expected === undefined ? 2_048 : 256;
|
|
190
|
-
if (!actual || actual.length > maximumCredentialLength) {
|
|
191
|
-
return json({ error: 'authentication required' }, 401);
|
|
192
|
-
}
|
|
193
|
-
if (expected !== undefined && !(await credentialsMatch(actual, expected))) {
|
|
194
|
-
return json({ error: 'authentication required' }, 401);
|
|
195
|
-
}
|
|
206
|
+
const gate = await authorizeAdminCredential(request, env, {
|
|
207
|
+
surface: 'maintenance administration',
|
|
208
|
+
delegateCapability: env.FLEET_MAINTENANCE_CAPABILITIES === 'required',
|
|
209
|
+
});
|
|
210
|
+
if (!gate.authorized)
|
|
211
|
+
return gate.response;
|
|
196
212
|
const deploymentSpecDigest = env.FLEET_SPEC_DIGEST;
|
|
197
213
|
if (deploymentSpecDigest !== undefined &&
|
|
198
214
|
!FLEET_SPEC_DIGEST_PATTERN.test(deploymentSpecDigest)) {
|
|
@@ -206,11 +222,18 @@ async function maintenanceAdminResponse(request, env) {
|
|
|
206
222
|
const id = env.MAINTENANCE.idFromName(MAINTENANCE_INSTANCE_NAME);
|
|
207
223
|
const response = await env.MAINTENANCE.get(id).fetch(`http://maintenance/${operation}`, {
|
|
208
224
|
method: expectedMethod,
|
|
209
|
-
|
|
210
|
-
|
|
225
|
+
// The gate's own verdict, not a second reading of the env var it decided
|
|
226
|
+
// on: a delegated request carries a capability the maintenance DO
|
|
227
|
+
// verifies, so this Worker relays the credential unchanged; anything else
|
|
228
|
+
// was authenticated HERE and travels on the deployment identity.
|
|
229
|
+
headers: gate.delegated
|
|
230
|
+
? { authorization: `Bearer ${gate.credential}` }
|
|
211
231
|
: deploymentIdentityHeaders(env.DEPLOYMENT_IDENTITY_SECRET),
|
|
212
232
|
});
|
|
213
|
-
|
|
233
|
+
// Nothing to enrich on the delegated path: the digest check below belongs to
|
|
234
|
+
// the deployment this Worker authenticated for, and a relayed response is the
|
|
235
|
+
// maintenance DO's own answer.
|
|
236
|
+
if (gate.delegated)
|
|
214
237
|
return response;
|
|
215
238
|
if (!response.ok || deploymentSpecDigest === undefined)
|
|
216
239
|
return response;
|
|
@@ -223,16 +246,222 @@ async function maintenanceAdminResponse(request, env) {
|
|
|
223
246
|
deploymentSpecDigest,
|
|
224
247
|
});
|
|
225
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* This composer's env-shaped view of the ONE per-database fence memo
|
|
251
|
+
* (do-runner/execution-fence.ts). Every call site here holds an `env` rather
|
|
252
|
+
* than a binding, so the unwrapping happens once instead of at each of them;
|
|
253
|
+
* the identity guarantee — admin route, approval service, and runner runtime
|
|
254
|
+
* all on the same store for the same database — belongs to the shared memo.
|
|
255
|
+
*/
|
|
256
|
+
function executionFenceForEnv(env) {
|
|
257
|
+
return executionFenceFor(env.DB);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* The same env-shaped view of the ONE per-database start-reservation memo
|
|
261
|
+
* (do-runner/start-idempotency.ts), for the same reason: the run router
|
|
262
|
+
* reserves here, and the runtime inside the run object settles there, and both
|
|
263
|
+
* must be the store built from THIS env's binding.
|
|
264
|
+
*/
|
|
265
|
+
function startIdempotencyForEnv(env) {
|
|
266
|
+
return startIdempotencyFor(env.DB);
|
|
267
|
+
}
|
|
268
|
+
const EXECUTION_FENCE_ADMIN_PATH = '/admin/execution-fence';
|
|
269
|
+
const EXECUTION_FENCE_ADMIN_MAX_BODY_BYTES = 4_096;
|
|
270
|
+
/**
|
|
271
|
+
* The deployment execution fence's control-plane surface, behind the SAME gate
|
|
272
|
+
* `maintenanceAdminResponse` uses (`authorizeAdminCredential`) — it is the same
|
|
273
|
+
* trust boundary (the provisioning TCB, docs/security-threat-model.md), and
|
|
274
|
+
* splitting the credential would only add a second secret an operator can get
|
|
275
|
+
* wrong.
|
|
276
|
+
*
|
|
277
|
+
* `GET` reports the state; `POST` moves it, compare-and-set on `expected`.
|
|
278
|
+
* Transition POLICY is the HOST's: this package enforces only the state
|
|
279
|
+
* vocabulary, the CAS, and the rule that entering 'proof-only' names a proof
|
|
280
|
+
* key. Which sequence of states a migration walks is the control plane's
|
|
281
|
+
* business, and hard-coding it here would freeze an operational procedure into
|
|
282
|
+
* a published package.
|
|
283
|
+
*
|
|
284
|
+
* Answers on a mis-provisioned deployment are NOT reachable: the identity gate
|
|
285
|
+
* 503s before this dispatch. Accepted — an operator whose bindings are wrong
|
|
286
|
+
* has a bigger problem than the fence, and relaxing the identity gate to serve
|
|
287
|
+
* this route would put an unverified database behind a control-plane write.
|
|
288
|
+
*/
|
|
289
|
+
async function executionFenceAdminResponse(request, env) {
|
|
290
|
+
const url = new URL(request.url);
|
|
291
|
+
if (url.pathname !== EXECUTION_FENCE_ADMIN_PATH)
|
|
292
|
+
return null;
|
|
293
|
+
if (request.method !== 'GET' && request.method !== 'POST') {
|
|
294
|
+
return json({ error: 'method not allowed' }, 405);
|
|
295
|
+
}
|
|
296
|
+
const gate = await authorizeAdminCredential(request, env, {
|
|
297
|
+
surface: 'execution fence administration',
|
|
298
|
+
// Unconfigured is 503, never open: the fence is the control that stops a
|
|
299
|
+
// deployment executing, so an unauthenticated caller must never move it.
|
|
300
|
+
// There is no capability-token relay behind this route to delegate to.
|
|
301
|
+
delegateCapability: false,
|
|
302
|
+
});
|
|
303
|
+
if (!gate.authorized)
|
|
304
|
+
return gate.response;
|
|
305
|
+
const fence = executionFenceForEnv(env);
|
|
306
|
+
try {
|
|
307
|
+
if (request.method === 'GET') {
|
|
308
|
+
return json(executionFenceReadingPayload(await fence.read()));
|
|
309
|
+
}
|
|
310
|
+
const raw = await readBoundedBody(request, EXECUTION_FENCE_ADMIN_MAX_BODY_BYTES, 'execution fence body exceeds limit');
|
|
311
|
+
if (!raw.ok) {
|
|
312
|
+
return json({ error: 'a JSON object body is required' }, raw.reason === 'payload-too-large' ? 413 : 400);
|
|
313
|
+
}
|
|
314
|
+
let parsed;
|
|
315
|
+
try {
|
|
316
|
+
parsed = raw.text === '' ? undefined : JSON.parse(raw.text);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
parsed = undefined;
|
|
320
|
+
}
|
|
321
|
+
if (parsed === null ||
|
|
322
|
+
typeof parsed !== 'object' ||
|
|
323
|
+
Array.isArray(parsed)) {
|
|
324
|
+
return json({ error: 'a JSON object body is required' }, 400);
|
|
325
|
+
}
|
|
326
|
+
const body = parsed;
|
|
327
|
+
const reading = await fence.transition({
|
|
328
|
+
expected: assertExecutionFenceState(body.expected, 'expected'),
|
|
329
|
+
next: assertExecutionFenceState(body.next, 'next'),
|
|
330
|
+
...(body.proofKey === undefined ? {} : { proofKey: body.proofKey }),
|
|
331
|
+
expectedMutationEpoch: body.expectedMutationEpoch,
|
|
332
|
+
expectedRevision: body.expectedRevision,
|
|
333
|
+
advanceMutationEpoch: body.advanceMutationEpoch,
|
|
334
|
+
});
|
|
335
|
+
return json(executionFenceReadingPayload(reading));
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
if (error instanceof DoStatusError) {
|
|
339
|
+
return json({
|
|
340
|
+
error: error.message,
|
|
341
|
+
...(error.reason === undefined ? {} : { reason: error.reason }),
|
|
342
|
+
}, error.status);
|
|
343
|
+
}
|
|
344
|
+
console.error(JSON.stringify({
|
|
345
|
+
type: 'execution-fence-admin-error',
|
|
346
|
+
reason: hostErrorText(error, true),
|
|
347
|
+
}));
|
|
348
|
+
return json({ error: 'execution fence administration failed' }, 500);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const INVENTORY_ADMIN_PATH = '/admin/inventory';
|
|
352
|
+
/**
|
|
353
|
+
* The deployment's drain-proof surface uses the same credential helper as the
|
|
354
|
+
* fence and maintenance routes. Their absent-secret policies differ:
|
|
355
|
+
* maintenance routes may delegate to a fleet capability; fence and inventory
|
|
356
|
+
* routes never do.
|
|
357
|
+
*
|
|
358
|
+
* WHAT IT IS FOR. An operator holds the fence in `draining` and needs to prove,
|
|
359
|
+
* with no side effects, that this deployment holds no executable or resumable
|
|
360
|
+
* work before locking it for a migration. Without such a proof the only
|
|
361
|
+
* available answer is a wait-and-hope, and a suspended run that survives it
|
|
362
|
+
* gets resumed by two deployments at once.
|
|
363
|
+
*
|
|
364
|
+
* HOW TO READ THE ANSWER — the contract the index response also states, in
|
|
365
|
+
* full, because this is the part a hurried operator skips:
|
|
366
|
+
*
|
|
367
|
+
* Each result is a point-in-time observation, not a snapshot. Rows can enter
|
|
368
|
+
* or leave `work` categories while draining admits work. An empty result
|
|
369
|
+
* cannot over-count work, and keyset pagination never skips a row that
|
|
370
|
+
* existed before the sweep started.
|
|
371
|
+
*
|
|
372
|
+
* The proof is TWO consecutive full sweeps, at least one 60-second
|
|
373
|
+
* RUN_OWNER_RECOVERY_DELAY_MS cadence apart, in which every `work` category
|
|
374
|
+
* comes back empty. One sweep cannot cover the window in which a run object
|
|
375
|
+
* has journalled its recovery key but not yet written its D1 owner row; two,
|
|
376
|
+
* spaced that far, can.
|
|
377
|
+
*
|
|
378
|
+
* An empty sweep from `draining` contributes to the two-sweep proof. After
|
|
379
|
+
* the transition to `migration-locked`, an empty post-lock re-sweep is
|
|
380
|
+
* conclusive because the lock refuses new work. A non-empty one means work is
|
|
381
|
+
* still outstanding, either because it entered after the proof or because
|
|
382
|
+
* the lock parked it before it finished. Return to `draining` and repeat the
|
|
383
|
+
* proof.
|
|
384
|
+
*
|
|
385
|
+
* `standing` categories (schedules, provider subscriptions) are reported for
|
|
386
|
+
* reconciliation and are never required to be empty: they are configuration a
|
|
387
|
+
* migration carries across.
|
|
388
|
+
*
|
|
389
|
+
* GET only. Every query underneath is a bare SELECT that never creates schema,
|
|
390
|
+
* so running this against a deployment about to be copied does not change what
|
|
391
|
+
* is being copied.
|
|
392
|
+
*/
|
|
393
|
+
async function inventoryAdminResponse(request, env, storageTablePrefix) {
|
|
394
|
+
const url = new URL(request.url);
|
|
395
|
+
if (url.pathname !== INVENTORY_ADMIN_PATH)
|
|
396
|
+
return null;
|
|
397
|
+
if (request.method !== 'GET') {
|
|
398
|
+
return json({ error: 'method not allowed' }, 405);
|
|
399
|
+
}
|
|
400
|
+
const gate = await authorizeAdminCredential(request, env, {
|
|
401
|
+
surface: 'deployment inventory',
|
|
402
|
+
// Unconfigured is 503, never open: this read enumerates every outstanding
|
|
403
|
+
// run, approval, and reservation on the deployment. There is no capability
|
|
404
|
+
// relay behind it to delegate to, either.
|
|
405
|
+
delegateCapability: false,
|
|
406
|
+
});
|
|
407
|
+
if (!gate.authorized)
|
|
408
|
+
return gate.response;
|
|
409
|
+
try {
|
|
410
|
+
const inventory = new DeploymentInventory(env.DB, {
|
|
411
|
+
...(storageTablePrefix === undefined
|
|
412
|
+
? {}
|
|
413
|
+
: { tablePrefix: storageTablePrefix }),
|
|
414
|
+
});
|
|
415
|
+
const category = url.searchParams.get('category');
|
|
416
|
+
if (category === null || category === '') {
|
|
417
|
+
return json(inventory.index());
|
|
418
|
+
}
|
|
419
|
+
if (!isInventoryCategory(category)) {
|
|
420
|
+
throw new InvalidInventoryRequestError(`unknown inventory category '${category}'`);
|
|
421
|
+
}
|
|
422
|
+
const rawLimit = url.searchParams.get('limit');
|
|
423
|
+
// Parsed here rather than coerced inside the store: `Number('abc')` is NaN
|
|
424
|
+
// and `Number('')` is 0, and both would otherwise reach the clamp as a
|
|
425
|
+
// number that means something the caller never asked for.
|
|
426
|
+
if (rawLimit !== null && !/^[0-9]{1,4}$/.test(rawLimit)) {
|
|
427
|
+
throw new InvalidInventoryRequestError('inventory limit must be a positive integer');
|
|
428
|
+
}
|
|
429
|
+
const cursor = url.searchParams.get('cursor');
|
|
430
|
+
return json(await inventory.read(category, {
|
|
431
|
+
...(cursor === null ? {} : { cursor }),
|
|
432
|
+
...(rawLimit === null ? {} : { limit: Number(rawLimit) }),
|
|
433
|
+
}));
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
if (error instanceof DoStatusError) {
|
|
437
|
+
return json({
|
|
438
|
+
error: error.message,
|
|
439
|
+
...(error.reason === undefined ? {} : { reason: error.reason }),
|
|
440
|
+
}, error.status);
|
|
441
|
+
}
|
|
442
|
+
console.error(JSON.stringify({
|
|
443
|
+
type: 'inventory-admin-error',
|
|
444
|
+
reason: hostErrorText(error, true),
|
|
445
|
+
}));
|
|
446
|
+
return json({ error: 'deployment inventory failed' }, 500);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
226
449
|
export function createFlowsafeWorker(config) {
|
|
450
|
+
const epochSource = config.mutationEpoch;
|
|
451
|
+
if (typeof epochSource !== 'function')
|
|
452
|
+
normalizeMutationEpoch(epochSource);
|
|
227
453
|
const storageTablePrefix = validateTablePrefix(config.storageTablePrefix, 'storageTablePrefix');
|
|
228
454
|
// Authenticate before constructing request-scoped services.
|
|
229
|
-
const buildResolve = (env, topology, waitUntil, notify, selfDecision, stream) => {
|
|
455
|
+
const buildResolve = (env, topology, waitUntil, notify, selfDecision, stream, mutationEpoch) => {
|
|
230
456
|
const base = createActorResolver({
|
|
457
|
+
mutationEpoch,
|
|
231
458
|
authenticate: bearerActorAuthenticator(config.buildVerifier(env)),
|
|
232
459
|
storeFactory: approvalStoreFactoryFor(env.DB, storageTablePrefix),
|
|
233
460
|
deploymentTag: env.DEPLOYMENT_TENANT,
|
|
234
461
|
buildService: (store) => buildConfiguredApprovalService(config, env, topology, {
|
|
235
462
|
store,
|
|
463
|
+
executionFence: executionFenceForEnv(env),
|
|
464
|
+
workflowTablePrefix: (storageTablePrefix ?? '').toLowerCase(),
|
|
236
465
|
waitUntil,
|
|
237
466
|
notify,
|
|
238
467
|
stream,
|
|
@@ -266,10 +495,10 @@ export function createFlowsafeWorker(config) {
|
|
|
266
495
|
selfDecisionCache.set(raw, policy);
|
|
267
496
|
return policy;
|
|
268
497
|
};
|
|
269
|
-
async function runPurgeMaintenance(env, trigger) {
|
|
498
|
+
async function runPurgeMaintenance(env, trigger, context) {
|
|
270
499
|
const failures = [];
|
|
271
500
|
const recordFailure = (surface, error) => {
|
|
272
|
-
const failure =
|
|
501
|
+
const failure = hostErrorText(error).slice(0, 256);
|
|
273
502
|
failures.push(`${surface}: ${failure}`);
|
|
274
503
|
console.error(JSON.stringify({
|
|
275
504
|
type: 'maintenance-error',
|
|
@@ -280,12 +509,31 @@ export function createFlowsafeWorker(config) {
|
|
|
280
509
|
};
|
|
281
510
|
let purged;
|
|
282
511
|
try {
|
|
512
|
+
const advanceCursor = context.advanceRetentionCursor;
|
|
513
|
+
const db = env.DB;
|
|
514
|
+
const prepare = db.prepare;
|
|
515
|
+
const batch = db.batch;
|
|
516
|
+
if (typeof prepare !== 'function' || typeof batch !== 'function') {
|
|
517
|
+
throw new Error('retention purge requires database.prepare() and batch()');
|
|
518
|
+
}
|
|
519
|
+
const retentionDb = {
|
|
520
|
+
prepare: prepare.bind(db),
|
|
521
|
+
batch: batch.bind(db),
|
|
522
|
+
};
|
|
523
|
+
const storedCursor = parseRunRetentionCursor(context.retentionCursor);
|
|
524
|
+
const cursor = storedCursor?.tablePrefix ===
|
|
525
|
+
(storageTablePrefix?.toLowerCase() ?? '') &&
|
|
526
|
+
storedCursor.startIdempotencyTable === START_IDEMPOTENCY_TABLE
|
|
527
|
+
? storedCursor
|
|
528
|
+
: undefined;
|
|
283
529
|
const artifactStore = config.artifactStore?.(env);
|
|
284
530
|
// The resource registry is lazy like Mastra's snapshot table. Retention
|
|
285
531
|
// may be the first resource-aware operation in a fresh deployment, so
|
|
286
532
|
// initialize it before asking the atomic purge to reference it.
|
|
287
|
-
await createResourceOwnershipSchema(
|
|
288
|
-
purged = await purgeExpiredWorkflowRuns(
|
|
533
|
+
await createResourceOwnershipSchema(retentionDb);
|
|
534
|
+
purged = await purgeExpiredWorkflowRuns(retentionDb, {
|
|
535
|
+
cursor,
|
|
536
|
+
advanceCursor,
|
|
289
537
|
// allowZero: RUN_RETENTION_DAYS=0 means "purge terminal runs now".
|
|
290
538
|
ttlMs: numberVar(env.RUN_RETENTION_DAYS, 30, 'RUN_RETENTION_DAYS', {
|
|
291
539
|
allowZero: true,
|
|
@@ -294,23 +542,24 @@ export function createFlowsafeWorker(config) {
|
|
|
294
542
|
60 *
|
|
295
543
|
60 *
|
|
296
544
|
1000,
|
|
297
|
-
// Pairs each expired run's R2 artifacts with its snapshot-row deletion
|
|
298
|
-
// (artifacts BEFORE the row — the row is the only record of their keys).
|
|
299
|
-
// Undefined on hosts that wire no R2, so the purge stays byte-identical.
|
|
300
545
|
artifactStore,
|
|
301
546
|
tablePrefix: storageTablePrefix,
|
|
302
|
-
// Snapshot + owner release share one D1 transaction, so retention
|
|
303
|
-
// cannot leave unbounded run-ownership tombstones or expose a live row
|
|
304
|
-
// without its authorization record.
|
|
305
547
|
resourceOwnerTable: RESOURCE_OWNERSHIP_TABLE,
|
|
548
|
+
startIdempotencyTable: START_IDEMPOTENCY_TABLE,
|
|
549
|
+
...(env.START_IDEMPOTENCY_RETENTION_DAYS === undefined
|
|
550
|
+
? {}
|
|
551
|
+
: {
|
|
552
|
+
startIdempotencyTtlMs: numberVar(env.START_IDEMPOTENCY_RETENTION_DAYS, 30, 'START_IDEMPOTENCY_RETENTION_DAYS', { allowZero: true }) *
|
|
553
|
+
24 *
|
|
554
|
+
60 *
|
|
555
|
+
60 *
|
|
556
|
+
1000,
|
|
557
|
+
}),
|
|
306
558
|
});
|
|
307
559
|
}
|
|
308
560
|
catch (error) {
|
|
309
561
|
recordFailure('retention-purge', error);
|
|
310
562
|
}
|
|
311
|
-
// Own containment (inside runApprovalRetentionPurge), same isolation as
|
|
312
|
-
// the snapshot purge above: a failure in any one purge duty must never
|
|
313
|
-
// stop the others.
|
|
314
563
|
const approvalPurge = await runApprovalRetentionPurge({
|
|
315
564
|
store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
|
|
316
565
|
retentionDays: env.APPROVAL_RETENTION_DAYS,
|
|
@@ -320,11 +569,6 @@ export function createFlowsafeWorker(config) {
|
|
|
320
569
|
failures.push(`approval-retention-purge: ${approvalPurge.error}`);
|
|
321
570
|
}
|
|
322
571
|
const approvalsPurged = approvalPurge.ok ? approvalPurge.value : undefined;
|
|
323
|
-
// Agent-memory thread TTL, opt-in.
|
|
324
|
-
// Its OWN try/catch, like every sibling duty above and below: isolating one
|
|
325
|
-
// loop while a sibling shares its failure is a defect this codebase has
|
|
326
|
-
// already shipped once — a wedged thread purge must cost the run-snapshot
|
|
327
|
-
// purge, the approval purge, and the extra duties nothing.
|
|
328
572
|
let threadsPurged;
|
|
329
573
|
let threadMessagesPurged;
|
|
330
574
|
// optionalNumberVar, not numberVar: this var GATES the duty rather than
|
|
@@ -346,9 +590,6 @@ export function createFlowsafeWorker(config) {
|
|
|
346
590
|
recordFailure('thread-retention-purge', error);
|
|
347
591
|
}
|
|
348
592
|
}
|
|
349
|
-
// Background-task TTL cleanup (Track B, opt-in). Its OWN try/catch, like
|
|
350
|
-
// every sibling duty: a wedged background-task purge must cost the
|
|
351
|
-
// run-snapshot, approval, and thread purges nothing.
|
|
352
593
|
let backgroundTasksPurged;
|
|
353
594
|
if (config.backgroundTasks) {
|
|
354
595
|
try {
|
|
@@ -362,8 +603,6 @@ export function createFlowsafeWorker(config) {
|
|
|
362
603
|
recordFailure('background-task-purge', error);
|
|
363
604
|
}
|
|
364
605
|
}
|
|
365
|
-
// Track C notification TTL (opt-in). Its OWN try/catch, like every sibling
|
|
366
|
-
// duty. optionalNumberVar (GATES the duty; unset/garbage => do not delete).
|
|
367
606
|
let notificationsPurged;
|
|
368
607
|
const notificationRetentionDays = optionalNumberVar(env.NOTIFICATION_RETENTION_DAYS, 'NOTIFICATION_RETENTION_DAYS', { allowZero: true });
|
|
369
608
|
if (notificationRetentionDays !== undefined) {
|
|
@@ -377,7 +616,6 @@ export function createFlowsafeWorker(config) {
|
|
|
377
616
|
recordFailure('notification-purge', error);
|
|
378
617
|
}
|
|
379
618
|
}
|
|
380
|
-
// Track C thread-state TTL (opt-in). Same isolation + opt-in posture.
|
|
381
619
|
let threadStatePurged;
|
|
382
620
|
const threadStateRetentionDays = optionalNumberVar(env.THREAD_STATE_RETENTION_DAYS, 'THREAD_STATE_RETENTION_DAYS', { allowZero: true });
|
|
383
621
|
if (threadStateRetentionDays !== undefined) {
|
|
@@ -391,9 +629,6 @@ export function createFlowsafeWorker(config) {
|
|
|
391
629
|
recordFailure('thread-state-purge', error);
|
|
392
630
|
}
|
|
393
631
|
}
|
|
394
|
-
// Track D schedule-trigger history TTL (opt-in). Same isolation + opt-in
|
|
395
|
-
// posture. Only the fire HISTORY expires; schedule config rows are reaped
|
|
396
|
-
// only at deployment teardown.
|
|
397
632
|
let scheduleTriggersPurged;
|
|
398
633
|
const scheduleTriggerRetentionDays = optionalNumberVar(env.SCHEDULE_TRIGGER_RETENTION_DAYS, 'SCHEDULE_TRIGGER_RETENTION_DAYS', { allowZero: true });
|
|
399
634
|
if (scheduleTriggerRetentionDays !== undefined) {
|
|
@@ -434,7 +669,7 @@ export function createFlowsafeWorker(config) {
|
|
|
434
669
|
? { ok: true, value: undefined }
|
|
435
670
|
: { ok: false, error: failures.join('; ') };
|
|
436
671
|
}
|
|
437
|
-
//
|
|
672
|
+
// Schedule tick — its OWN failure-isolated duty (own try/catch, own log
|
|
438
673
|
// line). A wedged fire pass must cost the other duties nothing, and vice
|
|
439
674
|
// versa (the same failure-isolation rationale).
|
|
440
675
|
async function runScheduleTickDuty(env, trigger) {
|
|
@@ -459,7 +694,7 @@ export function createFlowsafeWorker(config) {
|
|
|
459
694
|
return { ok: true, value: undefined };
|
|
460
695
|
}
|
|
461
696
|
catch (error) {
|
|
462
|
-
const failure =
|
|
697
|
+
const failure = hostErrorText(error);
|
|
463
698
|
console.error(JSON.stringify({
|
|
464
699
|
type: 'schedule-tick-error',
|
|
465
700
|
trigger,
|
|
@@ -498,7 +733,7 @@ export function createFlowsafeWorker(config) {
|
|
|
498
733
|
return { ok: true, value: undefined };
|
|
499
734
|
}
|
|
500
735
|
catch (error) {
|
|
501
|
-
const failure =
|
|
736
|
+
const failure = hostErrorText(error);
|
|
502
737
|
console.error(JSON.stringify({
|
|
503
738
|
type: 'deadline-sweep-error',
|
|
504
739
|
trigger,
|
|
@@ -510,6 +745,7 @@ export function createFlowsafeWorker(config) {
|
|
|
510
745
|
return {
|
|
511
746
|
async fetch(request, env, ctx) {
|
|
512
747
|
try {
|
|
748
|
+
const mutationEpoch = normalizeMutationEpoch(typeof epochSource === 'function' ? epochSource(env) : epochSource);
|
|
513
749
|
await ensureDeploymentIdentityBindings(env);
|
|
514
750
|
await validateFleetChannelTopology(env);
|
|
515
751
|
const url = new URL(request.url);
|
|
@@ -519,12 +755,25 @@ export function createFlowsafeWorker(config) {
|
|
|
519
755
|
const maintenanceAdmin = await maintenanceAdminResponse(request, env);
|
|
520
756
|
if (maintenanceAdmin)
|
|
521
757
|
return maintenanceAdmin;
|
|
758
|
+
// The execution fence's control plane, beside the maintenance admin
|
|
759
|
+
// routes and ahead of every tenant router: it must answer while the
|
|
760
|
+
// deployment is refusing tenant traffic, which is the whole state it
|
|
761
|
+
// exists to report and clear.
|
|
762
|
+
const fenceAdmin = await executionFenceAdminResponse(request, env);
|
|
763
|
+
if (fenceAdmin)
|
|
764
|
+
return fenceAdmin;
|
|
765
|
+
// Beside the fence for the same reason: the drain proof is read WHILE
|
|
766
|
+
// the deployment is refusing tenant traffic, so it must not sit behind
|
|
767
|
+
// a router that a drain is trying to empty.
|
|
768
|
+
const inventoryAdmin = await inventoryAdminResponse(request, env, storageTablePrefix);
|
|
769
|
+
if (inventoryAdmin)
|
|
770
|
+
return inventoryAdmin;
|
|
522
771
|
const waitUntil = (promise) => ctx.waitUntil(promise);
|
|
523
772
|
const topology = createDoRunTopology(env.RUNNER, env.DEPLOYMENT_IDENTITY_SECRET);
|
|
524
773
|
const notify = config.notify?.(env);
|
|
525
774
|
const selfDecision = parseSelfDecision(env);
|
|
526
775
|
// Fetch-scope live fan-out sink: present iff a hub is bound (streaming is
|
|
527
|
-
// opt-in
|
|
776
|
+
// opt-in). Each publish rides ctx.waitUntil and is
|
|
528
777
|
// contained — a failed fan-out logs and never fails the mutation.
|
|
529
778
|
const hub = env.HUB;
|
|
530
779
|
let streamSink;
|
|
@@ -532,10 +781,10 @@ export function createFlowsafeWorker(config) {
|
|
|
532
781
|
const hubTopology = createHubTopology(hub, env.DEPLOYMENT_IDENTITY_SECRET);
|
|
533
782
|
streamSink = (event) => waitUntil(hubTopology.publish(event).catch((error) => console.error(JSON.stringify({
|
|
534
783
|
type: 'stream-publish-error',
|
|
535
|
-
reason: error
|
|
784
|
+
reason: hostErrorText(error, true),
|
|
536
785
|
}))));
|
|
537
786
|
}
|
|
538
|
-
const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision, streamSink);
|
|
787
|
+
const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision, streamSink, mutationEpoch);
|
|
539
788
|
if (config.preRoutes) {
|
|
540
789
|
const preResponse = await config.preRoutes(request, env, ctx, {
|
|
541
790
|
resolve,
|
|
@@ -550,7 +799,7 @@ export function createFlowsafeWorker(config) {
|
|
|
550
799
|
if (agentResponse)
|
|
551
800
|
return agentResponse;
|
|
552
801
|
}
|
|
553
|
-
// Optional stream stage
|
|
802
|
+
// Optional stream stage: mounted only when BOTH the hub
|
|
554
803
|
// binding and the ticket secret are present. Every route is under
|
|
555
804
|
// /api/stream/, so it composes ahead of the approval router without
|
|
556
805
|
// touching the /api/* run_worker_first entry.
|
|
@@ -566,29 +815,29 @@ export function createFlowsafeWorker(config) {
|
|
|
566
815
|
if (streamResponse)
|
|
567
816
|
return streamResponse;
|
|
568
817
|
}
|
|
569
|
-
// Optional
|
|
570
|
-
//
|
|
571
|
-
//
|
|
818
|
+
// Optional signal stage: the host-built createSignalRouter closes over
|
|
819
|
+
// THIS request's resolver. `/api/threads/*` composes ahead of
|
|
820
|
+
// approvals/runs without overlap. Absent seam => unmounted.
|
|
572
821
|
const signalRouter = config.buildSignalRouter?.(resolve, env);
|
|
573
822
|
if (signalRouter) {
|
|
574
823
|
const signalResponse = await signalRouter(request);
|
|
575
824
|
if (signalResponse)
|
|
576
825
|
return signalResponse;
|
|
577
826
|
}
|
|
578
|
-
// Optional
|
|
579
|
-
//
|
|
580
|
-
//
|
|
581
|
-
//
|
|
827
|
+
// Optional goal stage: the host-built createObjectiveRouter closes over
|
|
828
|
+
// THIS request's resolver. `/api/threads/:threadId/goal` composes after
|
|
829
|
+
// signals and ahead of approvals/runs. Absent seam => unmounted and
|
|
830
|
+
// byte-identical.
|
|
582
831
|
const objectiveRouter = config.buildObjectiveRouter?.(resolve, env);
|
|
583
832
|
if (objectiveRouter) {
|
|
584
833
|
const objectiveResponse = await objectiveRouter(request);
|
|
585
834
|
if (objectiveResponse)
|
|
586
835
|
return objectiveResponse;
|
|
587
836
|
}
|
|
588
|
-
// Optional
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
//
|
|
837
|
+
// Optional schedule CRUD stage: the host-built createScheduleRouter
|
|
838
|
+
// closes over THIS request's resolver. `/api/schedules/*` composes
|
|
839
|
+
// after goals and ahead of approvals/runs. Absent seam => unmounted
|
|
840
|
+
// and byte-identical.
|
|
592
841
|
const scheduleRouter = config.buildScheduleRouter?.(resolve, env);
|
|
593
842
|
if (scheduleRouter) {
|
|
594
843
|
const scheduleResponse = await scheduleRouter(request);
|
|
@@ -608,14 +857,25 @@ export function createFlowsafeWorker(config) {
|
|
|
608
857
|
status: topology.status,
|
|
609
858
|
resume: topology.resume,
|
|
610
859
|
terminate: topology.terminate,
|
|
860
|
+
// Both halves come from this env's own bindings: the store from the
|
|
861
|
+
// per-database memo (so the runtime inside the run object settles the
|
|
862
|
+
// very rows this router reserved), and the probe from the same DO
|
|
863
|
+
// topology every other run operation travels through (so "is it
|
|
864
|
+
// live?" is asked of the one object that could be running it).
|
|
865
|
+
startIdempotency: {
|
|
866
|
+
store: startIdempotencyForEnv(env),
|
|
867
|
+
live: topology.startLiveness,
|
|
868
|
+
persistedStart: topology.persistedStart,
|
|
869
|
+
executionFence: executionFenceForEnv(env),
|
|
870
|
+
},
|
|
611
871
|
beforeStart: beforeStart
|
|
612
|
-
? (context, workflowId, inputData) => beforeStart(context, env, workflowId, inputData)
|
|
872
|
+
? (context, workflowId, inputData, requestContext) => beforeStart(context, env, workflowId, inputData, requestContext)
|
|
613
873
|
: undefined,
|
|
614
874
|
beforeResume: beforeResume
|
|
615
875
|
? (context, workflowId, runId, body) => beforeResume(context, env, workflowId, runId, body)
|
|
616
876
|
: undefined,
|
|
617
|
-
//
|
|
618
|
-
// detach + reconcile-error logging.
|
|
877
|
+
// Self-healing approval reconciliation is waitUntil-detached; the
|
|
878
|
+
// shared wrapper owns the detach + reconcile-error logging.
|
|
619
879
|
reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemPrincipalId, waitUntil),
|
|
620
880
|
})(request);
|
|
621
881
|
if (runResponse)
|
|
@@ -626,17 +886,20 @@ export function createFlowsafeWorker(config) {
|
|
|
626
886
|
if (error instanceof DeploymentIdentityError) {
|
|
627
887
|
console.error(JSON.stringify({
|
|
628
888
|
type: 'deployment-identity-error',
|
|
629
|
-
reason: error
|
|
889
|
+
reason: hostErrorText(error, true),
|
|
630
890
|
}));
|
|
631
891
|
return json({ error: 'deployment unavailable' }, 503);
|
|
632
892
|
}
|
|
893
|
+
if (error instanceof InvalidMutationEpochError) {
|
|
894
|
+
return json({ error: error.message, reason: error.reason }, error.status);
|
|
895
|
+
}
|
|
633
896
|
// Backstop: a mounted router (or any handler fault) that THROWS before
|
|
634
897
|
// returning a Response — e.g. a future unguarded path decode — is
|
|
635
898
|
// contained as a generic 500 here rather than rejecting out of fetch()
|
|
636
899
|
// as an unhandled promise. Never surface error.message to the client.
|
|
637
900
|
console.error(JSON.stringify({
|
|
638
901
|
type: 'worker-fetch-error',
|
|
639
|
-
reason: error
|
|
902
|
+
reason: hostErrorText(error, true),
|
|
640
903
|
}));
|
|
641
904
|
return json({ error: 'internal error' }, 500);
|
|
642
905
|
}
|
|
@@ -666,12 +929,28 @@ export function createFlowsafeWorker(config) {
|
|
|
666
929
|
});
|
|
667
930
|
}
|
|
668
931
|
if (duty === 'purge') {
|
|
669
|
-
|
|
932
|
+
if (!hasRetentionCursorSeam(context)) {
|
|
933
|
+
// The same refusal the tick duty makes below for an unwired
|
|
934
|
+
// builder: the cursor seam is part of the purge's wiring, not one
|
|
935
|
+
// of its surfaces, so a host that omits it gets the misconfig
|
|
936
|
+
// named rather than its remaining surfaces purged and the run
|
|
937
|
+
// retention reported as failed. MaintenancePurgeDutyContext
|
|
938
|
+
// requires the seam; this is the check for hosts types do not
|
|
939
|
+
// reach.
|
|
940
|
+
console.error(JSON.stringify({
|
|
941
|
+
type: 'config-error',
|
|
942
|
+
var: 'maintenance.purge.advanceRetentionCursor',
|
|
943
|
+
trigger: duty,
|
|
944
|
+
reason: RETENTION_CURSOR_SEAM_REASON,
|
|
945
|
+
}));
|
|
946
|
+
return { ok: false, error: RETENTION_CURSOR_SEAM_REASON };
|
|
947
|
+
}
|
|
948
|
+
return await runPurgeMaintenance(env, duty, context);
|
|
670
949
|
}
|
|
671
950
|
return await runScheduleTickDuty(env, duty);
|
|
672
951
|
}
|
|
673
952
|
catch (error) {
|
|
674
|
-
const failure =
|
|
953
|
+
const failure = hostErrorText(error);
|
|
675
954
|
console.error(JSON.stringify({
|
|
676
955
|
type: 'maintenance-error',
|
|
677
956
|
surface: `${duty}-duty`,
|
|
@@ -686,6 +965,7 @@ export function createFlowsafeWorker(config) {
|
|
|
686
965
|
const MAINTENANCE_HEALTH_KEY = 'flowsafe:maintenance-health:v1';
|
|
687
966
|
const MAINTENANCE_NONCES_KEY = 'flowsafe:maintenance-nonces:v1';
|
|
688
967
|
const MAINTENANCE_DEADLINE_CURSOR_KEY = 'flowsafe:maintenance-deadline-cursor:v1';
|
|
968
|
+
const MAINTENANCE_RUN_RETENTION_CURSOR_KEY = 'flowsafe:maintenance-run-retention-cursor:v1';
|
|
689
969
|
const DUTY_ORDER = ['deadline', 'sweep', 'purge', 'tick'];
|
|
690
970
|
/** Build the fixed-name maintenance Durable Object class for one host. */
|
|
691
971
|
export function createFlowsafeMaintenanceDurableObject(config) {
|
|
@@ -829,6 +1109,10 @@ export function createFlowsafeMaintenanceDurableObject(config) {
|
|
|
829
1109
|
}
|
|
830
1110
|
if (!capability)
|
|
831
1111
|
return undefined;
|
|
1112
|
+
if (this.#env.FLEET_RESOURCE_ROLE === 'platform-catalog' &&
|
|
1113
|
+
(capability.scriptName !== this.#env.FLEET_DEPLOYMENT_SCRIPT ||
|
|
1114
|
+
capability.specDigest !== this.#env.FLEET_SPEC_DIGEST))
|
|
1115
|
+
return undefined;
|
|
832
1116
|
if (operation === 'maintenance-status')
|
|
833
1117
|
return capability;
|
|
834
1118
|
const nowSeconds = Math.floor(Date.now() / 1_000);
|
|
@@ -897,7 +1181,7 @@ export function createFlowsafeMaintenanceDurableObject(config) {
|
|
|
897
1181
|
}
|
|
898
1182
|
console.error(JSON.stringify({
|
|
899
1183
|
type: 'maintenance-do-error',
|
|
900
|
-
reason: error
|
|
1184
|
+
reason: hostErrorText(error, true),
|
|
901
1185
|
}));
|
|
902
1186
|
return json({ error: 'internal error' }, 500);
|
|
903
1187
|
}
|
|
@@ -925,17 +1209,31 @@ export function createFlowsafeMaintenanceDurableObject(config) {
|
|
|
925
1209
|
setNextAt(health, duty, advancePast(dueAt, interval, now));
|
|
926
1210
|
const followUpAt = nextAlarmAt(health, intervals);
|
|
927
1211
|
await this.#persistAndArm(health, hasDueDuty(health, intervals, now) ? now : followUpAt);
|
|
928
|
-
|
|
1212
|
+
// Each duty carries the cursor pair it owns, so the call sits inside the
|
|
1213
|
+
// branch that builds it: the purge seam is required by its context type,
|
|
1214
|
+
// which a single call over the whole duty union cannot satisfy.
|
|
1215
|
+
let outcome;
|
|
929
1216
|
if (duty === 'deadline') {
|
|
930
1217
|
const deadlineCursor = await this.#state.storage.get(MAINTENANCE_DEADLINE_CURSOR_KEY);
|
|
931
|
-
|
|
1218
|
+
outcome = await worker.runMaintenanceDuty(duty, this.#env, {
|
|
932
1219
|
...(deadlineCursor ? { deadlineCursor } : {}),
|
|
933
1220
|
advanceDeadlineCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
|
|
934
1221
|
await transaction.put(MAINTENANCE_DEADLINE_CURSOR_KEY, cursor);
|
|
935
1222
|
}),
|
|
936
|
-
};
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
else if (duty === 'purge') {
|
|
1226
|
+
const retentionCursor = await this.#state.storage.get(MAINTENANCE_RUN_RETENTION_CURSOR_KEY);
|
|
1227
|
+
outcome = await worker.runMaintenanceDuty(duty, this.#env, {
|
|
1228
|
+
...(retentionCursor === undefined ? {} : { retentionCursor }),
|
|
1229
|
+
advanceRetentionCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
|
|
1230
|
+
await transaction.put(MAINTENANCE_RUN_RETENTION_CURSOR_KEY, cursor);
|
|
1231
|
+
}),
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
else {
|
|
1235
|
+
outcome = await worker.runMaintenanceDuty(duty, this.#env);
|
|
937
1236
|
}
|
|
938
|
-
const outcome = await worker.runMaintenanceDuty(duty, this.#env, context);
|
|
939
1237
|
await this.#recordOutcome(duty, Date.now(), outcome);
|
|
940
1238
|
}
|
|
941
1239
|
};
|