Skip to main content

dataflow_rs/engine/
task_executor.rs

1//! # Task Execution Module
2//!
3//! Dispatches a single `Task` to its function implementation. Built-in sync
4//! variants of `FunctionConfig` are dispatched in `workflow_executor`'s sync
5//! stretch via [`FunctionConfig::try_execute_in_arena`]; this module owns
6//! the async path — `HttpCall`, `Enrich`, `PublishKafka`, and `Custom` —
7//! routed to the matching registered handler.
8
9use crate::engine::error::{DataflowError, Result};
10use crate::engine::functions::config::can_dispatch_in;
11use crate::engine::functions::{BoxedFunctionHandler, FunctionConfig};
12use crate::engine::message::{Change, Message};
13use crate::engine::secrets::Secrets;
14use crate::engine::task::Task;
15use crate::engine::task_context::{TaskContext, TaskIdentity};
16use crate::engine::task_outcome::TaskOutcome;
17use datalogic_rs::Engine;
18use log::{debug, error};
19use std::any::Any;
20use std::collections::HashMap;
21use std::sync::Arc;
22
23/// Handles the execution of tasks with their associated functions.
24///
25/// The `TaskExecutor` is responsible for:
26/// - Routing async functions (http_call, enrich, publish_kafka, custom) to
27///   the matching registered handler via [`crate::engine::functions::DynAsyncFunctionHandler`]
28/// - Owning the function registry
29///
30/// Sync built-ins are *not* routed through `execute` — `workflow_executor`
31/// calls [`FunctionConfig::try_execute_in_arena`] inside its sync stretch
32/// for those, sharing one arena across consecutive sync tasks.
33pub struct TaskExecutor {
34    /// Registry of async function handlers
35    task_functions: Arc<HashMap<String, BoxedFunctionHandler>>,
36    /// Shared datalogic Engine (Send + Sync; Arc-shared across tasks)
37    engine: Arc<Engine>,
38    /// The engine's secret store, for [`TaskContext::secret`]. Empty for an
39    /// executor built directly through [`Self::new`].
40    secrets: Arc<Secrets>,
41}
42
43impl TaskExecutor {
44    /// Create a new TaskExecutor
45    pub fn new(
46        task_functions: Arc<HashMap<String, BoxedFunctionHandler>>,
47        engine: Arc<Engine>,
48    ) -> Self {
49        Self::with_secrets(task_functions, engine, Arc::new(Secrets::empty()))
50    }
51
52    /// As [`Self::new`], handing handlers `secrets` through
53    /// [`TaskContext::secret`]. A separate constructor rather than a `new`
54    /// parameter for the same reason `execute_in_workflow` is a separate
55    /// method: `new` is public.
56    pub(crate) fn with_secrets(
57        task_functions: Arc<HashMap<String, BoxedFunctionHandler>>,
58        engine: Arc<Engine>,
59        secrets: Arc<Secrets>,
60    ) -> Self {
61        Self {
62            task_functions,
63            engine,
64            secrets,
65        }
66    }
67
68    /// Execute a single task. Sync built-ins reach here only when called from
69    /// outside the workflow executor's sync-stretch path — they fall back to
70    /// their `execute()` methods (which open a fresh thread-local arena).
71    pub async fn execute(
72        &self,
73        task: &Task,
74        message: &mut Message,
75    ) -> Result<(TaskOutcome, Vec<Change>)> {
76        self.execute_in_workflow(task, message, None, None).await
77    }
78
79    /// As [`Self::execute`], carrying the identity the handler will see through
80    /// [`TaskContext::workflow_id`] / [`TaskContext::task_id`].
81    ///
82    /// Separate from `execute` rather than an added parameter because
83    /// `TaskExecutor` is publicly reachable (`engine::task_executor`), so
84    /// widening the existing signature would break a caller outside the crate
85    /// for a path only the workflow executor uses.
86    pub(crate) async fn execute_in_workflow(
87        &self,
88        task: &Task,
89        message: &mut Message,
90        identity: Option<TaskIdentity<'_>>,
91        loop_counter: Option<i64>,
92    ) -> Result<(TaskOutcome, Vec<Change>)> {
93        debug!(
94            "Executing task: {} with function: {:?}",
95            task.id,
96            task.function.function_name()
97        );
98
99        match &task.function {
100            // Sync built-ins — only hit here when called outside the workflow
101            // sync stretch (test harness, direct `TaskExecutor::execute`).
102            FunctionConfig::Map { input, .. } => input.execute(message, &self.engine),
103            FunctionConfig::Validation { input, .. } => input.execute(message, &self.engine),
104            FunctionConfig::ParseJson { input, .. } => {
105                crate::engine::functions::parse::execute_parse_json(message, input)
106            }
107            FunctionConfig::ParseXml { input, .. } => {
108                crate::engine::functions::parse::execute_parse_xml(message, input)
109            }
110            FunctionConfig::PublishJson { input, .. } => {
111                crate::engine::functions::publish::execute_publish_json(message, input)
112            }
113            FunctionConfig::PublishXml { input, .. } => {
114                crate::engine::functions::publish::execute_publish_xml(message, input)
115            }
116            FunctionConfig::Filter { input, .. } => input.execute(message, &self.engine),
117            FunctionConfig::Log { input, .. } => input.execute(message, &self.engine),
118            // Async / user-registered handlers. Named via `function_name()`
119            // rather than a repeated string literal, so the registry lookup
120            // can never drift from the canonical name `FunctionConfig` itself
121            // reports for the variant.
122            FunctionConfig::HttpCall { input, .. } => {
123                self.dispatch_handler(
124                    task.function.function_name(),
125                    message,
126                    input,
127                    identity,
128                    loop_counter,
129                )
130                .await
131            }
132            FunctionConfig::Enrich { input, .. } => {
133                self.dispatch_handler(
134                    task.function.function_name(),
135                    message,
136                    input,
137                    identity,
138                    loop_counter,
139                )
140                .await
141            }
142            FunctionConfig::PublishKafka { input, .. } => {
143                self.dispatch_handler(
144                    task.function.function_name(),
145                    message,
146                    input,
147                    identity,
148                    loop_counter,
149                )
150                .await
151            }
152            FunctionConfig::Custom {
153                name,
154                compiled_input,
155                ..
156            } => {
157                let any_input = compiled_input.as_ref().ok_or_else(|| {
158                    DataflowError::Validation(format!(
159                        "Custom function '{}' has no precompiled input — \
160                         was the workflow built outside Engine::new?",
161                        name
162                    ))
163                })?;
164                self.dispatch_handler_any(name, message, any_input.as_any(), identity, loop_counter)
165                    .await
166            }
167        }
168    }
169
170    /// Generic-Input flavour: takes any `T: Any + Send + Sync`, hands it to
171    /// the registered handler as `&dyn Any`. Used by the built-in async
172    /// dispatch (`HttpCallConfig`, `EnrichConfig`, `PublishKafkaConfig`)
173    /// where the typed config is already on the `FunctionConfig` enum.
174    async fn dispatch_handler<T>(
175        &self,
176        name: &str,
177        message: &mut Message,
178        input: &T,
179        identity: Option<TaskIdentity<'_>>,
180        loop_counter: Option<i64>,
181    ) -> Result<(TaskOutcome, Vec<Change>)>
182    where
183        T: Any + Send + Sync,
184    {
185        let any_input: &(dyn Any + Send + Sync) = input;
186        self.dispatch_handler_any(name, message, any_input, identity, loop_counter)
187            .await
188    }
189
190    /// Inner dispatch: build a `TaskContext`, invoke the handler, drain the
191    /// accumulated `Change` buffer.
192    async fn dispatch_handler_any(
193        &self,
194        name: &str,
195        message: &mut Message,
196        any_input: &(dyn Any + Send + Sync),
197        identity: Option<TaskIdentity<'_>>,
198        loop_counter: Option<i64>,
199    ) -> Result<(TaskOutcome, Vec<Change>)> {
200        let handler = self.task_functions.get(name).ok_or_else(|| {
201            error!("Function handler not found: {}", name);
202            DataflowError::FunctionNotFound(name.to_string())
203        })?;
204        let mut ctx = TaskContext::with_identity(
205            message,
206            &self.engine,
207            identity,
208            loop_counter,
209            &self.secrets,
210        );
211        let outcome = handler.dyn_execute(&mut ctx, any_input).await?;
212        let changes = ctx.into_changes();
213        Ok((outcome, changes))
214    }
215
216    /// Whether this executor can actually run a task named `name`.
217    ///
218    /// `true` for a [`BuiltinKind::SelfContained`] built-in, which this crate
219    /// executes itself, and for any name with a registered handler.
220    ///
221    /// `false` for `http_call` / `enrich` / `publish_kafka` with no handler
222    /// registered — those deserialize into a typed built-in variant and so pass
223    /// `Engine::new`, but fail at dispatch with
224    /// [`DataflowError::FunctionNotFound`] on the first message. This is
225    /// deliberately narrower than "is this a known name"; use
226    /// [`crate::is_builtin_function`] for that.
227    pub fn has_function(&self, name: &str) -> bool {
228        can_dispatch_in(&self.task_functions, name)
229    }
230
231    /// Borrow the handler registry.
232    ///
233    /// [`Self::task_functions`] hands back an owned `Arc` clone for rebuilding
234    /// an executor; this borrows in place, so callers can yield `&str` keyed to
235    /// the executor's own lifetime — which
236    /// [`crate::Engine::dispatchable_functions`] needs and an `Arc` temporary
237    /// cannot provide.
238    pub fn registry(&self) -> &HashMap<String, BoxedFunctionHandler> {
239        &self.task_functions
240    }
241
242    /// Get a clone of the task_functions Arc for reuse in new engines
243    pub fn task_functions(&self) -> Arc<HashMap<String, BoxedFunctionHandler>> {
244        Arc::clone(&self.task_functions)
245    }
246
247    /// Get the count of registered custom functions
248    pub fn custom_function_count(&self) -> usize {
249        self.task_functions.len()
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::engine::AsyncFunctionHandler;
257    use crate::engine::compiler::LogicCompiler;
258    use crate::engine::functions::config::is_builtin_function;
259
260    /// A `TaskExecutor` with an empty handler registry.
261    fn executor_with_no_handlers() -> TaskExecutor {
262        TaskExecutor::new(Arc::new(HashMap::new()), LogicCompiler::new().into_engine())
263    }
264
265    /// A `TaskExecutor` with `MockAsyncFunction` registered under `name`.
266    fn executor_with_handler(name: &str) -> TaskExecutor {
267        let mut handlers: HashMap<String, BoxedFunctionHandler> = HashMap::new();
268        handlers.insert(name.to_string(), Box::new(MockAsyncFunction));
269        TaskExecutor::new(Arc::new(handlers), LogicCompiler::new().into_engine())
270    }
271
272    #[test]
273    fn test_has_function() {
274        let task_executor = executor_with_no_handlers();
275
276        // Built-in functions
277        assert!(task_executor.has_function("map"));
278        assert!(task_executor.has_function("validation"));
279        assert!(task_executor.has_function("validate"));
280
281        // Non-existent function
282        assert!(!task_executor.has_function("nonexistent"));
283        assert!(!task_executor.has_function(""));
284    }
285
286    #[test]
287    fn has_function_is_false_for_config_only_integrations_without_a_handler() {
288        // These three deserialize into typed built-in variants, so `Engine::new`
289        // accepts them — but they dispatch to a registered handler and fail with
290        // FunctionNotFound on the first message. `has_function` answers "can this
291        // executor run it", so it must say no.
292        let task_executor = executor_with_no_handlers();
293
294        for name in ["http_call", "enrich", "publish_kafka"] {
295            assert!(
296                !task_executor.has_function(name),
297                "'{name}' has no registered handler, so it cannot be run"
298            );
299            // It is still a known built-in name — the two questions differ.
300            assert!(is_builtin_function(name));
301        }
302    }
303
304    #[test]
305    fn has_function_is_true_for_config_only_integrations_once_registered() {
306        for name in ["http_call", "enrich", "publish_kafka"] {
307            assert!(
308                executor_with_handler(name).has_function(name),
309                "'{name}' has a registered handler, so it can be run"
310            );
311        }
312    }
313
314    #[test]
315    fn has_function_is_true_for_every_self_contained_builtin_with_an_empty_registry() {
316        let task_executor = executor_with_no_handlers();
317
318        // Both accepted spellings of validation are covered: the deserializer
319        // takes either, while `function_name()` only ever returns "validate".
320        for name in [
321            "map",
322            "validation",
323            "validate",
324            "parse_json",
325            "parse_xml",
326            "publish_json",
327            "publish_xml",
328            "filter",
329            "log",
330        ] {
331            assert!(
332                task_executor.has_function(name),
333                "'{name}' is executed by the crate and needs no registration"
334            );
335        }
336    }
337
338    #[test]
339    fn registering_a_handler_under_a_self_contained_name_does_not_change_the_answer() {
340        // `TaskExecutor::execute` dispatches sync built-ins by variant and never
341        // consults the registry, so a handler registered under "map" is dead
342        // code. `has_function` answers `true` either way; pinning it here stops a
343        // later change from making the two disagree silently.
344        assert!(executor_with_handler("map").has_function("map"));
345        assert!(executor_with_no_handlers().has_function("map"));
346    }
347
348    #[test]
349    fn has_function_is_unchanged_for_custom_names() {
350        assert!(executor_with_handler("custom_test").has_function("custom_test"));
351        assert!(!executor_with_handler("custom_test").has_function("other_custom"));
352    }
353
354    #[test]
355    fn test_custom_function_count() {
356        let mut custom_functions: HashMap<String, BoxedFunctionHandler> = HashMap::new();
357        custom_functions.insert("custom_test".to_string(), Box::new(MockAsyncFunction));
358
359        let engine = LogicCompiler::new().into_engine();
360        let task_executor = TaskExecutor::new(Arc::new(custom_functions), engine);
361
362        assert_eq!(task_executor.custom_function_count(), 1);
363    }
364
365    // Mock async function for testing
366    struct MockAsyncFunction;
367
368    #[async_trait::async_trait]
369    impl AsyncFunctionHandler for MockAsyncFunction {
370        type Input = serde_json::Value;
371
372        async fn execute(
373            &self,
374            _ctx: &mut TaskContext<'_>,
375            _input: &serde_json::Value,
376        ) -> Result<TaskOutcome> {
377            Ok(TaskOutcome::Success)
378        }
379    }
380}