@makaio/framework 1.0.0-dev-1788511348215 → 1.0.0-dev-1788721567504
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/dist/.makaio-build.json +2 -2
- package/dist/attempt-record-codec-BORASgzn.mjs +1 -0
- package/dist/bus/index.d.mts +19 -19
- package/dist/bus/index.mjs +1 -1
- package/dist/{context-resolution-841T7jBI.d.mts → context-resolution-CoKFKIqz.d.mts} +3 -3
- package/dist/contracts/adapter/index.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +2 -2
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +3 -3
- package/dist/contracts/index.d.mts +616 -122
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +2 -2
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/shared/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/{execution-attempt-repository-DY4KTptE.d.mts → execution-attempt-repository-CRdrgou3.d.mts} +512 -3
- package/dist/{index-jxPncqWZ2.d.mts → index--Ws52sWV2.d.mts} +4 -4
- package/dist/{index-Wbd_syN2.d.mts → index-37_b--BH.d.mts} +11 -11
- package/dist/{index-6trZYnUP2.d.mts → index-8NdPPzUh2.d.mts} +12 -12
- package/dist/{index-B-3I98nw.d.mts → index-AdcDBUnc.d.mts} +95 -95
- package/dist/{index-C6aSnO8m.d.mts → index-BJdkVFX9.d.mts} +288 -24
- package/dist/{index-DXtQRehh.d.mts → index-BKIxdzIw.d.mts} +11 -11
- package/dist/{index-CmwAJ8-5.d.mts → index-CFI6FxC7.d.mts} +1 -1
- package/dist/{index-DI2lS7VT.d.mts → index-CVcG4Q3X.d.mts} +5 -5
- package/dist/{index-DHH-93YD.d.mts → index-CYjgoYeX.d.mts} +1 -1
- package/dist/{index-CDud4NAm.d.mts → index-CxwqnZpT.d.mts} +75 -75
- package/dist/{index-BkbnC65b.d.mts → index-CyWGSxrs.d.mts} +291 -291
- package/dist/{index-C146Eq_J.d.mts → index-D1wTWSLR.d.mts} +327 -327
- package/dist/{index-Bqk0pJBQ2.d.mts → index-DBD_oFEt2.d.mts} +1 -1
- package/dist/{index-BmilK-co2.d.mts → index-DV38-klA2.d.mts} +12 -36
- package/dist/{index-DNI6UF9h.d.mts → index-I5a37JCm.d.mts} +4 -4
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{namespace-l-HG1rLF.d.mts → namespace-Bo94cenp.d.mts} +136 -136
- package/dist/{namespace-DknCutQZ.d.mts → namespace-CPm9dhi2.d.mts} +2 -2
- package/dist/{namespace-BNp7n_gu.d.mts → namespace-CsnrP8AD.d.mts} +3 -3
- package/dist/{namespace-BGRHcrmp.d.mts → namespace-CstawJgN.d.mts} +2 -2
- package/dist/{package-efR90JGe.d.mts → package-DkZmsdCd.d.mts} +49 -1
- package/dist/package-UemD2NWn.mjs +7 -0
- package/dist/package.json +1 -1
- package/dist/runtime-node/index.d.mts +2 -2
- package/dist/runtime-node/index.mjs +24 -24
- package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
- package/dist/runtime-node/workflow-worker/index.d.mts +2 -2
- package/dist/runtime-node/workflow-worker/index.mjs +1 -1
- package/dist/runtime-node/workflow-worker/worker-entry.d.mts +49 -9
- package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
- package/dist/runtime-registration-client-BTtFpt_k.mjs +1 -0
- package/dist/{schemas-D7EeKBDJ.d.mts → schemas-CJKHYluy.d.mts} +13 -13
- package/dist/{schemas-C1mxTfd7.d.mts → schemas-CenET9Cq.d.mts} +1 -1
- package/dist/{schemas-D7ScxLrf.d.mts → schemas-DTJtS14K.d.mts} +136 -136
- package/dist/services/adapter-runtime/index.d.mts +3 -3
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +1 -1
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/index.d.mts +86 -86
- package/dist/services/session/index.d.mts +1 -1
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +10 -10
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/subagent-template/index.d.mts +2 -2
- package/dist/services/subagent-template/namespace.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/{transition-D3zUBTPc.d.mts → transition-DxsrTsn4.d.mts} +1 -1
- package/dist/{types-DcxBYlPA.d.mts → types-Czdm5op1.d.mts} +306 -306
- package/dist/{view-builder-B0j9p5C0.d.mts → view-builder-D-Wz_l_B.d.mts} +1 -1
- package/dist/worker-DlRdLf2d.mjs +1 -0
- package/dist/workflow-engine/execution-attempt-repository.d.mts +2 -2
- package/dist/workflow-engine/execution-attempt-repository.mjs +1 -1
- package/dist/workflow-engine/index.d.mts +205 -70
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/dist/workflow-engine/testing/index.d.mts +55 -3
- package/dist/workflow-engine/testing/index.mjs +1 -1
- package/dist/workflow-engine/testing/sqlite.d.mts +1 -1
- package/dist/workflow-engine/testing/sqlite.mjs +106 -38
- package/dist/workflow-worker-DjUfKshi.mjs +1 -0
- package/package.json +1 -1
- package/dist/attempt-record-codec-dC9LSFUE.mjs +0 -1
- package/dist/await-trigger-Bkg2BQfg.mjs +0 -1
- package/dist/package-Cgjpm9om.mjs +0 -7
- package/dist/worker-CARV52hT.mjs +0 -1
- package/dist/workflow-worker-Dul-wcOR.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as e,H as t,M as n,P as r,T as i,W as a,X as o,et as s,g as c,it as l,j as u,ot as d}from"../authority-state-bootstrap-eitx6Ukn.mjs";import{a as f,c as p,d as m,f as h,
|
|
1
|
+
import{B as e,H as t,M as n,P as r,T as i,W as a,X as o,et as s,g as c,it as l,j as u,ot as d}from"../authority-state-bootstrap-eitx6Ukn.mjs";import{a as f,c as p,d as m,f as h,h as g,i as _,l as v,m as y,n as b,o as x,p as S,r as C,s as w,t as T,u as E}from"../package-UemD2NWn.mjs";import{assertWorkflowTriggerPayload as D,compileWorkflowTriggerBindingFilter as O}from"./workflow-trigger-binding-consumer.mjs";import{ATTEMPT_OPERATION_START_GATES as k,DuplicateExecutionAttemptError as A,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as j,EXECUTION_ATTEMPT_STATUSES as M,decodeDurableOutcome as N,durableOutcome as P,sameAllocationRef as F,sameDurableOutcome as I}from"./execution-attempt-repository.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as L}from"./provider-operation.mjs";import{JsonValueSchema as R,WorkflowFrameStateSchema as z}from"@makaio/framework/contracts";const B=new Set([...z.shape.status.options]);function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function H(e){if(!V(e))return!1;for(let t of Object.values(e))if(!V(t)||typeof t.status!=`string`||!B.has(t.status)||`result`in t&&t.result!==void 0&&!R.safeParse(t.result).success)return!1;return!0}function U(e){let t={trigger:V(e.trigger)?e.trigger:{},steps:H(e.steps)?e.steps:{},inputs:R.safeParse(e.inputs).success?e.inputs:{}};return`item`in e&&(t.item=e.item),typeof e.index==`number`&&(t.index=e.index),t}export{k as ATTEMPT_OPERATION_START_GATES,A as DuplicateExecutionAttemptError,j as EXECUTION_ATTEMPT_SETTLEMENT_KINDS,M as EXECUTION_ATTEMPT_STATUSES,f as ExecutionAttemptAuthority,L as PROVIDER_OPERATION_OBLIGATIONS,v as RUNTIME_PROBE_DELIVERY_TIMEOUT_MS,_ as WorkflowEngineService,T as WorkflowEngineToken,w as WorkflowExecutor,u as WorkflowStorageNamespace,n as WorkflowStorageSubjects,x as WorkflowTriggerReconciler,D as assertWorkflowTriggerPayload,U as buildWorkflowExpressionContextFromResolvedInputs,O as compileWorkflowTriggerBindingFilter,b as createWorkflowEnginePackage,N as decodeDurableOutcome,P as durableOutcome,S as getWorkflowState,y as initializeWorkflowState,g as patchWorkflowState,h as registerDrizzleWorkflowStorage,p as registerOperationAdmissionHandler,E as registerRuntimeRegistrationHandler,c as runAuthorityDispatchedAttempt,i as runShellStep,F as sameAllocationRef,I as sameDurableOutcome,m as submitAttemptOutcome,r as workflowDefinitionsDual,C as workflowEnginePackage,e as workflowExecutionStateDual,t as workflowExecutionStateEventsDual,a as workflowExecutionsDual,d as workflowFinalizationsDual,o as workflowStepSpansDual,s as worklogFrameEntriesDual,l as worklogSummariesDual};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-
|
|
1
|
+
import { n as createWorkflowEnginePackage, r as workflowEnginePackage, t as WorkflowEngineToken } from "../package-DkZmsdCd.mjs";
|
|
2
2
|
export { WorkflowEngineToken, createWorkflowEnginePackage, workflowEnginePackage };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"../package-
|
|
1
|
+
import{n as e,r as t,t as n}from"../package-UemD2NWn.mjs";export{n as WorkflowEngineToken,e as createWorkflowEnginePackage,t as workflowEnginePackage};
|
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
import { a as ProviderOperationClaim, i as ProcessBoundProvisionerLossProof, l as ProviderOperationOwnershipRecord } from "../../provider-operation-DbdyFwNm.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { BoundedRecoveryEvidence, ProviderAllocationRef, WorkflowRunResult } from "@makaio/framework/contracts";
|
|
2
|
+
import { A as OutcomeCodec, F as RecordAllocationInput, P as ProvisioningClaimDecision, l as BeginProvisioningInput, r as AllocationRecordingDecision, s as AttemptControlState, w as ExecutionOwnerId, x as ExecutionAttemptRepository, y as ExecutionAttemptRecord } from "../../execution-attempt-repository-CRdrgou3.mjs";
|
|
3
|
+
import { BoundedRecoveryEvidence, ProviderAllocationRef, WorkerAllocationLifetime, WorkflowRunResult } from "@makaio/framework/contracts";
|
|
4
4
|
|
|
5
|
+
//#region subsystems/workflow-engine/src/testing/attempt-record-codec.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The control state a freshly created attempt holds.
|
|
8
|
+
*
|
|
9
|
+
* Stated once so both realizations open an attempt in the same place: no
|
|
10
|
+
* runtime, no readiness, nothing running, and a start gate that is open. A
|
|
11
|
+
* durable realization spells the same values as column defaults; that they
|
|
12
|
+
* agree is what makes a record built in memory and a row read back from
|
|
13
|
+
* storage the same attempt.
|
|
14
|
+
*/
|
|
15
|
+
declare const INITIAL_ATTEMPT_CONTROL_STATE: AttemptControlState;
|
|
16
|
+
//#endregion
|
|
5
17
|
//#region subsystems/workflow-engine/src/testing/in-memory-attempt-repository.d.ts
|
|
6
18
|
/**
|
|
7
19
|
* Durable state the in-memory realization keeps.
|
|
@@ -163,5 +175,45 @@ declare const workflowRunResultOutcomeCodec: OutcomeCodec<WorkflowRunResult>;
|
|
|
163
175
|
* @returns A canonical workflow run result.
|
|
164
176
|
*/
|
|
165
177
|
declare function makeTestWorkflowResult(executionId: string, status?: 'completed' | 'failed'): WorkflowRunResult;
|
|
178
|
+
/**
|
|
179
|
+
* The operations that bring an attempt from creation to `allocated`.
|
|
180
|
+
*
|
|
181
|
+
* The durable repository and the Authority expose all three with the same
|
|
182
|
+
* shapes, so one driver serves harnesses at either layer.
|
|
183
|
+
*/
|
|
184
|
+
interface AttemptAllocationDriver extends ProvisioningClaimGrantor {
|
|
185
|
+
/**
|
|
186
|
+
* Persist a new attempt for its owner.
|
|
187
|
+
* @param executionId - Owner identifier the attempt belongs to.
|
|
188
|
+
* @returns The persisted attempt record.
|
|
189
|
+
*/
|
|
190
|
+
createAttempt(executionId: ExecutionOwnerId): Promise<ExecutionAttemptRecord>;
|
|
191
|
+
/**
|
|
192
|
+
* Record the allocation the provider returned for the claimed attempt.
|
|
193
|
+
* @param input - The claim and the allocation reference to record.
|
|
194
|
+
* @returns The durable allocation recording decision.
|
|
195
|
+
*/
|
|
196
|
+
recordAllocation(input: RecordAllocationInput): Promise<AllocationRecordingDecision>;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Drive an existing attempt to `allocated`, the state a runtime may register against.
|
|
200
|
+
*
|
|
201
|
+
* A created attempt answers `not-allocated` to every registration, so a
|
|
202
|
+
* harness that lets a runtime register owes these two moves. They are the
|
|
203
|
+
* test-side stand-in for the provisioner a real dispatch would run.
|
|
204
|
+
* @param driver - Repository or Authority owning the attempt.
|
|
205
|
+
* @param executionAttemptId - Attempt to provision and allocate.
|
|
206
|
+
* @param executionId - Owner the attempt belongs to.
|
|
207
|
+
* @throws When provisioning does not start or the allocation is not recorded.
|
|
208
|
+
*/
|
|
209
|
+
declare function driveTestAttemptToAllocated(driver: Pick<AttemptAllocationDriver, 'beginProvisioning' | 'recordAllocation'>, executionAttemptId: string, executionId: ExecutionOwnerId): Promise<void>;
|
|
210
|
+
/**
|
|
211
|
+
* Create one attempt through the Authority and drive it to `allocated`.
|
|
212
|
+
* @param driver - Authority owning the attempt; it mints the attempt identifier.
|
|
213
|
+
* @param executionId - Owner the attempt belongs to.
|
|
214
|
+
* @returns The allocated attempt's identifier.
|
|
215
|
+
* @throws When provisioning does not start or the allocation is not recorded.
|
|
216
|
+
*/
|
|
217
|
+
declare function allocateTestAttempt(driver: AttemptAllocationDriver, executionId: ExecutionOwnerId): Promise<string>;
|
|
166
218
|
//#endregion
|
|
167
|
-
export { type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, beginTestProvisioning, createInMemoryAttemptRepository, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestWorkflowResult, workflowRunResultOutcomeCodec };
|
|
219
|
+
export { type AttemptAllocationDriver, INITIAL_ATTEMPT_CONTROL_STATE, type InMemoryAttemptRepository, type InMemoryAttemptRepositoryState, type ProvisioningClaimGrantor, TEST_OWNER_ID, TEST_PROVIDER_ID, TEST_PROVISIONER_INCARNATION_ID, allocateTestAttempt, beginTestProvisioning, createInMemoryAttemptRepository, driveTestAttemptToAllocated, leaseAt, makeBeginProvisioningInput, makeEvidence, makeProcessLossProof, makeTestAllocationRef, makeTestWorkflowResult, workflowRunResultOutcomeCodec };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DuplicateExecutionAttemptError as e,decodeDurableOutcome as t,durableOutcome as n,sameAllocationRef as r,sameDurableOutcome as i}from"../execution-attempt-repository.mjs";import{a,c as o,i as s,n as c,o as l,r as u,s as d,t as f}from"../../attempt-record-codec-dC9LSFUE.mjs";import{BoundedRecoveryEvidenceSchema as p,PROVIDER_ALLOCATION_REF_VERSION as m,WorkflowRunResultSchema as h}from"@makaio/framework/contracts";function g(m,h={}){let g=h.attempts??new Map,_=h.operations??new Map,v=h.committedOutcomes??new Map,y=h.activeAttempts??new Map,b=e=>{let t=g.get(e.executionAttemptId),n=_.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}:{kind:`resolved`,attempt:t}},x=(e,t)=>{_.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},S=(e,t)=>{let n=a(e.allocationRef),i=b(e.claim);if(i.kind!==`not-found`&&d(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:o,operation:s}=i;if(o.allocationRef!==null)return r(o.allocationRef,n)?{kind:`duplicate`,allocationRef:o.allocationRef}:{kind:`conflict`,allocationRef:o.allocationRef};let c=y.get(o.executionId)===o.executionAttemptId;return g.set(o.executionAttemptId,{...o,status:`allocated`,allocationRef:n,claimable:t&&c}),_.set(s.executionAttemptId,{...s,obligation:`allocation-control`}),{kind:`recorded`}};return{async createAttempt(t){if(g.has(t.executionAttemptId))throw new e(t.executionAttemptId);let n={executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:new Date().toISOString(),providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null},r=y.get(t.executionId),i=r===void 0?void 0:g.get(r);return i?.status===`allocated`&&g.set(i.executionAttemptId,{...i,claimable:!1}),g.set(t.executionAttemptId,n),y.set(t.executionId,t.executionAttemptId),n},async beginProvisioning(e){let t=s(e.allocationLifetime),n=g.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(y.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.status!==`pending`)return{kind:`already-provisioning`};g.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:u(e.leaseExpiresAt)};return _.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return _.get(e)??null},async renewProviderOperationClaim(e){let t=b(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=u(e.leaseExpiresAt);return _.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=g.get(e.executionAttemptId),n=_.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&c(n.leaseExpiresAt)>c(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:u(e.leaseExpiresAt)};return _.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:p.parse(e.evidence),n=b(e.claim);return n.kind===`authorized`?(_.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=p.parse(e.evidence),n=b(e.claim);return n.kind===`authorized`?(_.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return S(e,!0)},async recordProvisioningAbsent(e){let t=p.parse(e.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(g.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),x(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=p.parse(e.proof.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationLifetime===`provisioner-process-bound`?r.provisionerIncarnationId===null||r.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:r.provisionerIncarnationId}:r.allocationRef===null?(g.set(r.executionAttemptId,{...r,status:`settled`,settlementKind:`abandoned`,claimable:!1}),x(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-process-bound`,allocationLifetime:r.allocationLifetime}:{kind:`not-found`}},async recordAllocationTerminated(e){let t=p.parse(e.evidence),n=b(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(_.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=b(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(g.set(n.executionAttemptId,{...n,status:`settled`,settlementKind:`infrastructure-failure`,claimable:!1}),x(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async getActiveAttempt(e,t){return y.get(e)===t?g.get(t)??null:null},canonicalizeOutcome(e){return n(m,e)},decodeOutcome(e){return t(m,e)},async commitOutcome(e){let n=e.result;if(y.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let r=g.get(e.executionAttemptId);if(r===void 0)return{kind:`fenced`};let a=v.get(e.executionAttemptId);if(a!==void 0){let e=t(m,a);return i(a,n.text)?{kind:`duplicate`,outcome:e,text:a}:{kind:`conflict`}}if(r.settlementKind!=null)return{kind:`conflict`};v.set(e.executionAttemptId,n.text),g.set(e.executionAttemptId,{...r,status:`settled`,settlementKind:`outcome`,claimable:!1});let o=_.get(e.executionAttemptId);return o&&x(o,o.lastFailure),{kind:`accepted`,outcome:t(m,n.text),text:n.text}},async abandonPendingAttempt(e,t){if(y.get(t)!==e)return{kind:`fenced`};let n=g.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(g.set(e,{...n,status:`settled`,settlementKind:`abandoned`,claimable:!1}),{kind:`abandoned`}):{kind:`fenced`}},recovery:{async getAttemptWithAllocation(e){return g.get(e)??null},async recordDiscoveredAllocation(e){return S(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=l(e),i=b(e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:r(a.allocationRef,t)?(g.set(a.executionAttemptId,{...a,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=c(new Date().toISOString()),n=[];for(let r of g.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&c(r.claimExpiresAt)<t||n.push(o(r)));return n.sort(f)}},attempts:g,operations:_,committedOutcomes:v,activeAttempts:y}}const _=`controller-incarnation-1`,v=`provisioner-incarnation-1`,y=`test-provider`;function b(e){return new Date(Date.now()+e).toISOString()}function x(e,t,n={}){return{executionAttemptId:e,executionId:t,providerId:y,allocationLifetime:`provider-managed`,provisionerIncarnationId:v,ownerId:_,leaseExpiresAt:b(6e4),...n}}async function S(e,t,n,r={}){let i=await e.beginProvisioning(x(t,n,r));if(i.kind!==`started`)throw Error(`Expected provisioning to start, got '${i.kind}'`);return i.claim}function C(e={}){return{source:y,summary:`provider rejected the request before creating anything`,observedAt:new Date().toISOString(),...e}}function w(e=v,t=C({summary:`supervisor observed the provisioner process exit`})){return{kind:`provisioner-incarnation-lost`,provisionerIncarnationId:e,evidence:t}}function T(e=y,t={runId:1}){return{version:m,providerId:e,providerData:t}}const E={parse:e=>h.parse(e),serialize:e=>JSON.stringify(e)};function D(e,t=`completed`){let n={executionId:e,workflowId:`contract-workflow`};return t===`completed`?{...n,status:`completed`}:{...n,status:`failed`,error:`contract failure`}}export{_ as TEST_OWNER_ID,y as TEST_PROVIDER_ID,v as TEST_PROVISIONER_INCARNATION_ID,S as beginTestProvisioning,g as createInMemoryAttemptRepository,b as leaseAt,x as makeBeginProvisioningInput,C as makeEvidence,w as makeProcessLossProof,T as makeTestAllocationRef,D as makeTestWorkflowResult,E as workflowRunResultOutcomeCodec};
|
|
1
|
+
import{DuplicateExecutionAttemptError as e,decodeDurableOutcome as t,durableOutcome as n,sameAllocationRef as r,sameDurableOutcome as i}from"../execution-attempt-repository.mjs";import{a,c as o,i as s,l as c,n as l,o as u,r as d,s as f,t as p,u as m}from"../../attempt-record-codec-BORASgzn.mjs";import{BoundedRecoveryEvidenceSchema as h,PROVIDER_ALLOCATION_REF_VERSION as g,WorkflowRunResultSchema as _}from"@makaio/framework/contracts";function v(e,t){return{...e,status:`settled`,settlementKind:t,claimable:!1,operationStartGate:`closed`}}function y(g,_={}){let y=_.attempts??new Map,b=_.operations??new Map,x=e=>b.get(e)?.obligation===`terminal-convergence`,S=_.committedOutcomes??new Map,C=_.activeAttempts??new Map,w=e=>{let t=y.get(e.executionAttemptId),n=b.get(e.executionAttemptId);return!t||!n?{kind:`not-found`}:t.settlementKind==null?n.token===null||n.token!==e.token||n.generation!==e.generation||n.ownerId!==e.ownerId?{kind:`stale`,attempt:t}:{kind:`authorized`,attempt:t,operation:n}:{kind:`resolved`,attempt:t}},T=(e,t)=>{b.set(e.executionAttemptId,{...e,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t})},E=(e,t)=>{let n=u(e.allocationRef),i=w(e.claim);if(i.kind!==`not-found`&&o(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a,operation:s}=i;if(a.allocationRef!==null)return r(a.allocationRef,n)?{kind:`duplicate`,allocationRef:a.allocationRef}:{kind:`conflict`,allocationRef:a.allocationRef};let c=C.get(a.executionId)===a.executionAttemptId;return y.set(a.executionAttemptId,{...a,status:`allocated`,allocationRef:n,claimable:t&&c}),b.set(s.executionAttemptId,{...s,obligation:`allocation-control`}),{kind:`recorded`}};return{async createAttempt(t){if(y.has(t.executionAttemptId))throw new e(t.executionAttemptId);let n={executionAttemptId:t.executionAttemptId,executionId:t.executionId,status:`pending`,allocationRef:null,createdAt:new Date().toISOString(),providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null,...p},r=C.get(t.executionId),i=r===void 0?void 0:y.get(r);return i!==void 0&&y.set(i.executionAttemptId,{...i,claimable:i.status===`allocated`?!1:i.claimable,operationStartGate:`closed`}),y.set(t.executionAttemptId,n),C.set(t.executionId,t.executionAttemptId),n},async beginProvisioning(e){let t=a(e.allocationLifetime),n=y.get(e.executionAttemptId);if(!n||n.executionId!==e.executionId)return{kind:`not-found`};if(C.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(n.settlementKind!=null)return{kind:`resolved`,allocationRef:n.allocationRef};if(n.allocationRef!==null)return{kind:`allocated`,allocationRef:n.allocationRef};if(n.status!==`pending`)return{kind:`already-provisioning`};y.set(e.executionAttemptId,{...n,status:`provisioning`,providerId:e.providerId,allocationLifetime:t,provisionerIncarnationId:e.provisionerIncarnationId});let r={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:s(e.leaseExpiresAt)};return b.set(e.executionAttemptId,{executionAttemptId:e.executionAttemptId,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt,obligation:`provisioning-resolution`,failureCount:0,lastFailure:null}),{kind:`started`,claim:r}},async getProviderOperation(e){return b.get(e)??null},async renewProviderOperationClaim(e){let t=w(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let n=s(e.leaseExpiresAt);return b.set(e.claim.executionAttemptId,{...t.operation,leaseExpiresAt:n}),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:n}}},async takeOverProviderOperation(e){let t=y.get(e.executionAttemptId),n=b.get(e.executionAttemptId);if(!t||!n)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(n.ownerId!==null&&n.leaseExpiresAt!==null&&d(n.leaseExpiresAt)>d(e.observedAt))return{kind:`stale`};let r={executionAttemptId:e.executionAttemptId,generation:n.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:s(e.leaseExpiresAt)};return b.set(e.executionAttemptId,{...n,generation:r.generation,ownerId:r.ownerId,token:r.token,leaseExpiresAt:r.leaseExpiresAt}),{kind:`claimed`,claim:r}},async handoffProviderOperation(e){let t=e.evidence===void 0?void 0:h.parse(e.evidence),n=w(e.claim);return n.kind===`authorized`?(b.set(e.claim.executionAttemptId,{...n.operation,ownerId:null,token:null,leaseExpiresAt:null,lastFailure:t??n.operation.lastFailure}),{kind:`recorded`}):{kind:n.kind}},async recordProviderOperationUncertainty(e){let t=h.parse(e.evidence),n=w(e.claim);return n.kind===`authorized`?(b.set(e.claim.executionAttemptId,{...n.operation,failureCount:n.operation.failureCount+1,lastFailure:t}),{kind:`recorded`}):{kind:n.kind}},async recordAllocation(e){return E(e,!0)},async recordProvisioningAbsent(e){let t=h.parse(e.evidence),n=w(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?(y.set(r.executionAttemptId,v(r,`abandoned`)),T(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-found`}},async recordProvisionerIncarnationLost(e){let t=h.parse(e.proof.evidence),n=w(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationLifetime===`provisioner-process-bound`?r.provisionerIncarnationId===null||r.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:r.provisionerIncarnationId}:r.allocationRef===null?(y.set(r.executionAttemptId,v(r,`abandoned`)),T(i,t),{kind:`recorded`}):{kind:`allocated`,allocationRef:r.allocationRef}:{kind:`not-process-bound`,allocationLifetime:r.allocationLifetime}:{kind:`not-found`}},async recordAllocationTerminated(e){let t=h.parse(e.evidence),n=w(e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.allocationRef===null?{kind:`not-allocated`}:(b.set(i.executionAttemptId,{...i,obligation:`terminal-convergence`,lastFailure:t}),{kind:`recorded`})},async recordInfrastructureFailure(e){let t=w(e.claim);if(t.kind!==`authorized`)return{kind:t.kind};let{attempt:n,operation:r}=t;return n.executionId===e.executionId?n.allocationRef===null?{kind:`not-allocated`}:r.obligation===`terminal-convergence`?(y.set(n.executionAttemptId,v(n,`infrastructure-failure`)),T(r,r.lastFailure),{kind:`recorded`}):{kind:`not-terminated`}:{kind:`not-found`}},async registerRuntime(e){let t=y.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(C.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(t.allocationRef===null||x(t.executionAttemptId))return{kind:`not-allocated`};if(t.runtimeIncarnationId===e.runtimeIncarnationId)return{kind:`duplicate`,runtimeGeneration:t.runtimeGeneration,runtimeReadyAt:t.runtimeReadyAt};if(t.activeOperationId!==null&&t.activeOperationKind!==`runtime-probe`)return{kind:`operation-active`,operationId:t.activeOperationId};let n=t.runtimeGeneration+1;return y.set(t.executionAttemptId,{...t,runtimeGeneration:n,runtimeIncarnationId:e.runtimeIncarnationId,runtimeReadyAt:null,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null}),{kind:`registered`,runtimeGeneration:n}},async admitOperation(e){let t=y.get(e.executionAttemptId);if(t===void 0||t.executionId!==e.executionId)return{kind:`not-found`};if(t.settlementKind!=null)return{kind:`resolved`};if(C.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(t.allocationRef===null||x(t.executionAttemptId))return{kind:`not-allocated`};if(t.activeOperationId!==null)return t.activeOperationKey===e.admissionKey?{kind:`duplicate`,operationId:t.activeOperationId,runtimeGeneration:t.activeOperationGeneration??t.runtimeGeneration,admittedAt:t.activeOperationAdmittedAt??s(new Date().toISOString())}:{kind:`operation-active`,operationId:t.activeOperationId};if(t.operationStartGate===`closed`)return{kind:`gate-closed`};if(e.operationKind!==`runtime-probe`&&t.runtimeReadyAt===null)return{kind:`not-ready`};if(t.runtimeGeneration!==e.runtimeGeneration)return{kind:`stale-generation`,runtimeGeneration:t.runtimeGeneration};let n=crypto.randomUUID(),r=s(new Date().toISOString());return y.set(t.executionAttemptId,{...t,activeOperationId:n,activeOperationKind:e.operationKind,activeOperationKey:e.admissionKey,activeOperationGeneration:t.runtimeGeneration,activeOperationAdmittedAt:r}),{kind:`admitted`,operationId:n,runtimeGeneration:t.runtimeGeneration,admittedAt:r}},async completeOperation(e){let t=y.get(e.executionAttemptId);return t===void 0?{kind:`not-found`}:t.settlementKind==null?t.lastCompletedOperationId===e.operationId?{kind:`duplicate`}:t.activeOperationId===null?{kind:`not-active`}:t.activeOperationId===e.operationId?t.activeOperationGeneration===e.runtimeGeneration?(y.set(t.executionAttemptId,{...t,activeOperationId:null,activeOperationKind:null,activeOperationKey:null,activeOperationGeneration:null,activeOperationAdmittedAt:null,lastCompletedOperationId:e.operationId}),{kind:`completed`}):{kind:`stale-generation`}:{kind:`mismatch`,activeOperationId:t.activeOperationId}:{kind:`resolved`}},async markRuntimeReady(e){let t=s(e.readyAt),n=y.get(e.executionAttemptId);return n===void 0||n.executionId!==e.executionId?{kind:`not-found`}:n.settlementKind==null?C.get(e.executionId)===e.executionAttemptId?n.allocationRef===null||x(n.executionAttemptId)?{kind:`not-allocated`}:n.runtimeGeneration===e.runtimeGeneration?n.runtimeReadyAt===null?n.activeOperationId===null?(y.set(n.executionAttemptId,{...n,runtimeReadyAt:t}),{kind:`ready`,acceptedAt:t}):{kind:`operation-active`,operationId:n.activeOperationId}:{kind:`duplicate`,acceptedAt:n.runtimeReadyAt}:{kind:`stale-generation`}:{kind:`fenced`}:{kind:`resolved`}},async getAttemptControlState(e){let t=y.get(e);return t===void 0?null:c(t)},async getActiveAttempt(e,t){return C.get(e)===t?y.get(t)??null:null},canonicalizeOutcome(e){return n(g,e)},decodeOutcome(e){return t(g,e)},async commitOutcome(e){let n=e.result;if(C.get(e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let r=y.get(e.executionAttemptId);if(r===void 0)return{kind:`fenced`};let a=S.get(e.executionAttemptId);if(a!==void 0){let e=t(g,a);return i(a,n.text)?{kind:`duplicate`,outcome:e,text:a}:{kind:`conflict`}}if(r.settlementKind!=null)return{kind:`conflict`};S.set(e.executionAttemptId,n.text),y.set(e.executionAttemptId,v(r,`outcome`));let o=b.get(e.executionAttemptId);return o&&T(o,o.lastFailure),{kind:`accepted`,outcome:t(g,n.text),text:n.text}},async abandonPendingAttempt(e,t){if(C.get(t)!==e)return{kind:`fenced`};let n=y.get(e);return n?n.status===`allocated`?{kind:`allocated`}:n.status===`provisioning`?{kind:`provisioning`}:n.status===`settled`?{kind:n.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:(y.set(e,v(n,`abandoned`)),{kind:`abandoned`}):{kind:`fenced`}},recovery:{async getAttemptWithAllocation(e){return y.get(e)??null},async recordDiscoveredAllocation(e){return E(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=f(e),i=w(e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:r(a.allocationRef,t)?(y.set(a.executionAttemptId,{...a,allocationRef:n}),{kind:`evolved`}):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},async getRecoverableAttempts(e){let t=d(new Date().toISOString()),n=[];for(let r of y.values())r.executionId===e&&r.status===`allocated`&&r.allocationRef!==null&&r.claimable===!0&&r.settlementKind==null&&(r.claimExpiresAt!=null&&d(r.claimExpiresAt)<t||n.push(m(r)));return n.sort(l)}},attempts:y,operations:b,committedOutcomes:S,activeAttempts:C}}const b=`controller-incarnation-1`,x=`provisioner-incarnation-1`,S=`test-provider`;function C(e){return new Date(Date.now()+e).toISOString()}function w(e,t,n={}){return{executionAttemptId:e,executionId:t,providerId:S,allocationLifetime:`provider-managed`,provisionerIncarnationId:x,ownerId:b,leaseExpiresAt:C(6e4),...n}}async function T(e,t,n,r={}){let i=await e.beginProvisioning(w(t,n,r));if(i.kind!==`started`)throw Error(`Expected provisioning to start, got '${i.kind}'`);return i.claim}function E(e={}){return{source:S,summary:`provider rejected the request before creating anything`,observedAt:new Date().toISOString(),...e}}function D(e=x,t=E({summary:`supervisor observed the provisioner process exit`})){return{kind:`provisioner-incarnation-lost`,provisionerIncarnationId:e,evidence:t}}function O(e=S,t={runId:1}){return{version:g,providerId:e,providerData:t}}const k={parse:e=>_.parse(e),serialize:e=>JSON.stringify(e)};function A(e,t=`completed`){let n={executionId:e,workflowId:`contract-workflow`};return t===`completed`?{...n,status:`completed`}:{...n,status:`failed`,error:`contract failure`}}async function j(e,t,n){let r=await e.beginProvisioning(w(t,n));if(r.kind!==`started`)throw Error(`Expected provisioning to start, got '${r.kind}'`);let i=await e.recordAllocation({claim:r.claim,allocationRef:O()});if(i.kind!==`recorded`)throw Error(`Expected the allocation to be recorded, got '${i.kind}'`)}async function M(e,t){let{executionAttemptId:n}=await e.createAttempt(t);return await j(e,n,t),n}export{p as INITIAL_ATTEMPT_CONTROL_STATE,b as TEST_OWNER_ID,S as TEST_PROVIDER_ID,x as TEST_PROVISIONER_INCARNATION_ID,M as allocateTestAttempt,T as beginTestProvisioning,y as createInMemoryAttemptRepository,j as driveTestAttemptToAllocated,C as leaseAt,w as makeBeginProvisioningInput,E as makeEvidence,D as makeProcessLossProof,O as makeTestAllocationRef,A as makeTestWorkflowResult,k as workflowRunResultOutcomeCodec};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as OutcomeCodec, x as ExecutionAttemptRepository } from "../../execution-attempt-repository-CRdrgou3.mjs";
|
|
2
2
|
import { MakaioDatabase } from "@makaio/framework/storage/drizzle";
|
|
3
3
|
|
|
4
4
|
//#region subsystems/workflow-engine/src/testing/sqlite-attempt-repository.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ATTEMPT_OPERATION_START_GATES as e,DuplicateExecutionAttemptError as t,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as n,EXECUTION_ATTEMPT_STATUSES as r,decodeDurableOutcome as i,durableOutcome as a,sameAllocationRef as o,sameDurableOutcome as s}from"../execution-attempt-repository.mjs";import{PROVIDER_OPERATION_OBLIGATIONS as c}from"../provider-operation.mjs";import{a as l,c as u,i as d,o as f,r as p,s as m,t as h,u as g}from"../../attempt-record-codec-BORASgzn.mjs";import{BoundedRecoveryEvidenceSchema as _,ExecutionAttemptOperationKindSchema as v,ProviderAllocationRefSchema as y,WorkerAllocationLifetimeSchema as b}from"@makaio/framework/contracts";import{getRawSqlExecutor as x,isSqliteUniqueViolationError as S,serializeByKey as C,serializeDatabaseOperation as w}from"@makaio/framework/storage/drizzle";import{sql as T}from"drizzle-orm";const E=[`CREATE TABLE IF NOT EXISTS test_execution_attempt (
|
|
2
2
|
execution_attempt_id TEXT PRIMARY KEY,
|
|
3
3
|
execution_id TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -10,7 +10,17 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
|
|
|
10
10
|
workflow_result TEXT,
|
|
11
11
|
claimable INTEGER NOT NULL DEFAULT 0,
|
|
12
12
|
claim_expires_at TEXT,
|
|
13
|
-
created_at TEXT NOT NULL
|
|
13
|
+
created_at TEXT NOT NULL,
|
|
14
|
+
runtime_generation INTEGER NOT NULL DEFAULT 0,
|
|
15
|
+
runtime_incarnation_id TEXT,
|
|
16
|
+
runtime_ready_at TEXT,
|
|
17
|
+
operation_start_gate TEXT NOT NULL DEFAULT 'open',
|
|
18
|
+
active_operation_id TEXT,
|
|
19
|
+
active_operation_kind TEXT,
|
|
20
|
+
active_operation_key TEXT,
|
|
21
|
+
active_operation_generation INTEGER,
|
|
22
|
+
active_operation_admitted_at TEXT,
|
|
23
|
+
last_completed_operation_id TEXT
|
|
14
24
|
)`,`CREATE TABLE IF NOT EXISTS test_active_execution_attempt (
|
|
15
25
|
execution_id TEXT PRIMARY KEY,
|
|
16
26
|
execution_attempt_id TEXT NOT NULL
|
|
@@ -25,43 +35,50 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
|
|
|
25
35
|
obligation TEXT NOT NULL,
|
|
26
36
|
failure_count INTEGER NOT NULL DEFAULT 0,
|
|
27
37
|
last_failure TEXT
|
|
28
|
-
)`];function
|
|
38
|
+
)`];function D(e,t,n){let r=e.find(e=>e===t);if(r===void 0)throw Error(`Stored '${n}' value '${t}' is not part of the port's vocabulary`);return r}function O(e,t){return e===null?null:t(JSON.parse(e))}function k(t){return{runtimeGeneration:t.runtime_generation,runtimeIncarnationId:t.runtime_incarnation_id,runtimeReadyAt:t.runtime_ready_at,operationStartGate:D(e,t.operation_start_gate,`operation_start_gate`),activeOperationId:t.active_operation_id,activeOperationKind:t.active_operation_kind===null?null:v.parse(t.active_operation_kind),activeOperationKey:t.active_operation_key,activeOperationGeneration:t.active_operation_generation,activeOperationAdmittedAt:t.active_operation_admitted_at,lastCompletedOperationId:t.last_completed_operation_id}}function A(e){return{...k(e),executionAttemptId:e.execution_attempt_id,executionId:e.execution_id,status:D(r,e.status,`status`),allocationRef:O(e.allocation_ref,e=>y.parse(e)),createdAt:e.created_at,providerId:e.provider_id,allocationLifetime:e.allocation_lifetime===null?null:b.parse(e.allocation_lifetime),provisionerIncarnationId:e.provisioner_incarnation_id,settlementKind:e.settlement_kind===null?null:D(n,e.settlement_kind,`settlement_kind`),claimable:e.claimable!==0,claimExpiresAt:e.claim_expires_at}}function j(e){return{executionAttemptId:e.execution_attempt_id,generation:e.generation,ownerId:e.owner_id,token:e.token,leaseExpiresAt:e.lease_expires_at,obligation:D(c,e.obligation,`obligation`),failureCount:e.failure_count,lastFailure:O(e.last_failure,e=>_.parse(e))}}const M=new Map,N=new Map;function P(e){if(typeof e!=`object`||!e)return!1;let t=e,n=typeof t.message==`string`?t.message:``;return n.includes(`SQLITE_BUSY`)||n.startsWith(`Failed query: BEGIN IMMEDIATE`)||n.startsWith(`Failed query: COMMIT`)||P(t.cause)}function F(e){if(typeof e!=`object`||!e)return!1;let t=e;return(typeof t.message==`string`?t.message:``).includes(`no transaction is active`)||F(t.cause)}async function I(){await new Promise(e=>setImmediate(e))}async function L(e){for(let t=0;;t+=1)try{await e.run(T.raw(`COMMIT`));return}catch(e){if(!P(e)||t===100)throw e;await I()}}async function R(e,t){return C(M,e,t)}async function z(e,t){return C(N,e,t)}const B=new WeakMap;async function V(e,t){let n=(await t.all(T.raw(`PRAGMA database_list`))).find(e=>e.name===`main`)?.file??null;if(n!==null&&n!==``)return`file:${n}`;let r=B.get(e);if(r!==void 0)return r;let i=`connection:${crypto.randomUUID()}`;return B.set(e,i),i}async function H(e,t){let n=await e();if(typeof n!=`function`)return n;if((await n()).rowsAffected>0)return t;let r=await e();if(typeof r!=`function`)return r;throw Error(`A guarded transition affected no rows while durable state still permitted it`)}function U(e){return T`EXISTS (SELECT 1 FROM test_provider_operation
|
|
29
39
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
30
40
|
AND generation = ${e.generation}
|
|
31
41
|
AND owner_id = ${e.ownerId}
|
|
32
|
-
AND token = ${e.token})`}function
|
|
33
|
-
WHERE execution_attempt_id = ${e} AND settlement_kind IS NULL)`}function
|
|
42
|
+
AND token = ${e.token})`}function W(e){return T`EXISTS (SELECT 1 FROM test_execution_attempt
|
|
43
|
+
WHERE execution_attempt_id = ${e} AND settlement_kind IS NULL)`}function G(e){return T`${U(e)} AND ${W(e.executionAttemptId)}`}function K(e){return T`EXISTS (SELECT 1 FROM test_provider_operation
|
|
34
44
|
WHERE execution_attempt_id = ${e}
|
|
35
|
-
AND obligation = ${`terminal-convergence`})`}function
|
|
45
|
+
AND obligation = ${`terminal-convergence`})`}function q(){return T`EXISTS (SELECT 1 FROM test_active_execution_attempt
|
|
36
46
|
WHERE execution_id = test_execution_attempt.execution_id
|
|
37
|
-
AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function
|
|
38
|
-
SET status = ${`settled`}, settlement_kind = ${n}, claimable = ${0}
|
|
47
|
+
AND execution_attempt_id = test_execution_attempt.execution_attempt_id)`}async function J(e,n){let r=x(e);await r.run(T.raw(`PRAGMA busy_timeout = 0`));let v=await V(e,r);await R(v,async()=>{for(let e of E)await r.run(T.raw(e))});let y,b=async t=>w(e,()=>z(v,async()=>{if(y!==void 0)throw Error(`This repository was retired by a failed transaction rollback`,{cause:y});for(let e=0;;e+=1)try{return await r.withSession(async e=>{let n=!1;try{await e.run(T.raw(`BEGIN IMMEDIATE`)),n=!0;let r=await t(e);return await L(e),r}catch(t){try{await e.run(T.raw(`ROLLBACK`))}catch(e){throw!n&&F(e)?t:(y=AggregateError([t,e],`Transaction rollback failed`),y)}throw t}})}catch(t){if(!P(t)||e===100)throw t;await I()}})),C=async(e,t)=>(await e.all(T`SELECT * FROM test_execution_attempt WHERE execution_attempt_id = ${t}`))[0],O=async(e,t)=>(await e.all(T`SELECT * FROM test_provider_operation WHERE execution_attempt_id = ${t}`))[0],M=async(e,t)=>(await O(e,t))?.obligation===`terminal-convergence`,N=async(e,t)=>(await e.all(T`SELECT execution_attempt_id FROM test_active_execution_attempt WHERE execution_id = ${t}`))[0]?.execution_attempt_id??null,B=async(e,t)=>{let n=await C(e,t.executionAttemptId),r=await O(e,t.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};let i=A(n);return i.settlementKind==null?r.token===null||r.token!==t.token||r.generation!==t.generation||r.owner_id!==t.ownerId?{kind:`stale`,attempt:i}:{kind:`authorized`,attempt:i,attemptRow:n,operation:r}:{kind:`resolved`,attempt:i}},J=async(e,t)=>{let n=await B(e,t);return n.kind===`authorized`?void 0:{kind:n.kind}},Y=async(e,t,n,r,i)=>{let a=await e.run(T`UPDATE test_execution_attempt
|
|
48
|
+
SET status = ${`settled`}, settlement_kind = ${n}, claimable = ${0},
|
|
49
|
+
operation_start_gate = ${`closed`}
|
|
39
50
|
WHERE execution_attempt_id = ${t}
|
|
40
51
|
AND settlement_kind IS NULL
|
|
41
|
-
AND ${r}`);return a.rowsAffected===0||await e.run(i===void 0?
|
|
52
|
+
AND ${r}`);return a.rowsAffected===0||await e.run(i===void 0?T`UPDATE test_provider_operation
|
|
42
53
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL
|
|
43
|
-
WHERE execution_attempt_id = ${t}`:
|
|
54
|
+
WHERE execution_attempt_id = ${t}`:T`UPDATE test_provider_operation
|
|
44
55
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL, last_failure = ${JSON.stringify(i)}
|
|
45
|
-
WHERE execution_attempt_id = ${t}`),a},
|
|
56
|
+
WHERE execution_attempt_id = ${t}`),a},X=(e,t)=>{let n=f(e.allocationRef),r=t?T`CASE WHEN ${q()} THEN 1 ELSE 0 END`:T`${0}`;return b(t=>H(async()=>{let i=await B(t,e.claim);if(i.kind!==`not-found`&&u(i.attempt,n),i.kind===`resolved`)return{kind:`resolved`,allocationRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a}=i;return a.allocationRef===null?async()=>{let i=await t.run(T`UPDATE test_execution_attempt
|
|
46
57
|
SET status = ${`allocated`},
|
|
47
58
|
allocation_ref = ${JSON.stringify(n)},
|
|
48
59
|
claimable = ${r}
|
|
49
|
-
WHERE execution_attempt_id = ${
|
|
60
|
+
WHERE execution_attempt_id = ${a.executionAttemptId}
|
|
50
61
|
AND allocation_ref IS NULL
|
|
51
|
-
AND ${
|
|
52
|
-
WHERE execution_attempt_id = ${
|
|
62
|
+
AND ${G(e.claim)}`);return i.rowsAffected===0||await t.run(T`UPDATE test_provider_operation SET obligation = ${`allocation-control`}
|
|
63
|
+
WHERE execution_attempt_id = ${a.executionAttemptId}`),i}:o(a.allocationRef,n)?{kind:`duplicate`,allocationRef:a.allocationRef}:{kind:`conflict`,allocationRef:a.allocationRef}},{kind:`recorded`}))};return{async createAttempt(e){return b(async n=>{let r=new Date().toISOString();try{await n.run(T`INSERT INTO test_execution_attempt
|
|
53
64
|
(execution_attempt_id, execution_id, status, claimable, created_at)
|
|
54
|
-
VALUES (${
|
|
65
|
+
VALUES (${e.executionAttemptId}, ${e.executionId}, ${`pending`}, ${0}, ${r})`)}catch(n){throw S(n)?new t(e.executionAttemptId,{cause:n}):n}return await n.run(T`UPDATE test_execution_attempt
|
|
55
66
|
SET claimable = ${0}
|
|
56
67
|
WHERE execution_attempt_id = (
|
|
57
68
|
SELECT execution_attempt_id
|
|
58
69
|
FROM test_active_execution_attempt
|
|
59
|
-
WHERE execution_id = ${
|
|
70
|
+
WHERE execution_id = ${e.executionId}
|
|
60
71
|
)
|
|
61
|
-
AND status = ${`allocated`}`),await n.run(
|
|
62
|
-
|
|
72
|
+
AND status = ${`allocated`}`),await n.run(T`UPDATE test_execution_attempt
|
|
73
|
+
SET operation_start_gate = ${`closed`}
|
|
74
|
+
WHERE execution_attempt_id = (
|
|
75
|
+
SELECT execution_attempt_id
|
|
76
|
+
FROM test_active_execution_attempt
|
|
77
|
+
WHERE execution_id = ${e.executionId}
|
|
78
|
+
)`),await n.run(T`INSERT INTO test_active_execution_attempt (execution_id, execution_attempt_id)
|
|
79
|
+
VALUES (${e.executionId}, ${e.executionAttemptId})
|
|
63
80
|
ON CONFLICT(execution_id)
|
|
64
|
-
DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{executionAttemptId:
|
|
81
|
+
DO UPDATE SET execution_attempt_id = excluded.execution_attempt_id`),{...h,executionAttemptId:e.executionAttemptId,executionId:e.executionId,status:`pending`,allocationRef:null,createdAt:r,providerId:null,allocationLifetime:null,provisionerIncarnationId:null,settlementKind:null,claimable:!1,claimExpiresAt:null}})},async beginProvisioning(e){let t=l(e.allocationLifetime),n={executionAttemptId:e.executionAttemptId,generation:1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:d(e.leaseExpiresAt)};return b(r=>H(async()=>{let i=await C(r,e.executionAttemptId);if(i===void 0||i.execution_id!==e.executionId)return{kind:`not-found`};let a=A(i);return await N(r,e.executionId)===e.executionAttemptId?a.settlementKind==null?a.allocationRef===null?a.status===`pending`?async()=>{let i=await r.run(T`UPDATE test_execution_attempt
|
|
65
82
|
SET status = ${`provisioning`},
|
|
66
83
|
provider_id = ${e.providerId},
|
|
67
84
|
allocation_lifetime = ${t},
|
|
@@ -71,60 +88,111 @@ import{DuplicateExecutionAttemptError as e,EXECUTION_ATTEMPT_SETTLEMENT_KINDS as
|
|
|
71
88
|
AND status = ${`pending`}
|
|
72
89
|
AND allocation_ref IS NULL
|
|
73
90
|
AND settlement_kind IS NULL
|
|
74
|
-
AND ${
|
|
91
|
+
AND ${q()}`);return i.rowsAffected===0||await r.run(T`INSERT INTO test_provider_operation
|
|
75
92
|
(execution_attempt_id, generation, owner_id, token, lease_expires_at, obligation, failure_count)
|
|
76
93
|
VALUES (${e.executionAttemptId}, ${n.generation}, ${n.ownerId}, ${n.token},
|
|
77
|
-
${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return
|
|
94
|
+
${n.leaseExpiresAt}, ${`provisioning-resolution`}, ${0})`),i}:{kind:`already-provisioning`}:{kind:`allocated`,allocationRef:a.allocationRef}:{kind:`resolved`,allocationRef:a.allocationRef}:{kind:`fenced`}},{kind:`started`,claim:n}))},async getProviderOperation(e){return b(async t=>{let n=await O(t,e);return n===void 0?null:j(n)})},async renewProviderOperationClaim(e){let t=d(e.leaseExpiresAt);return b(n=>H(async()=>await J(n,e.claim)??(()=>n.run(T`UPDATE test_provider_operation SET lease_expires_at = ${t}
|
|
78
95
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
79
|
-
AND ${
|
|
96
|
+
AND ${G(e.claim)}`)),{kind:`claimed`,claim:{...e.claim,leaseExpiresAt:t}}))},async takeOverProviderOperation(e){return b(async t=>{let n=await C(t,e.executionAttemptId),r=await O(t,e.executionAttemptId);if(n===void 0||r===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};if(r.owner_id!==null&&r.lease_expires_at!==null&&p(r.lease_expires_at)>p(e.observedAt))return{kind:`stale`};let i={executionAttemptId:e.executionAttemptId,generation:r.generation+1,ownerId:e.ownerId,token:crypto.randomUUID(),leaseExpiresAt:d(e.leaseExpiresAt)},{rowsAffected:a}=await t.run(T`UPDATE test_provider_operation
|
|
80
97
|
SET generation = ${i.generation}, owner_id = ${i.ownerId}, token = ${i.token},
|
|
81
98
|
lease_expires_at = ${i.leaseExpiresAt}
|
|
82
99
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
83
100
|
AND generation = ${r.generation}
|
|
84
|
-
AND ${
|
|
101
|
+
AND ${W(e.executionAttemptId)}`);return a===0?{kind:`stale`}:{kind:`claimed`,claim:i}})},async handoffProviderOperation(e){let t=e.evidence===void 0?null:_.parse(e.evidence);return b(n=>H(async()=>await J(n,e.claim)??(()=>n.run(t===null?T`UPDATE test_provider_operation
|
|
85
102
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL
|
|
86
103
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
87
|
-
AND ${
|
|
104
|
+
AND ${G(e.claim)}`:T`UPDATE test_provider_operation
|
|
88
105
|
SET owner_id = NULL, token = NULL, lease_expires_at = NULL,
|
|
89
106
|
last_failure = ${JSON.stringify(t)}
|
|
90
107
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
91
|
-
AND ${
|
|
108
|
+
AND ${G(e.claim)}`)),{kind:`recorded`}))},async recordProviderOperationUncertainty(e){let t=_.parse(e.evidence);return b(n=>H(async()=>await J(n,e.claim)??(()=>n.run(T`UPDATE test_provider_operation
|
|
92
109
|
SET failure_count = failure_count + 1, last_failure = ${JSON.stringify(t)}
|
|
93
110
|
WHERE execution_attempt_id = ${e.claim.executionAttemptId}
|
|
94
|
-
AND ${
|
|
111
|
+
AND ${G(e.claim)}`)),{kind:`recorded`}))},async recordAllocation(e){return X(e,!0)},async recordProvisioningAbsent(e){let t=_.parse(e.evidence);return b(n=>H(async()=>{let r=await B(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationRef===null?()=>Y(n,i.executionAttemptId,`abandoned`,T`execution_id = ${e.executionId}
|
|
95
112
|
AND allocation_ref IS NULL
|
|
96
|
-
AND ${
|
|
113
|
+
AND ${U(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-found`}},{kind:`recorded`}))},async recordProvisionerIncarnationLost(e){let t=_.parse(e.proof.evidence);return b(n=>H(async()=>{let r=await B(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.executionId===e.executionId?i.allocationLifetime===`provisioner-process-bound`?i.provisionerIncarnationId===null||i.provisionerIncarnationId!==e.proof.provisionerIncarnationId?{kind:`incarnation-mismatch`,provisionerIncarnationId:i.provisionerIncarnationId}:i.allocationRef===null?()=>Y(n,i.executionAttemptId,`abandoned`,T`execution_id = ${e.executionId}
|
|
97
114
|
AND allocation_ref IS NULL
|
|
98
115
|
AND allocation_lifetime = ${`provisioner-process-bound`}
|
|
99
116
|
AND provisioner_incarnation_id = ${e.proof.provisionerIncarnationId}
|
|
100
|
-
AND ${
|
|
117
|
+
AND ${U(e.claim)}`,t):{kind:`allocated`,allocationRef:i.allocationRef}:{kind:`not-process-bound`,allocationLifetime:i.allocationLifetime}:{kind:`not-found`}},{kind:`recorded`}))},async recordAllocationTerminated(e){let t=_.parse(e.evidence);return b(n=>H(async()=>{let r=await B(n,e.claim);if(r.kind!==`authorized`)return{kind:r.kind};let{attempt:i}=r;return i.allocationRef===null?{kind:`not-allocated`}:()=>n.run(T`UPDATE test_provider_operation
|
|
101
118
|
SET obligation = ${`terminal-convergence`}, last_failure = ${JSON.stringify(t)}
|
|
102
119
|
WHERE execution_attempt_id = ${i.executionAttemptId}
|
|
103
|
-
AND ${
|
|
120
|
+
AND ${G(e.claim)}
|
|
104
121
|
AND EXISTS (SELECT 1 FROM test_execution_attempt
|
|
105
122
|
WHERE execution_attempt_id = ${i.executionAttemptId}
|
|
106
|
-
AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return
|
|
123
|
+
AND allocation_ref IS NOT NULL)`)},{kind:`recorded`}))},async recordInfrastructureFailure(e){return b(t=>H(async()=>{let n=await B(t,e.claim);if(n.kind!==`authorized`)return{kind:n.kind};let{attempt:r,operation:i}=n;return r.executionId===e.executionId?r.allocationRef===null?{kind:`not-allocated`}:D(c,i.obligation,`obligation`)===`terminal-convergence`?()=>Y(t,r.executionAttemptId,`infrastructure-failure`,T`execution_id = ${e.executionId}
|
|
107
124
|
AND allocation_ref IS NOT NULL
|
|
108
|
-
AND ${
|
|
109
|
-
AND ${
|
|
125
|
+
AND ${K(r.executionAttemptId)}
|
|
126
|
+
AND ${U(e.claim)}`):{kind:`not-terminated`}:{kind:`not-found`}},{kind:`recorded`}))},async registerRuntime(e){return b(async t=>{let n=0,r=await H(async()=>{let r=await C(t,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};if(r.settlement_kind!==null)return{kind:`resolved`};if(await N(t,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(r.allocation_ref===null||await M(t,e.executionAttemptId))return{kind:`not-allocated`};let i=k(r);return i.runtimeIncarnationId===e.runtimeIncarnationId?{kind:`duplicate`,runtimeGeneration:i.runtimeGeneration,runtimeReadyAt:i.runtimeReadyAt}:i.activeOperationId!==null&&i.activeOperationKind!==`runtime-probe`?{kind:`operation-active`,operationId:i.activeOperationId}:(n=i.runtimeGeneration+1,()=>t.run(T`UPDATE test_execution_attempt
|
|
127
|
+
SET runtime_generation = ${n},
|
|
128
|
+
runtime_incarnation_id = ${e.runtimeIncarnationId},
|
|
129
|
+
runtime_ready_at = NULL,
|
|
130
|
+
active_operation_id = NULL,
|
|
131
|
+
active_operation_kind = NULL,
|
|
132
|
+
active_operation_key = NULL,
|
|
133
|
+
active_operation_generation = NULL,
|
|
134
|
+
active_operation_admitted_at = NULL
|
|
135
|
+
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
136
|
+
AND execution_id = ${e.executionId}
|
|
137
|
+
AND runtime_generation = ${i.runtimeGeneration}
|
|
138
|
+
AND settlement_kind IS NULL
|
|
139
|
+
AND (active_operation_id IS NULL OR active_operation_kind = ${`runtime-probe`})
|
|
140
|
+
AND allocation_ref IS NOT NULL
|
|
141
|
+
AND NOT ${K(e.executionAttemptId)}
|
|
142
|
+
AND ${q()}`))},{kind:`applied`});return r.kind===`applied`?{kind:`registered`,runtimeGeneration:n}:r})},async admitOperation(e){let t=crypto.randomUUID(),n=d(new Date().toISOString()),r=e.operationKind!==`runtime-probe`,i=r?T`runtime_ready_at IS NOT NULL`:T`1 = 1`;return b(a=>H(async()=>{let o=await C(a,e.executionAttemptId);if(o===void 0||o.execution_id!==e.executionId)return{kind:`not-found`};if(o.settlement_kind!==null)return{kind:`resolved`};if(await N(a,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(o.allocation_ref===null||await M(a,e.executionAttemptId))return{kind:`not-allocated`};let s=k(o);return s.activeOperationId===null?s.operationStartGate===`closed`?{kind:`gate-closed`}:r&&s.runtimeReadyAt===null?{kind:`not-ready`}:s.runtimeGeneration===e.runtimeGeneration?()=>a.run(T`UPDATE test_execution_attempt
|
|
143
|
+
SET active_operation_id = ${t},
|
|
144
|
+
active_operation_kind = ${e.operationKind},
|
|
145
|
+
active_operation_key = ${e.admissionKey},
|
|
146
|
+
active_operation_generation = ${e.runtimeGeneration},
|
|
147
|
+
active_operation_admitted_at = ${n}
|
|
148
|
+
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
149
|
+
AND execution_id = ${e.executionId}
|
|
150
|
+
AND active_operation_id IS NULL
|
|
151
|
+
AND operation_start_gate = ${`open`}
|
|
152
|
+
AND runtime_generation = ${e.runtimeGeneration}
|
|
153
|
+
AND settlement_kind IS NULL
|
|
154
|
+
AND allocation_ref IS NOT NULL
|
|
155
|
+
AND NOT ${K(e.executionAttemptId)}
|
|
156
|
+
AND ${i}
|
|
157
|
+
AND ${q()}`):{kind:`stale-generation`,runtimeGeneration:s.runtimeGeneration}:s.activeOperationKey===e.admissionKey?{kind:`duplicate`,operationId:s.activeOperationId,runtimeGeneration:s.activeOperationGeneration??s.runtimeGeneration,admittedAt:s.activeOperationAdmittedAt??n}:{kind:`operation-active`,operationId:s.activeOperationId}},{kind:`admitted`,operationId:t,runtimeGeneration:e.runtimeGeneration,admittedAt:n}))},async completeOperation(e){return b(t=>H(async()=>{let n=await C(t,e.executionAttemptId);if(n===void 0)return{kind:`not-found`};if(n.settlement_kind!==null)return{kind:`resolved`};let r=k(n);return r.lastCompletedOperationId===e.operationId?{kind:`duplicate`}:r.activeOperationId===null?{kind:`not-active`}:r.activeOperationId===e.operationId?r.activeOperationGeneration===e.runtimeGeneration?()=>t.run(T`UPDATE test_execution_attempt
|
|
158
|
+
SET active_operation_id = NULL,
|
|
159
|
+
active_operation_kind = NULL,
|
|
160
|
+
active_operation_key = NULL,
|
|
161
|
+
active_operation_generation = NULL,
|
|
162
|
+
active_operation_admitted_at = NULL,
|
|
163
|
+
last_completed_operation_id = ${e.operationId}
|
|
164
|
+
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
165
|
+
AND settlement_kind IS NULL
|
|
166
|
+
AND active_operation_id = ${e.operationId}
|
|
167
|
+
AND active_operation_generation = ${e.runtimeGeneration}`):{kind:`stale-generation`}:{kind:`mismatch`,activeOperationId:r.activeOperationId}},{kind:`completed`}))},async markRuntimeReady(e){let t=d(e.readyAt);return b(n=>H(async()=>{let r=await C(n,e.executionAttemptId);if(r===void 0||r.execution_id!==e.executionId)return{kind:`not-found`};if(r.settlement_kind!==null)return{kind:`resolved`};if(await N(n,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};if(r.allocation_ref===null||await M(n,e.executionAttemptId))return{kind:`not-allocated`};let i=k(r);return i.runtimeGeneration===e.runtimeGeneration?i.runtimeReadyAt===null?i.activeOperationId===null?()=>n.run(T`UPDATE test_execution_attempt SET runtime_ready_at = ${t}
|
|
168
|
+
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
169
|
+
AND execution_id = ${e.executionId}
|
|
170
|
+
AND settlement_kind IS NULL
|
|
171
|
+
AND runtime_generation = ${e.runtimeGeneration}
|
|
172
|
+
AND runtime_ready_at IS NULL
|
|
173
|
+
AND active_operation_id IS NULL
|
|
174
|
+
AND allocation_ref IS NOT NULL
|
|
175
|
+
AND NOT ${K(e.executionAttemptId)}
|
|
176
|
+
AND ${q()}`):{kind:`operation-active`,operationId:i.activeOperationId}:{kind:`duplicate`,acceptedAt:i.runtimeReadyAt}:{kind:`stale-generation`}},{kind:`ready`,acceptedAt:t}))},async getAttemptControlState(e){return b(async t=>{let n=await C(t,e);return n===void 0?null:k(n)})},async getActiveAttempt(e,t){return b(async n=>{if(await N(n,e)!==t)return null;let r=await C(n,t);return r===void 0?null:A(r)})},canonicalizeOutcome(e){return a(n,e)},decodeOutcome(e){return i(n,e)},async commitOutcome(e){let t=e.result;return b(r=>H(async()=>{if(await N(r,e.executionId)!==e.executionAttemptId)return{kind:`fenced`};let a=await C(r,e.executionAttemptId);if(a===void 0)return{kind:`fenced`};let o=a.workflow_result;if(o!==null){let e=i(n,o);return s(o,t.text)?{kind:`duplicate`,outcome:e,text:o}:{kind:`conflict`}}return a.settlement_kind===null?async()=>{let n=await r.run(T`UPDATE test_execution_attempt SET workflow_result = ${t.text}
|
|
110
177
|
WHERE execution_attempt_id = ${e.executionAttemptId}
|
|
111
178
|
AND workflow_result IS NULL
|
|
112
179
|
AND settlement_kind IS NULL
|
|
113
|
-
AND ${
|
|
114
|
-
SET status = ${`settled`}, settlement_kind = ${`abandoned`}, claimable = ${0}
|
|
180
|
+
AND ${q()}`);return n.rowsAffected===0?n:Y(r,e.executionAttemptId,`outcome`,T`workflow_result IS NOT NULL`)}:{kind:`conflict`}},{kind:`accepted`,outcome:i(n,t.text),text:t.text}))},async abandonPendingAttempt(e,t){return b(n=>H(async()=>{if(await N(n,t)!==e)return{kind:`fenced`};let r=await C(n,e);if(r===void 0)return{kind:`fenced`};let i=A(r);return i.status===`allocated`?{kind:`allocated`}:i.status===`provisioning`?{kind:`provisioning`}:i.status===`settled`?{kind:i.settlementKind===`abandoned`?`already-abandoned`:`already-settled`}:()=>n.run(T`UPDATE test_execution_attempt
|
|
181
|
+
SET status = ${`settled`}, settlement_kind = ${`abandoned`}, claimable = ${0},
|
|
182
|
+
operation_start_gate = ${`closed`}
|
|
115
183
|
WHERE execution_attempt_id = ${e}
|
|
116
184
|
AND execution_id = ${t}
|
|
117
185
|
AND status = ${`pending`}
|
|
118
186
|
AND settlement_kind IS NULL
|
|
119
|
-
AND ${
|
|
120
|
-
WHERE execution_attempt_id = ${
|
|
187
|
+
AND ${q()}`)},{kind:`abandoned`}))},recovery:{async getAttemptWithAllocation(e){return b(async t=>{let n=await C(t,e);return n===void 0?null:A(n)})},async recordDiscoveredAllocation(e){return X(e,!1)},async evolveAllocationRef(e){let{currentRef:t,nextRef:n}=m(e);return b(r=>H(async()=>{let i=await B(r,e.claim);if(i.kind===`stale`)return{kind:`stale`,storedRef:i.attempt.allocationRef};if(i.kind!==`authorized`)return{kind:i.kind};let{attempt:a,attemptRow:s}=i;return a.executionId===e.executionId?a.allocationRef===null?{kind:`not-allocated`}:o(a.allocationRef,t)?()=>r.run(T`UPDATE test_execution_attempt SET allocation_ref = ${JSON.stringify(n)}
|
|
188
|
+
WHERE execution_attempt_id = ${a.executionAttemptId}
|
|
121
189
|
AND execution_id = ${e.executionId}
|
|
122
190
|
AND allocation_ref = ${s.allocation_ref}
|
|
123
|
-
AND ${
|
|
191
|
+
AND ${G(e.claim)}`):{kind:`stale`,storedRef:a.allocationRef}:{kind:`not-found`}},{kind:`evolved`}))},async getRecoverableAttempts(e){return b(async t=>{let n=new Date().toISOString();return(await t.all(T`SELECT * FROM test_execution_attempt
|
|
124
192
|
WHERE execution_id = ${e}
|
|
125
193
|
AND status = ${`allocated`}
|
|
126
194
|
AND settlement_kind IS NULL
|
|
127
195
|
AND allocation_ref IS NOT NULL
|
|
128
196
|
AND claimable = ${1}
|
|
129
197
|
AND (claim_expires_at IS NULL OR claim_expires_at >= ${n})
|
|
130
|
-
ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>
|
|
198
|
+
ORDER BY created_at ASC, execution_attempt_id ASC`)).map(e=>g(A(e)))})}}}}export{J as createSqliteAttemptRepository};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveMakaioHome as e}from"./runtime-node/makaio-config.mjs";import{t}from"./extension-package-provenance-aYrZuS4W.mjs";import{a as n,c as r,l as i,o as a,p as o}from"./runtime-registration-client-BTtFpt_k.mjs";import{mintOrRotateWorkflowExecutionBusSecret as s}from"./runtime-node/workflow-execution-bus-access.mjs";import*as c from"node:fs/promises";import{access as l}from"node:fs/promises";import*as u from"node:path";import{basename as d,join as f}from"node:path";import*as p from"node:crypto";import{randomUUID as m}from"node:crypto";import{constants as h}from"node:fs";import{createBusInstance as g,waitForSubscriptionPropagation as _}from"@makaio/framework/bus";import{AdapterSubjects as v,BoundedRecoveryEvidenceSchema as y,FrameworkContractNamespaces as b,FrameworkStorageNamespaces as x,PROVIDER_ALLOCATION_REF_VERSION as ee,ProviderAllocationRefSchema as te,RECOVERY_EVIDENCE_LIMITS as ne,WorkerCapabilitiesSchema as re,WorkerSubjects as ie,WorkflowSubjects as ae,WorkflowWorkerConfigSchema as oe,createWorkflowCancelSubject as se}from"@makaio/framework/contracts";import{ExtensionCoordinator as ce,KernelSubjects as le,coalesceExtensionOverrides as ue,filterEligibleExtensions as de}from"@makaio/framework/kernel";import{BaseService as fe}from"@makaio/framework/service-base";import{AdapterRuntimeSubjects as pe,registerAdapterRuntimeIdentityHandlers as me}from"@makaio/framework/services/adapter-runtime";import{CLIDetectionNamespace as he,CLIDetectionSubjects as ge}from"@makaio/framework/services/cli-detection/namespace";import{SessionOrchestratorToken as _e,ToolRegistryToken as ve,canonicalModelPackage as ye,createSubagentServicePackage as be,createToolContributionProcessor as xe,frameworkCorePackages as S,sessionBridgePackage as Se,sessionOrchestratorPackage as Ce,sessionPackage as we,sessionStoragePackage as Te,toolRegistryPackage as Ee}from"@makaio/framework/services";import{AdapterSubsystemSubjects as De}from"@makaio/framework/services/adapter-subsystem";import{createClientsCorePackage as Oe}from"@makaio/framework/clients";import{AdapterSubsystemToken as C,createAdapterSubsystemContributionProcessor as ke,createAdapterSubsystemPackage as Ae,orderAfterAdapterSubsystem as je}from"@makaio/framework/adapter-subsystem";import{execa as Me}from"execa";import Ne from"piscina";import{ExecutionAttemptAuthority as Pe,runAuthorityDispatchedAttempt as Fe}from"@makaio/framework/workflow-engine";import{runWorkflowOrchestrator as Ie}from"@makaio/framework/workflow-engine/workflow-orchestrator";function w(e){return e.on(v.getCapabilities,async t=>{let{adapterName:n,adapterId:r}=t.payload;if(r){await t.next();return}if(n){let r=await e.requestOptional(pe.resolveId,{adapterName:n}),i=r.handled?r.data.adapterId:void 0;i&&(t.payload.adapterId=i)}await t.next()},{priority:20})}function T(e){let{coordinator:t,configRepository:n,platformDefaults:r,prepareAuthRuntime:i,runtimeSnapshotHandlerPriority:a,runtimeDefinitionHandlerPriority:o}=e,s=Ae({configRepository:n,coordinator:t,platformDefaults:r,...i!==void 0&&{prepareAuthRuntime:i},...a!==void 0&&{runtimeSnapshotHandlerPriority:a},...o!==void 0&&{runtimeDefinitionHandlerPriority:o}});return t.registerContributionProcessor(ke({getAdapterSubsystemService:()=>t.getExtensionService(C)})),{adapterSubsystemPackage:s}}function E(e){let{bus:t,currentMachineId:n}=e,r=me(t,{currentMachineId:n,listKnownAdapterNames:e.listKnownAdapterNames??(async()=>{let{configs:e}=await t.request(De.listAdapterConfigs,{});return e.map(e=>e.name)}),...e.resolveLiveAdapterId!==void 0&&{resolveLiveAdapterId:e.resolveLiveAdapterId},...e.resolveLiveAdapterIdentity!==void 0&&{resolveLiveAdapterIdentity:e.resolveLiveAdapterIdentity},...e.listLiveAdapterIdentities!==void 0&&{listLiveAdapterIdentities:e.listLiveAdapterIdentities}}),i=w(t);return{cleanup:()=>{r.cleanup(),i()}}}function D(e,t){if(!(e instanceof Error))return!1;let{rootPackageName:n,subpath:r}=Le(t),i=(r===void 0?[t]:[t,n]).flatMap(e=>[`Cannot find package '${e}'`,`Cannot find module '${e}'`,`Cannot find package "${e}"`,`Cannot find module "${e}"`]),a=e;return(a.code===`ERR_MODULE_NOT_FOUND`||a.code===`MODULE_NOT_FOUND`)&&i.some(t=>e.message.includes(t))||a.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`&&r!==void 0&&e.message.includes(`Package subpath '${r}' is not defined by "exports"`)&&Re(e.message,n)?!0:i.some(t=>e.message.includes(t))}async function O(e){try{return await import(e)}catch(t){if(D(t,e))return null;throw t}}function Le(e){let t=e.split(`/`);return e.startsWith(`@`)?{rootPackageName:t.slice(0,2).join(`/`),subpath:t.length>2?`./${t.slice(2).join(`/`)}`:void 0}:{rootPackageName:t[0]??e,subpath:t.length>1?`./${t.slice(1).join(`/`)}`:void 0}}function Re(e,t){let n=t,r=t.replaceAll(`/`,`\\`);return e.includes(`/${n}/package.json`)||e.includes(`\\${r}\\package.json`)}async function k(e,t=process.env,n=process.platform){let r=t[Object.keys(t).find(e=>e.toUpperCase()===`PATH`)??`PATH`]??``,i=(t.PATHEXT??`.EXE;.CMD;.BAT;.COM`).split(`;`).filter(Boolean),a=n===`win32`?u.extname(e)===``?i:[``,...i]:[``];for(let t of r.split(u.delimiter)){let n=t.replace(/^"|"$/gu,``),r=u.resolve(n||process.cwd());for(let t of a){let n=u.join(r,`${e}${t}`);try{return await l(n,h.X_OK),n}catch{}}}}async function A(e,t=5e3,n=1e3){let{stdout:r}=await Me(e,[`--version`],{forceKillAfterDelay:n,timeout:t});return r}function ze(e){return e.match(/(\d+\.\d+\.\d+)/u)?.[1]??`unknown`}async function Be(e,t=k,n=A){try{let r=await t(e);if(r===void 0)return{binary:e,found:!1};let i=await n(r);return i.length===0?{binary:e,found:!1}:{binary:e,found:!0,path:r,version:ze(i)}}catch{return{binary:e,found:!1}}}async function Ve(e,t=k,n=A){return Promise.all(e.map(e=>Be(e,t,n)))}var He=class extends fe{constructor(e){super(e)}onInit(){this.registerHandler(ge.scan,async e=>{let t=await Ve(e.payload.binaries);e.setResult({results:t})})}};const j={name:`makaio.cli-detection`,displayName:`CLI Detection`,version:`0.1.0`,critical:!0,surface:`any`,namespaces:[he],create:e=>new He(e.bus)};function M(e,t){e.push(...Ue(t))}function Ue(e){return e===void 0?[]:typeof e==`function`?[e]:[...e]}function We(e,t=[]){let n=new Set([e]),r=new Set,i=new Map;for(let e of t)typeof e==`string`?n.add(e):(r.add(e.id),e.version!==void 0&&i.set(e.id,e.version));return{hosts:n,capabilities:r,...i.size>0?{capabilityVersions:i}:{}}}function Ge(e=[]){return e.some(e=>typeof e==`string`&&e===`node`)?e:[`node`,...e]}function N(e){return ue(de(qe(e.packages,e.configProvider),e.surface,e.runtimeEnvironment))}function Ke(e,n){let r=N(n),i=new Set(r.map(t));return e.filter(({ownerPackage:e})=>i.has(e)).map(({package:e})=>e)}function qe(e,t){return t?e.filter(e=>t.loadEnabled(e.name)!==!1):e}function P(e,t){return e.filter(e=>e.runtimeOwnership?.[t]===!0).map(e=>e.name)}function Je(e,t){let n=P(e,t);if(n.length>1)throw Error(`Multiple extensions own runtimeOwnership.${t}: ${n.join(`, `)}`)}function F(e){return Je(e,`sessionOrchestrator`),P(e,`sessionOrchestrator`).length===0}function Ye(e){return e===!0||F(e)?S:S.filter(e=>e.name!==_e.name)}function I(e,t,n){let r=[];try{for(let i of e){let e=i.runtimeBoot;e&&M(r,e.configure({bus:t,registerContributionProcessor:e=>{r.push(n.registerContributionProcessor(e))},forEachActiveExtension:e=>{n.forEachActiveExtension(e)}}))}}catch(e){let t=[];for(let e of[...r].reverse())try{e()}catch(e){t.push(e)}throw t.length>0?AggregateError([e,...t],`Extension boot contribution failed and rollback cleanup reported additional errors`,{cause:e}):e}return r}function Xe(){let e=process.env.MAKAIO_SKIP_EXTENSIONS;if(!e)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(t)}var Ze=class{pool;constructor(e){this.pool=new Ne({filename:e.workerEntry,maxThreads:e.maxConcurrency??4,idleTimeout:e.idleTimeoutMs??3e4})}async run(e,t){return this.pool.run(e,{signal:t})}onMessage(e){return this.pool.on(`message`,e),()=>this.pool.off(`message`,e)}async dispose(){await this.pool.destroy()}},L=class extends Error{code;constructor(e,t){super(e),this.code=t,this.name=`MaterializationError`}};function R(e,t,n){let r=u.resolve(t)+u.sep,i=u.resolve(e);if(i!==u.resolve(t)&&!i.startsWith(r))throw new L(`${n} escapes allowed root: ${e} is not within ${t}`,`containment-violation`)}async function z(e,t,n,r){let i=r??await c.realpath(t),a;try{a=await c.realpath(e)}catch{return e}let o=i+u.sep;if(a!==i&&!a.startsWith(o))throw new L(`${n} escapes allowed root via symlink: real path ${a} is not within ${i}`,`symlink-escape`);return a}function B(e){let t=e.indexOf(`-`);if(t===-1)throw new L(`Invalid SRI integrity format: ${e}`,`contribution-integrity-mismatch`);return{algorithm:e.slice(0,t),digest:e.slice(t+1)}}async function Qe(e,t){let n=await c.readFile(e);return p.createHash(t).update(n).digest(`base64`)}const V=new Set([`.git`,`node_modules`]);function $e(e){return V.has(e.toLowerCase())}async function et(e,t){let n=t.toLowerCase();if(!V.has(n))return!1;if(t===n)return!0;try{let[r,i]=await Promise.all([c.lstat(u.join(e,t)),c.lstat(u.join(e,n))]);return r.dev===i.dev&&r.ino===i.ino}catch(e){if(e.code===`ENOENT`)return!1;throw e}}const tt=V,nt=new Set([`.DS_Store`]);async function H(e,t){let n=p.createHash(t),r=[];async function i(t){let n=await c.readdir(t,{withFileTypes:!0});for(let a of n){let n=u.join(t,a.name);if(a.isSymbolicLink())throw new L(`Contribution package contains a symbolic link: ${u.relative(e,n)}`,`symlink-escape`);if(a.isDirectory()){tt.has(a.name)||await i(n);continue}if(a.isFile()){nt.has(a.name)||r.push(u.relative(e,n));continue}throw new L(`Contribution package contains an unsupported filesystem entry: ${u.relative(e,n)}`,`contribution-integrity-mismatch`)}}await i(e),r.sort();for(let t of r)n.update(t.split(u.sep).join(`/`)),n.update(`\0`),n.update(await c.readFile(u.join(e,t))),n.update(`\0`);return`${t}-${n.digest(`base64`)}`}async function U(e,t=`sha256`){let n=p.createHash(t),r=[];async function i(t){let n=await c.readdir(t,{withFileTypes:!0});for(let a of n){let n=u.join(t,a.name);if(!await et(t,a.name)){if(a.isDirectory()){await i(n);continue}if(a.isFile()){r.push(u.relative(e,n));continue}throw a.isSymbolicLink()?new L(`Workspace root contains a symbolic link: ${u.relative(e,n)}`,`symlink-escape`):new L(`Workspace root contains an unsupported filesystem entry: ${u.relative(e,n)}`,`unsupported-filesystem-entry`)}}}await i(e),r.sort();for(let t of r){n.update(t),n.update(`\0`);let r=await c.readFile(u.join(e,t));n.update(r),n.update(`\0`)}return`${t}-${n.digest(`base64`)}`}async function W(e,t,n){let r=u.join(t,`node_modules`,e.packageName);R(r,t,`Contribution package directory`),await z(r,t,`Contribution package directory`,n);let i=u.join(r,`package.json`),a;try{a=await c.readFile(i,`utf-8`)}catch{throw new L(`Contribution package not found: ${e.packageName} (expected at ${r})`,`contribution-missing`)}let o=JSON.parse(a);if(o.name!==e.packageName)throw new L(`Contribution identity mismatch: expected ${e.packageName}, found ${o.name??`<none>`}`,`contribution-missing`);if(o.version!==e.version)throw new L(`Contribution version mismatch for ${e.packageName}: expected ${e.version}, found ${o.version??`<none>`}`,`contribution-version-mismatch`);let s=u.join(r,e.entrypoint);R(s,r,`Contribution entrypoint`),await z(s,t,`Contribution entrypoint`,n);try{await c.access(s)}catch{throw new L(`Contribution entrypoint not found for ${e.packageName}: ${e.entrypoint}`,`contribution-entrypoint-mismatch`)}let{algorithm:l}=B(e.integrity),d;try{d=await H(r,l)}catch(t){if(t instanceof L)throw t;let n=typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`?t.code:void 0;throw n!==void 0&&!n.startsWith(`ERR_`)?new L(`Contribution package cannot be read for ${e.packageName}`,`contribution-entrypoint-mismatch`):t}if(d!==e.integrity)throw new L(`Contribution integrity mismatch for ${e.packageName}: expected ${e.integrity}, computed ${d}`,`contribution-integrity-mismatch`);return s}async function G(e,t,n){let r=await n.resolveWorkspaceRoot(e.workspaceId);if(r===void 0)throw new L(`Unknown workspace ID: ${e.workspaceId}`,`unknown-workspace`);try{if(!(await c.stat(r)).isDirectory())throw new L(`Workspace root is not a directory: ${r}`,`containment-violation`)}catch(e){throw e instanceof L?e:new L(`Workspace root does not exist: ${r}`,`containment-violation`)}let i=await c.realpath(r),a=u.resolve(r,e.sourcePath);if(R(a,r,`Source path`),u.relative(r,a).split(u.sep).some($e))throw new L(`Workflow source path selects excluded workspace content: ${e.sourcePath}`,`source-path-mismatch`);await z(a,r,`Source path`,i);let o=await U(r);if(o!==e.rootDigest)throw new L(`Workspace root digest mismatch: expected ${e.rootDigest}, computed ${o}`,`digest-mismatch`);try{await c.access(a)}catch{throw new L(`Workflow source file not found: ${a}`,`source-missing`)}return{workspaceRoot:r,sourcePath:a,contributionEntrypoints:await Promise.all(t.map(e=>W(e,r,i))),platform:process.platform,arch:process.arch}}var K=class{options;manifest;pool;constructor(e){this.options=e,this.manifest=e.manifest}async run(e,t,n){this.pool??=new Ze(this.options);let r=n??this.manifest,i=await this.materializeTask(e,r,t);return{state:`uncommitted`,result:await this.pool.run(i,t)}}runWithReadiness(e,t,n,r){this.pool??=new Ze(this.options);let i=this.pool,a,s=!1,c,l=new Promise((t,n)=>{c=n,a=i.onMessage(n=>{o(n)&&n.executionAttemptId===r.executionAttemptId&&(n.executionId!==e.executionId||n.cancelSubject!==e.cancelSubject||(s=!0,a?.(),t(n)))})}),u=n??this.manifest,d=this.materializeTask(e,u,t).then(e=>i.run({...e,kind:`attempt-bound`,executionAttemptId:r.executionAttemptId},t));return d.then(()=>{s||(s=!0,a?.(),c(Error(`Workflow worker completed before ready signal: ${e.executionId}`)))},e=>{s||(s=!0,a?.(),c(e instanceof Error?e:Error(String(e))))}),{result:d,ready:l}}async dispose(){await this.pool?.dispose()}async materializeTask(e,t,n){if(n.throwIfAborted(),!(e.source.kind===`path`||t.contributionRefs.length>0))return{kind:`unbound`,config:e,manifest:t,contributionEntrypoints:[]};let r=e.materializationSpec;if(r?.kind!==`local-directory`)throw Error(`ThinWorkflowPiscinaRunner requires a local-directory materialization spec for path-backed workflows or declared contributions.`);if(this.options.resolveWorkspaceRoot===void 0)throw Error(`ThinWorkflowPiscinaRunner requires a host workspace-root resolver for local-directory materialization.`);let i=await G(r,t.contributionRefs,{resolveWorkspaceRoot:this.options.resolveWorkspaceRoot});if(n.throwIfAborted(),e.source.kind!==`path`)throw Error(`local-directory materialization requires a path-backed workflow source.`);return{kind:`unbound`,config:{...e,source:{kind:`path`,path:i.sourcePath}},manifest:t,contributionEntrypoints:i.contributionEntrypoints}}};function q(e){return e.mode===`source`?f(e.moduleDir,`workflow-worker`,`worker-entry.ts`):f(e.moduleDir,`workflow-worker`,`worker-entry.mjs`)}var J=class{options;constructor(e){this.options=e}async run(e,t,n,r){let i={...e,terminalAuthority:`authority`},a=n??this.options.manifest,o=this.options.requirements,s=r?.dispatchMetadata;return{state:`authority-committed`,result:await Fe({authority:this.options.authority,executionId:e.executionId,dispatch:e=>this.options.dispatch({executionAttemptId:e,config:i,...a!==void 0&&{manifest:a},...o!==void 0&&{requirements:o},...s!==void 0&&{metadata:s}},t)})}}},rt=class{#e;constructor(e){this.#e=e.bus}async run(e,t,n){let a=oe.parse(e),o=await i(a);return{state:`uncommitted`,result:await Ie({config:await r(a,o,this.#e,t),loaded:o,bus:this.#e,signal:t})}}};function it(){return{contributionRefs:[]}}function at(e){if(e.workflowRunner?.mode===`worker`&&!e.executionAttemptRepository)throw Error(`Worker dispatch mode requires an ExecutionAttemptRepository. Pass 'executionAttemptRepository' to createNodeWorkflowRunnerPackageOptions when workflowRunner.mode is 'worker'.`);let t=e.executionAttemptRepository?new Pe(e.executionAttemptRepository):void 0,n=d(e.runtimeModuleDir)===`src`?`source`:`dist`,r=ot({moduleDir:e.runtimeModuleDir,defaultWorkerEntryMode:n,runner:e.workflowRunner,bus:e.bus,authority:t});return{...r!==void 0&&{workflowRunner:r},executorConfig:{busUrl:e.busUrl,busAuth:{kind:`none`},platformDefaults:e.platformDefaults,makaioHome:e.makaioHome},...e.executionAttemptRepository!==void 0&&{executionAttemptRepository:e.executionAttemptRepository},...t!==void 0&&{executionAttemptAuthority:t},...e.workflowMaterializationSpecResolvers!==void 0&&{workflowMaterializationSpecResolvers:e.workflowMaterializationSpecResolvers}}}function ot(e){let{runner:t}=e;if(t)switch(t.mode){case void 0:case`in-process`:if(e.bus===void 0)throw Error(`InProcessWorkflowRunner requires a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'in-process'.`);return new rt({bus:e.bus});case`worker`:{if(e.authority===void 0)throw Error(`WorkerRunner requires an ExecutionAttemptAuthority. Pass 'authority' to createNodeWorkflowRunner when runner.mode is 'worker'.`);let n=e.bus,r=t.dispatch??(n===void 0?void 0:(e,t)=>n.request(ie.dispatch,{executionAttemptId:e.executionAttemptId,config:e.config,manifest:e.manifest,requirements:e.requirements,metadata:e.metadata},{signal:t}));if(r===void 0)throw Error(`WorkerRunner requires either a dispatch function or a bus instance. Pass 'bus' to createNodeWorkflowRunner when runner.mode is 'worker'.`);return new J({dispatch:r,authority:e.authority,...t.manifest!==void 0&&{manifest:t.manifest},...t.requirements!==void 0&&{requirements:t.requirements}})}case`piscina`:return new K({workerEntry:t.workerEntry??q({moduleDir:e.moduleDir,mode:t.workerEntryMode??e.defaultWorkerEntryMode}),manifest:t.manifest??it(),...t.resolveWorkspaceRoot!==void 0&&{resolveWorkspaceRoot:t.resolveWorkspaceRoot},maxConcurrency:t.maxConcurrency,idleTimeoutMs:t.idleTimeoutMs})}}const st=new Set([`accepted`,`duplicate`]);var Y=class extends Error{decision;result;reason;constructor(e,t,n=`authority-rejected`){super(`Outcome delivery ${n===`deadline-exceeded`?`deadline exceeded`:`rejected by Authority`} (decision=${e}, executionId=${t.executionId}, status=${t.status})`),this.decision=e,this.result=t,this.reason=n,this.name=`OutcomeDeliveryError`}};function X(e){return new Y(`deadline-exceeded`,e,`deadline-exceeded`)}function ct(e){let t={maxRetries:e?.maxRetries??7,baseDelayMs:e?.baseDelayMs??1e3,maxDelayMs:e?.maxDelayMs??3e4,deadlineMs:e?.deadlineMs??12e4};if(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0)throw TypeError(`Outcome submission maxRetries must be a non-negative safe integer, got ${t.maxRetries}`);for(let[e,n]of Object.entries({baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,deadlineMs:t.deadlineMs}))if(!Number.isFinite(n)||n<=0)throw TypeError(`Outcome submission ${e} must be a positive finite number, got ${n}`);return t}async function lt(e,t,n,r){let i=t.baseDelayMs*2**(e-1),a=n-Date.now(),o=Math.min(i,t.maxDelayMs,a);await new Promise(e=>setTimeout(e,o));let s=n-Date.now();if(s<=0)return!1;if(r!==void 0){let e;try{await Promise.race([r(),new Promise(t=>{e=setTimeout(t,s)})])}catch{}finally{e!==void 0&&clearTimeout(e)}}return Date.now()<n}async function Z(e,t,n){let r=ct(n?.retry),i=n?.reconnect,a=Date.now()+r.deadlineMs,o;for(let n=0;n<=r.maxRetries;n++){if(a-Date.now()<=0||n>0&&!await lt(n,r,a,i))throw X(t.result);try{let n=a-Date.now();if(n<=0)throw X(t.result);let{decision:r}=await e.request(ie.control.outcome.submit,{executionAttemptId:t.executionAttemptId,executionId:t.executionId,result:t.result},{timeout:n});if(st.has(r))return r;throw new Y(r,t.result)}catch(e){if(e instanceof Y)throw e;if(o=e,Date.now()>=a)throw X(t.result)}}throw o??X(t.result)}const ut={maxRetries:3,baseDelayMs:200,maxDelayMs:2e3,deadlineMs:1e4},dt={persistentStorage:!0,customCapabilities:[`workflow.local-runtime`,`workflow.thin-runner`],suspensionStrategy:`wait-in-process`,supportsRecovery:!1,materializationModes:[`local-directory`]};function ft(e){let t=new Set,n;return{conclude:r=>{if(n!==void 0)return;n={evidence:y.parse({source:e.slice(0,ne.source),summary:r.slice(0,ne.summary),observedAt:new Date().toISOString()})};let i=[...t];t.clear();for(let e of i)try{e(n)}catch(e){console.error(`[PiscinaThinWorkflowProvider] Infrastructure-conclusion observer failed:`,e)}},observe:e=>n===void 0?(t.add(e),()=>t.delete(e)):(e(n),()=>void 0)}}var pt=class{executionAttemptId;controller;detachCallerAbort;infrastructure;revokeBusIdentity;constructor(e,t,n,r,i){this.executionAttemptId=e,this.controller=t,this.detachCallerAbort=n,this.infrastructure=r,this.revokeBusIdentity=i}cancel(e){return this.controller.abort(e??`Worker cancelled`),this.detachCallerAbort(),Promise.resolve()}terminate(){return this.controller.abort(`Worker terminated`),this.detachCallerAbort(),this.revokeBusIdentity(),Promise.resolve()}release(){return this.detachCallerAbort(),this.revokeBusIdentity(),Promise.resolve()}observeInfrastructureConclusion(e){return this.infrastructure.observe(e)}},mt=class{options;environment=`piscina`;allocationLifetime=`provisioner-process-bound`;baseCapabilities;constructor(e){this.options=e,this.baseCapabilities=re.parse({...dt,...e.baseCapabilities,suspensionStrategy:e.baseCapabilities?.suspensionStrategy??dt.suspensionStrategy,supportsRecovery:!1})}get id(){return this.options.id}get displayName(){return this.options.displayName}async provision(e,t){t.throwIfAborted();let n=new AbortController,r=ft(this.id),i=()=>{n.abort(t.reason)};t.addEventListener(`abort`,i,{once:!0});let a=()=>t.removeEventListener(`abort`,i),o;try{let{executionAttemptId:i,executionId:c,workerConfig:l}=e;if(!l.busUrl)throw Error(`PiscinaThinWorkflowProvider requires a bus URL to provision an execution attempt (executionAttemptId=${i}, executionId=${c})`);let u=this.buildAllocationRef(i),d=s({executionAttemptId:i,executionId:c});o=d.cleanup;let f=new pt(i,n,a,r,d.cleanup);t.throwIfAborted();let p=this.options.runner.runWithReadiness({...l,busAuth:{kind:`hmac`,secret:d.secret}},n.signal,e.workerManifest,{executionAttemptId:i});return p.ready.then(()=>this.submitOutcomeOnSettlement(p.result,c,i,l.workflowId,r.conclude),e=>{n.abort(e),p.result.catch(()=>void 0),r.conclude(`Piscina worker for attempt '${i}' was refused before its workflow run was admitted: `+(e instanceof Error?e.message:String(e)))}),{kind:`allocated`,allocationRef:u,handle:f}}catch(e){throw n.abort(e),a(),o?.(),e}}async submitOutcomeOnSettlement(e,t,n,r,i){let a;try{a=await e}catch(e){a={executionId:t,workflowId:r,status:`failed`,error:e instanceof Error?e.message:String(e)}}try{let e={...ut,...this.options.outcomeRetry};await Z(this.options.bus,{executionAttemptId:n,executionId:t,result:a},{retry:e})}catch(e){e instanceof Y?console.error(`[PiscinaThinWorkflowProvider] Outcome rejected for execution '${t}' attempt '${n}' (decision=${e.decision}):`,e):console.error(`[PiscinaThinWorkflowProvider] Failed to submit outcome for execution '${t}' attempt '${n}':`,e),i(`Piscina worker for attempt '${n}' ended without an acknowledged outcome because outcome submission could not be completed`)}}buildAllocationRef(e){let t={version:ee,providerId:this.id,providerData:{executionAttemptId:e,allocatedAt:Date.now()}};return te.parse(t)}};const ht=[Te,Se,we];function gt(e){let t;return()=>(t??=(async()=>{let t=[];for(let n of[...e].reverse())try{await n()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Isolated workflow runtime shutdown reported errors`)})(),t)}function _t(e,t,n){return E({bus:e,currentMachineId:n,resolveLiveAdapterId:e=>t.getExtensionService(C)?.resolveLiveAdapterId(e),resolveLiveAdapterIdentity:e=>t.getExtensionService(C)?.resolveLiveAdapterIdentity(e),listLiveAdapterIdentities:()=>t.getExtensionService(C)?.getLiveAdapterIdentities()??[]})}async function vt(e){let t=g();t.registerNamespaces([...b,...x]);let{context:n}=e,r=new ce(t,{surface:`headless`,extensionContextBase:{cwd:n.cwd,platform:n.platform,homedir:n.homedir,makaioHome:n.makaioHome,username:n.username,machineId:n.machineId,tryImport:O}}),i,a=[()=>t.disconnect()],o=gt(a);try{await e.connectAuthority(t);let s=[...e.contributedPackages,...await e.loadContributedPackages?.(t)??[]],{adapterSubsystemPackage:c}=T({coordinator:r,configRepository:e.configRepository,platformDefaults:{cwd:n.cwd},runtimeSnapshotHandlerPriority:1,runtimeDefinitionHandlerPriority:1,...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}}),l=Oe({definitions:s.flatMap(e=>e.clients??[]),binaryResolutionPolicy:`global-only`});r.registerContributionProcessor(xe());let u=[...ht,c,ye,...F(s)?[Ce]:[],be(1),Ee,j,l,...je(s)];r.load(u),a.push(...I(u,t,r)),a.push(()=>r.shutdown()),await r.startAll(),i=_t(t,r,n.machineId),a.push(()=>{i?.cleanup(),i=void 0});let d=r.getExtensionService(ve);if(d===void 0)throw Error(`Isolated workflow tool registry did not start.`);for(let t of e.toolsets)await d.register(t);return await t.emit(le.ready,{machineId:n.machineId}),{bus:t,coordinator:r,machineId:n.machineId,shutdown:o}}catch(e){throw await o().catch(()=>void 0),e}}function Q(e,t){return{executionId:e,workflowId:t,status:`cancelled`,reason:`Execution cancelled`}}async function $(e,t,n){let r=new AbortController,i=e.on(se(t),()=>{r.abort()}),a=()=>{r.abort()};return n?.addEventListener(`abort`,a,{once:!0}),n?.aborted&&r.abort(),await _(i),{signal:r.signal,cleanup:()=>{n?.removeEventListener(`abort`,a),i()}}}function yt(t,n){let r=e();return{cwd:t.workspaceRoot,platform:t.platform,homedir:r,makaioHome:r,username:`workflow-worker`,machineId:n}}async function bt(e,t,n,r,i,a){return await vt({connectAuthority:async n=>{await e.connectBus(n,t,i)},contributedPackages:[...r],configRepository:e.configRepository,context:yt(n,a),toolsets:[...e.toolsets],...e.prepareAuthRuntime!==void 0&&{prepareAuthRuntime:e.prepareAuthRuntime}})}async function xt(e,t,n){let{executionId:r,executionAttemptId:i}=e,a=Q(r,n);return{result:a,decision:await Z(t,{executionAttemptId:i,executionId:r,result:a},{retry:e.outcomeRetry,reconnect:()=>t.reconnect()})}}async function St(e,t,n,r,i){let{executionId:a,executionAttemptId:o}=e,s;try{s=await e.execute(t.bus,n,r,i)}catch(e){s=i.aborted&&e instanceof DOMException&&e.name===`AbortError`?Q(a,n.workflowId):{executionId:a,workflowId:n.workflowId,status:`failed`,error:e instanceof Error?e.message:String(e)}}let c=await Z(t.bus,{executionAttemptId:o,executionId:a,result:s},{retry:e.outcomeRetry,reconnect:()=>t.bus.reconnect()});if(e.onPostCommit!==void 0)try{await e.onPostCommit(s,c)}catch{}return{result:s,decision:c}}async function Ct(e,t,r,i,a,o,s,c){let l=await $(r,i.cancelSubject),u=AbortSignal.any([a,l.signal]),d=u,f,p,m,h;try{u.throwIfAborted();let g=await e.materialize(i,u),_=g.context;h=g.cleanup,u.throwIfAborted();let v=await e.loadContributions(_,u);u.throwIfAborted(),f=await bt(e,t,_,v,u,o),p=await $(f.bus,i.cancelSubject,l.signal),m=await n(f.bus,{executionAttemptId:e.executionAttemptId,...s},{}),l.cleanup(),c(),r.disconnect();let y=AbortSignal.any([a,p.signal]);return d=y,y.throwIfAborted(),await St(e,f,i,_,y)}catch(t){if(!(d.aborted&&t instanceof DOMException&&t.name===`AbortError`))throw t;return await xt(e,f?.bus??r,i.workflowId)}finally{l.cleanup(),p?.cleanup(),m?.cleanup(),f!==void 0&&await f.shutdown().catch(()=>void 0),h!==void 0&&await h().catch(()=>void 0)}}async function wt(e,t){t.throwIfAborted();let r=m(),i=await e.bootstrap(t);t.throwIfAborted();let o=g();o.registerNamespaces([...b,...x]);let s,c=()=>{let e=s;s=void 0,e?.cleanup()};try{await e.connectBus(o,i,t),s=await n(o,{executionAttemptId:e.executionAttemptId,runtimeIncarnationId:r},{});let{runtimeGeneration:l}=await a(o,{executionAttemptId:e.executionAttemptId,runtimeIncarnationId:r,endpoint:s,signal:t});return await Ct(e,i,o,await o.request(ae.getRunContext,{executionId:e.executionId},{signal:t}),t,`headless-worker-${e.executionAttemptId}`,{runtimeIncarnationId:r,runtimeGeneration:l},c)}finally{c();try{o.disconnect()}catch{}}}export{j as A,M as C,N as D,I as E,w as F,O as M,E as N,Ke as O,T as P,We as S,Xe as T,U as _,Y as a,B as b,at as c,q as d,K as f,H as g,z as h,st as i,D as j,Ye as k,rt as l,R as m,vt as n,Z as o,L as p,mt as r,ot as s,wt as t,J as u,Qe as v,Ge as w,W as x,G as y};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ProviderAllocationRefSchema as e,WorkerAllocationLifetimeSchema as t}from"@makaio/framework/contracts";function n(e){let t=Date.parse(e);if(Number.isNaN(t))throw Error(`Expected an ISO-8601 timestamp, received '${e}'`);return t}function r(e){return new Date(n(e)).toISOString()}function i(e){return typeof e==`object`&&!!e}function a(e){if(!(!i(e)||Object.isFrozen(e))){Object.freeze(e);for(let t of Object.values(e))a(t)}}function o(e,t){let n=t(structuredClone(e));return a(n),n}function s(t){return o(t,t=>e.parse(t))}function c(e){return t.parse(e)}function l(t){let n=e.parse(t.currentRef),r=s(t.nextRef);if(n.providerId!==r.providerId)throw Error(`Allocation reference evolution must keep one provider, received '${n.providerId}' and '${r.providerId}'`);return{currentRef:n,nextRef:r}}function u(e,t){if(e.providerId!==t.providerId)throw Error(`Allocation reference for attempt '${e.executionAttemptId}' names provider '${t.providerId}' but the attempt is bound to '${e.providerId??`no provider`}'`)}function d(e,t){let r=n(e.createdAt)-n(t.createdAt);return r===0?e.executionAttemptId<t.executionAttemptId?-1:+(e.executionAttemptId>t.executionAttemptId):r}function f(e){let{status:t,claimable:n,settlementKind:r,allocationRef:i,providerId:a}=e,{allocationLifetime:o,provisionerIncarnationId:s}=e;if(t!==`allocated`||n!==!0||r!=null||i===null||a===null||o===null||s===null)throw Error(`Attempt '${e.executionAttemptId}' was selected as recoverable but is not: status '${t}', claimable '${String(n)}', settlement '${String(r)}', allocation '${i===null?`none`:`present`}', provider '${String(a)}', lifetime '${String(o)}', provisioner '${String(s)}'`);return{...e,status:t,claimable:!0,settlementKind:null,allocationRef:i,providerId:a,allocationLifetime:o,provisionerIncarnationId:s}}export{s as a,f as c,c as i,n,l as o,r,u as s,d as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{pathToFileURL as e}from"node:url";import{mkdir as t,rm as n,writeFile as r}from"node:fs/promises";import{basename as i,join as a}from"node:path";import{randomBytes as o}from"node:crypto";import{WorkflowDefinitionSchema as s,WorkflowError as c,WorkflowErrorCode as l}from"@makaio/framework/contracts";import{tmpdir as u}from"node:os";import{AUTOMATION_TRIGGER_BUILTINS_OWNER as d,AutomationTriggerBindingRuntime as f,busBackedAutomationTriggers as p}from"@makaio/framework/services/automation-trigger";import{assertWorkflowTriggerPayload as m,compileWorkflowTriggerBindingFilter as h}from"@makaio/framework/workflow-engine/workflow-trigger-binding-consumer";function g(e,t,n=[]){return{type:`makaio.workflow-worker.ready`,executionId:e,cancelSubject:t,adapters:n}}function _(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`makaio.workflow-worker.ready`&&typeof t.executionId==`string`&&typeof t.cancelSubject==`string`&&Array.isArray(t.adapters)&&t.adapters.every(e=>typeof e==`string`)}function v(e){if(typeof e!=`object`||!e)throw new c(l.NOT_EXECUTABLE,`Invalid workflow module default export: expected an object with 'definition' and 'runtimeHandlers', got ${typeof e}.`);let t=e;if(!(t.runtimeHandlers instanceof Map))throw new c(l.NOT_EXECUTABLE,`Invalid workflow module default export: 'runtimeHandlers' must be a Map instance.`);let n=s.safeParse(t.definition);if(!n.success)throw new c(l.NOT_EXECUTABLE,`Invalid workflow module default export: 'definition' must satisfy WorkflowDefinitionSchema. `+n.error.message);let r=y(t.zodSchemas)?t.zodSchemas:void 0,i=t.runtimeLoopGates;if(i!==void 0&&!(i instanceof Map))throw new c(l.NOT_EXECUTABLE,`Invalid workflow module default export: 'runtimeLoopGates' must be a Map instance when provided.`);return{definition:n.data,runtimeHandlers:t.runtimeHandlers,...r===void 0?{}:{zodSchemas:r},...i===void 0?{}:{runtimeLoopGates:i}}}function y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`gates`in e}async function b(e,s){let c=i(e);if(!c||c===`.`||c===`..`)throw Error(`Invalid workflow source filename: ${e}`);let l=a(u(),`makaio-wf-${o(6).toString(`hex`)}`);await t(l,{recursive:!0});let d=a(l,c.endsWith(`.mjs`)?c:`${c}.mjs`);try{await r(d,s,`utf8`)}catch(e){throw await n(l,{recursive:!0,force:!0}).catch(()=>{}),e}return{tempDir:l,tempPath:d}}function x(e){return typeof e==`object`&&e&&Array.isArray(e.workflows)?e.workflows.map(v):[v(e)]}async function S(t){if(t.kind===`path`)return x((await import(e(t.path).href)).default);let{tempDir:r,tempPath:i}=await b(t.filename,t.source);try{return x((await import(e(i).href)).default)}finally{await n(r,{recursive:!0,force:!0})}}async function C(e){if(e.kind===`definition`)throw new c(l.NOT_EXECUTABLE,`Definition-sourced workers are handled by the workflow executor, not the file loader. Received source: ${JSON.stringify(e)}`);let t=await S(e);if(t.length!==1)throw new c(l.NOT_EXECUTABLE,`loadWorkflowModule expects a single workflow export, but the module exported ${String(t.length)} workflows. Use loadWorkflowModules for bundle exports.`);return t[0]}async function w(e){if(e.source.kind===`definition`){if(e.definition===void 0)throw Error(`Definition-sourced worker config for workflowId "${e.source.workflowId}" is missing the required 'definition' field. Ensure the executor populates WorkflowWorkerConfig.definition before dispatching.`);return{definition:e.definition,runtimeHandlers:new Map}}let t=await C(e.source);return T(e,t),e.definition===void 0?t:{...t,definition:e.definition}}function T(e,t){if(e.workflowId!==e.executionId&&t.definition.id!==e.workflowId)throw new c(l.SOURCE_MISMATCH,`Source-backed workflow for logical workflow '${e.workflowId}' loaded definition '${t.definition.id}'.`)}const E=`[WorkflowWorkerAwaitTrigger]`;function D(e){let t=p(e);return{resolveRegistration:e=>{let n=t.find(t=>t.kind===e);return n===void 0?void 0:{owner:d,type:n}}}}async function O(e,t,n){let r=new f(D(e)),i=t.flatMap(e=>{let t=r.prepareBinding(e);return t===void 0?(console.warn(`${E} skipping binding '${e.kind}': awaiting it inside a worker is unsupported. A worker carries only bus-backed trigger types; schedules and extension-contributed sources are activated by the host that owns their placement.`),[]):t.workflowCompatible?[{binding:e,prepared:t}]:(console.warn(`${E} skipping binding '${e.kind}': its event payload does not have an object root.`),[])});if(i.length===0){await r.close();return}try{if(n.aborted)throw n.reason??Error(`Await-trigger aborted`);let e=Promise.withResolvers();e.promise.catch(()=>void 0);let t=()=>{e.reject(n.reason??Error(`Await-trigger aborted`))};n.addEventListener(`abort`,t,{once:!0});try{return await Promise.all(i.map(async({binding:t,prepared:n})=>{let r=h(t);await n.subscribe(t=>{r(t.payload)&&e.resolve(m(t.payload))})})),await e.promise}finally{n.removeEventListener(`abort`,t)}}finally{await r.close()}}async function k(e,t,n,r){let i=t.definition.triggers??[];if(e.triggerMode!==`await-trigger`||i.length===0)return e;let a=await O(n,i,r);return a===void 0?e:{...e,triggerPayload:a}}export{g as a,S as i,w as n,_ as o,C as r,k as t};
|