1use 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
23pub struct TaskExecutor {
34 task_functions: Arc<HashMap<String, BoxedFunctionHandler>>,
36 engine: Arc<Engine>,
38 secrets: Arc<Secrets>,
41}
42
43impl TaskExecutor {
44 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 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 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 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 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 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 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 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 pub fn has_function(&self, name: &str) -> bool {
228 can_dispatch_in(&self.task_functions, name)
229 }
230
231 pub fn registry(&self) -> &HashMap<String, BoxedFunctionHandler> {
239 &self.task_functions
240 }
241
242 pub fn task_functions(&self) -> Arc<HashMap<String, BoxedFunctionHandler>> {
244 Arc::clone(&self.task_functions)
245 }
246
247 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 fn executor_with_no_handlers() -> TaskExecutor {
262 TaskExecutor::new(Arc::new(HashMap::new()), LogicCompiler::new().into_engine())
263 }
264
265 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 assert!(task_executor.has_function("map"));
278 assert!(task_executor.has_function("validation"));
279 assert!(task_executor.has_function("validate"));
280
281 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 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 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 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 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 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}