obeli_sk_executor/
worker.rs

1use async_trait::async_trait;
2use chrono::{DateTime, Utc};
3use concepts::ExecutionId;
4use concepts::ExecutionMetadata;
5use concepts::FunctionMetadata;
6use concepts::PermanentFailureKind;
7use concepts::TrapKind;
8use concepts::prefixed_ulid::ExecutionIdDerived;
9use concepts::prefixed_ulid::RunId;
10use concepts::storage::HistoryEvent;
11use concepts::storage::Version;
12use concepts::storage::http_client_trace::HttpClientTrace;
13use concepts::{
14    FinishedExecutionError, StrVariant,
15    storage::{DbError, JoinSetResponseEvent},
16};
17use concepts::{FunctionFqn, ParamsParsingError, ResultParsingError};
18use concepts::{Params, SupportedFunctionReturnValue};
19use tracing::Span;
20
21#[async_trait]
22pub trait Worker: Send + Sync + 'static {
23    async fn run(&self, ctx: WorkerContext) -> WorkerResult;
24
25    // List exported functions without extensions.
26    // Used by executor.
27    // TODO: Rename to `exported_functions_noext`
28    fn exported_functions(&self) -> &[FunctionMetadata];
29}
30
31#[must_use]
32#[derive(Debug)]
33pub enum WorkerResult {
34    Ok(
35        SupportedFunctionReturnValue,
36        Version,
37        Option<Vec<HttpClientTrace>>,
38    ),
39    // If no write occured, the watcher will timeout the execution and retry after backoff which avoids the busy loop
40    DbUpdatedByWorkerOrWatcher,
41    Err(WorkerError),
42}
43
44#[derive(Debug)]
45pub struct WorkerContext {
46    pub execution_id: ExecutionId,
47    pub run_id: RunId,
48    pub metadata: ExecutionMetadata,
49    pub ffqn: FunctionFqn,
50    pub params: Params,
51    pub event_history: Vec<HistoryEvent>,
52    pub responses: Vec<JoinSetResponseEvent>,
53    pub version: Version,
54    pub execution_deadline: DateTime<Utc>,
55    pub can_be_retried: bool,
56    pub worker_span: Span,
57}
58
59#[derive(Debug, thiserror::Error)]
60pub enum WorkerError {
61    // retriable errors
62    // Used by activity worker
63    #[error("activity {trap_kind}: {reason}")]
64    ActivityTrap {
65        reason: String,
66        trap_kind: TrapKind,
67        detail: Option<String>,
68        version: Version,
69        http_client_traces: Option<Vec<HttpClientTrace>>,
70    },
71    #[error("{reason_kind}")]
72    ActivityPreopenedDirError {
73        reason_kind: &'static str,
74        reason_inner: String,
75        version: Version,
76    },
77    // Used by activity worker, must not be returned when retries are exhausted.
78    #[error("activity returned error")]
79    ActivityReturnedError {
80        detail: Option<String>,
81        version: Version,
82        http_client_traces: Option<Vec<HttpClientTrace>>,
83    },
84    // Resources are exhausted, retry after a delay as Unlocked, without increasing temporary event count.
85    #[error("limit reached: {reason}")]
86    LimitReached { reason: String, version: Version },
87    // Used by activity worker, best effort. If this is not persisted, the expired timers watcher will append it.
88    #[error("temporary timeout")]
89    TemporaryTimeout {
90        http_client_traces: Option<Vec<HttpClientTrace>>,
91        version: Version,
92    },
93    #[error(transparent)]
94    DbError(DbError),
95    // non-retriable errors
96    #[error("fatal error: {0}")]
97    FatalError(FatalError, Version),
98}
99
100#[derive(Debug, thiserror::Error)]
101pub enum FatalError {
102    /// Used by workflow worker when directly called child execution fails.
103    #[error("child finished with an execution error: {child_execution_id}")]
104    UnhandledChildExecutionError {
105        child_execution_id: ExecutionIdDerived,
106        root_cause_id: ExecutionIdDerived,
107    },
108    // Used by workflow worker
109    #[error("nondeterminism detected")]
110    NondeterminismDetected { detail: String },
111    // Used by activity worker, workflow worker
112    #[error(transparent)]
113    ParamsParsingError(ParamsParsingError),
114    // Used by activity worker, workflow worker
115    #[error("cannot instantiate: {reason}")]
116    CannotInstantiate { reason: String, detail: String },
117    // Used by activity worker, workflow worker
118    #[error(transparent)]
119    ResultParsingError(ResultParsingError),
120    /// Used when workflow cannot call an imported function, either a child execution or a function from workflow-support.
121    #[error("error calling imported function {ffqn} : {reason}")]
122    ImportedFunctionCallError {
123        ffqn: FunctionFqn,
124        reason: StrVariant,
125        detail: Option<String>,
126    },
127    /// Workflow trap if `retry_on_trap` is disabled.
128    #[error("workflow {trap_kind}: {reason}")]
129    WorkflowTrap {
130        reason: String,
131        trap_kind: TrapKind,
132        detail: Option<String>,
133    },
134    #[error("out of fuel: {reason}")]
135    OutOfFuel { reason: String },
136    /// Workflow attempted to create a join set with the same name twice, or with an invalid character.
137    #[error("{reason}")]
138    JoinSetNameError { reason: String },
139}
140
141impl From<FatalError> for FinishedExecutionError {
142    fn from(value: FatalError) -> Self {
143        let reason_full = value.to_string();
144        match value {
145            FatalError::UnhandledChildExecutionError {
146                child_execution_id,
147                root_cause_id,
148            } => FinishedExecutionError::UnhandledChildExecutionError {
149                child_execution_id,
150                root_cause_id,
151            },
152            FatalError::NondeterminismDetected { detail } => {
153                FinishedExecutionError::PermanentFailure {
154                    reason_inner: reason_full.clone(),
155                    reason_full,
156                    kind: PermanentFailureKind::NondeterminismDetected,
157                    detail: Some(detail),
158                }
159            }
160            FatalError::ParamsParsingError(params_parsing_error) => {
161                FinishedExecutionError::PermanentFailure {
162                    reason_inner: reason_full.to_string(),
163                    reason_full,
164                    kind: PermanentFailureKind::ParamsParsingError,
165                    detail: params_parsing_error.detail(),
166                }
167            }
168            FatalError::CannotInstantiate {
169                detail,
170                reason: reason_inner,
171                ..
172            } => FinishedExecutionError::PermanentFailure {
173                reason_inner,
174                reason_full,
175                kind: PermanentFailureKind::CannotInstantiate,
176                detail: Some(detail),
177            },
178            FatalError::ResultParsingError(_) => FinishedExecutionError::PermanentFailure {
179                reason_inner: reason_full.to_string(),
180                reason_full,
181                kind: PermanentFailureKind::ResultParsingError,
182                detail: None,
183            },
184            FatalError::ImportedFunctionCallError {
185                detail,
186                reason: reason_inner,
187                ..
188            } => FinishedExecutionError::PermanentFailure {
189                reason_inner: reason_inner.to_string(),
190                reason_full,
191                kind: PermanentFailureKind::ImportedFunctionCallError,
192                detail,
193            },
194            FatalError::WorkflowTrap {
195                detail,
196                reason: reason_inner,
197                ..
198            } => FinishedExecutionError::PermanentFailure {
199                reason_inner,
200                reason_full,
201                kind: PermanentFailureKind::WorkflowTrap,
202                detail,
203            },
204            FatalError::OutOfFuel {
205                reason: reason_inner,
206            } => FinishedExecutionError::PermanentFailure {
207                reason_inner,
208                reason_full,
209                kind: PermanentFailureKind::OutOfFuel,
210                detail: None,
211            },
212            FatalError::JoinSetNameError { reason } => FinishedExecutionError::PermanentFailure {
213                reason_inner: reason,
214                reason_full,
215                kind: PermanentFailureKind::JoinSetNameError,
216                detail: None,
217            },
218        }
219    }
220}