Skip to main content

dataflow_rs/engine/
mod.rs

1/*!
2# Engine Module
3
4This module implements the core async workflow engine for dataflow-rs. The engine provides
5high-performance, asynchronous message processing through workflows composed of tasks.
6
7## Architecture
8
9The engine features a clean async-first architecture built on datalogic v5:
10- **Compiler**: Pre-compiles JSONLogic expressions into `Arc<Logic>` via `Engine::compile_arc`
11- **Executor**: Handles internal function execution (map, validation) with async support
12- **Engine**: Orchestrates workflow processing with shared compiled logic
13- **Thread-Safe**: Single `datalogic_rs::Engine` shared via `Arc`, with `Arc<Logic>` entries for zero-copy sharing
14
15## Key Components
16
17- **Engine**: Async engine optimized for Tokio runtime with mixed I/O and CPU workloads
18- **LogicCompiler**: Compiles and caches JSONLogic expressions during initialization
19- **InternalExecutor**: Executes built-in map and validation functions with compiled logic
20- **Workflow**: Collection of tasks with JSONLogic conditions (can access data, metadata, temp_data)
21- **Task**: Individual processing unit that performs a specific function on a message
22- **AsyncFunctionHandler**: Trait for custom async processing logic
23- **Message**: Data structure flowing through the engine with audit trail
24
25## Performance Optimizations
26
27- **Pre-compilation**: All JSONLogic expressions compiled at startup
28- **Arc-wrapped Logic**: Zero-copy sharing of compiled logic across async tasks
29- **Bump-arena evaluation**: Per-worker thread-local `Bump` is rewound (not freed) between evals
30- **True Async**: I/O operations remain fully async
31
32## Usage
33
34```rust,no_run
35use dataflow_rs::{Engine, Workflow, engine::message::Message};
36use serde_json::json;
37
38#[tokio::main]
39async fn main() -> Result<(), Box<dyn std::error::Error>> {
40    // Define workflows
41    let workflows = vec![
42        Workflow::from_json(r#"{"id": "example", "name": "Example", "tasks": [{"id": "task1", "name": "Task 1", "function": {"name": "map", "input": {"mappings": []}}}]}"#)?
43    ];
44
45    // Create engine with defaults
46    let engine = Engine::builder().with_workflows(workflows).build()?;
47
48    // Process messages asynchronously
49    let mut message = Message::from_value(&json!({}));
50    engine.process_message(&mut message).await?;
51
52    Ok(())
53}
54```
55*/
56
57pub mod authoring;
58pub mod compiler;
59pub mod error;
60pub mod executor;
61pub mod functions;
62pub mod message;
63pub mod observer;
64/// Retrying a failed operation. Not available on `wasm32` — tokio's time
65/// driver, which the backoff needs, does not run there.
66#[cfg(not(target_arch = "wasm32"))]
67pub mod retry;
68pub mod rollout;
69pub mod secrets;
70pub mod steps;
71pub mod task;
72pub mod task_context;
73pub mod task_executor;
74pub mod task_outcome;
75pub mod trace;
76pub mod utils;
77pub mod workflow;
78pub mod workflow_executor;
79
80// Re-export key types for easier access
81pub use authoring::{IssueCode, Severity, WorkflowIssue};
82use error::{DEFAULT_ERROR_CONTEXT_LIMIT, ErrorContextConfig};
83pub use error::{DataflowError, ErrorInfo, Result, ServiceErrorBuilder};
84pub use functions::{
85    AsyncFunctionHandler, BoxedFunctionHandler, CompiledCustomInput, DynAsyncFunctionHandler,
86    FunctionConfig, Template, TemplateCompiler,
87};
88pub use message::Message;
89pub use observer::{
90    ExecutionObserver, MessageFinished, MessageStarted, TaskEvent, WorkflowFinished,
91    WorkflowStarted,
92};
93#[cfg(not(target_arch = "wasm32"))]
94pub use retry::{RetryPolicy, retry_with_attempts, retry_with_policy};
95pub use rollout::{Rollout, RolloutError};
96pub use secrets::Secrets;
97pub use steps::{
98    AuthoredStep, AuthoredSteps, MAX_GROUP_DEPTH, StepKind, is_group, walk_authored_steps,
99};
100pub use task::{HaltOn, Task, TaskGroup};
101pub use task_context::TaskContext;
102pub use task_outcome::{HALT_STATUS_CODE, TaskOutcome};
103pub use trace::{AuditTrailScope, ExecutionStep, ExecutionTrace, StepResult, TraceOptions};
104pub use workflow::{ConnectorRef, Workflow, WorkflowStatus};
105
106// `EngineBuilder` is defined further down in this file but exposed here so
107// downstream paths can import it via `dataflow_rs::engine::EngineBuilder`.
108
109use chrono::Utc;
110use datalogic_rs::Engine as DatalogicEngine;
111use datavalue::OwnedDataValue;
112use std::collections::HashMap;
113use std::sync::Arc;
114
115use crate::engine::functions::config::{
116    DispatchableFunction, can_dispatch_in, dispatchable_functions_in,
117};
118
119use compiler::LogicCompiler;
120use task_executor::TaskExecutor;
121use workflow_executor::WorkflowExecutor;
122
123/// High-performance async workflow engine for message processing.
124///
125/// ## Architecture
126///
127/// The engine is designed for async-first operation with Tokio:
128/// - **Separation of Concerns**: Distinct executors for workflows and tasks
129/// - **Shared datalogic engine**: Single `datalogic_rs::Engine` wrapped in `Arc` for thread-safe sharing
130/// - **`Arc<Logic>`**: Pre-compiled logic shared across all async tasks
131/// - **Async Functions**: Native async support for I/O-bound operations
132///
133/// ## Performance Characteristics
134///
135/// - **Zero Runtime Compilation**: All logic compiled during initialization
136/// - **Zero-Copy Sharing**: Arc-wrapped compiled logic shared without cloning
137/// - **Optimal for Mixed Workloads**: Async I/O with blocking CPU evaluation
138/// - **Thread-Safe by Design**: All components safe to share across Tokio tasks
139pub struct Engine {
140    /// Registry of available workflows, pre-sorted by priority (immutable after initialization).
141    /// Each workflow / task / function-config holds its own `Arc<Logic>` slots
142    /// — there is no central logic cache anymore.
143    workflows: Arc<Vec<Workflow>>,
144    /// Channel index: maps channel name -> indices into workflows vec (only Active workflows)
145    channel_index: Arc<HashMap<String, Vec<usize>>>,
146    /// Workflow executor for orchestrating workflow execution
147    workflow_executor: Arc<WorkflowExecutor>,
148    /// Shared datalogic v5 engine for JSONLogic evaluation (Send + Sync)
149    datalogic: Arc<DatalogicEngine>,
150    /// Custom JSONLogic operators registered via
151    /// [`EngineBuilder::with_datalogic_operator`]. Retained here — not just
152    /// applied once — because [`Engine::with_new_workflows`] builds a fresh
153    /// datalogic engine and must re-register them; holding only the built
154    /// engine would silently drop every custom operator at the first hot
155    /// reload.
156    datalogic_operators: DatalogicOperators,
157    /// Pre-built `Arc<OwnedDataValue::String>` of the engine version.
158    /// Built once at construction. Note the per-message stamp still clones
159    /// the inner `String` — the context owns its values, so the cached
160    /// form only saves re-formatting, not the (small) allocation.
161    engine_version: Arc<OwnedDataValue>,
162    /// The secret store behind the `secret` operator. Never part of a
163    /// `Message`; carried across [`Engine::with_new_workflows`] like the
164    /// custom operators, and for the same reason.
165    secrets: Arc<Secrets>,
166    /// Per-evaluation operation ceiling, or `None` for unbounded. Retained for
167    /// the same reason as `secrets` and the operators: a hot reload builds a
168    /// fresh datalogic engine, and a budget that silently lifted itself on
169    /// reload would be worse than no budget at all. Always `None` without the
170    /// `budget` feature.
171    ops_budget: Option<u64>,
172}
173
174/// The custom-operator registrations an engine carries across rebuilds.
175pub type DatalogicOperators = Arc<HashMap<String, Arc<dyn datalogic_rs::CustomOperator>>>;
176
177/// Build a channel index from pre-sorted workflows.
178/// Maps channel name -> indices into workflows vec, only for Active workflows.
179fn build_channel_index(workflows: &[Workflow]) -> HashMap<String, Vec<usize>> {
180    let mut index: HashMap<String, Vec<usize>> = HashMap::new();
181    for (i, workflow) in workflows.iter().enumerate() {
182        if workflow.status == WorkflowStatus::Active {
183            index.entry(workflow.channel.clone()).or_default().push(i);
184        }
185    }
186    index
187}
188
189impl Engine {
190    /// Creates a new Engine instance.
191    ///
192    /// Compiles every workflow / task / function-config JSONLogic expression
193    /// up-front. Returns `Err(DataflowError)` if any required expression
194    /// fails to compile — fail-loud at construction time instead of silently
195    /// dropping broken workflows at runtime.
196    ///
197    /// # Arguments
198    /// * `workflows` - The workflows to use for processing messages
199    /// * `task_functions` - Custom async function handlers (use
200    ///   `HashMap::new()` for none, or prefer [`Engine::builder`])
201    ///
202    /// # Example
203    ///
204    /// ```
205    /// use dataflow_rs::{Engine, Workflow};
206    ///
207    /// let workflows = vec![Workflow::from_json(r#"{"id": "test", "name": "Test", "priority": 0, "tasks": [{"id": "task1", "name": "Task 1", "function": {"name": "map", "input": {"mappings": []}}}]}"#).unwrap()];
208    ///
209    /// let engine = Engine::builder().with_workflows(workflows).build().unwrap();
210    /// ```
211    /// The recommended construction path is [`Engine::builder`]. `Engine::new`
212    /// is the lower-level escape hatch — accepts handlers as a plain
213    /// `HashMap` (use `HashMap::new()` for the no-handler case).
214    pub fn new(
215        workflows: Vec<Workflow>,
216        task_functions: HashMap<String, BoxedFunctionHandler>,
217    ) -> Result<Self> {
218        Self::new_with_operators(workflows, task_functions, Arc::new(HashMap::new()))
219    }
220
221    /// As [`Engine::new`], with custom JSONLogic operators registered on the
222    /// datalogic engine (and retained across [`Engine::with_new_workflows`]).
223    /// The builder path is [`EngineBuilder::with_datalogic_operator`]; this is
224    /// its escape-hatch twin, matching `new`.
225    pub fn new_with_operators(
226        workflows: Vec<Workflow>,
227        task_functions: HashMap<String, BoxedFunctionHandler>,
228        datalogic_operators: DatalogicOperators,
229    ) -> Result<Self> {
230        Self::new_inner(
231            workflows,
232            task_functions,
233            datalogic_operators,
234            Arc::new(Secrets::empty()),
235            None,
236        )
237    }
238
239    /// The one constructor every public entry point funnels into. `secrets`
240    /// and `ops_budget` are builder-only — `Engine::new*` are escape hatches
241    /// whose signatures stay put.
242    fn new_inner(
243        workflows: Vec<Workflow>,
244        task_functions: HashMap<String, BoxedFunctionHandler>,
245        datalogic_operators: DatalogicOperators,
246        secrets: Arc<Secrets>,
247        ops_budget: Option<u64>,
248    ) -> Result<Self> {
249        // Checked here rather than in the builder so the `Engine::new*` escape
250        // hatches refuse too: a host operator under this name would be
251        // shadowed by the engine's own, silently, on every engine.
252        if datalogic_operators.contains_key(secrets::SECRET_OPERATOR) {
253            return Err(DataflowError::Validation(format!(
254                "'{}' is a reserved operator name — it reads the engine's secret store \
255                 (see EngineBuilder::with_secrets) and cannot be registered by a host",
256                secrets::SECRET_OPERATOR
257            )));
258        }
259        // Compile workflows (sorted by priority at compile time). Each
260        // workflow/task/config owns its own `Arc<Logic>` slots — no central
261        // cache to return. Any compile failure bubbles up immediately.
262        //
263        // The compiler is built first only to read the operator vocabulary —
264        // the key checks need it. Refusal still runs before compilation, so an
265        // authoring issue is reported ahead of any compile error.
266        let compiler =
267            LogicCompiler::with_operators_and_secrets(&datalogic_operators, &secrets, ops_budget);
268        refuse_authoring_issues(&workflows, &secrets)?;
269        let mut sorted_workflows = compiler.compile_workflows(workflows)?;
270        let datalogic = compiler.into_engine();
271
272        // Pre-parse `FunctionConfig::Custom { input }` JSON into the
273        // registered handler's typed `Self::Input`, caching the boxed value
274        // on the task. Misshapen Custom configs fail here, not on first
275        // message — matches the "fail loud at startup" stance for compiled
276        // logic. Built-in async configs (HttpCall/Enrich/PublishKafka) are
277        // already typed by serde and need no second pass.
278        precompile_custom_inputs(&mut sorted_workflows, &task_functions, &datalogic)?;
279
280        let task_executor = Arc::new(TaskExecutor::with_secrets(
281            Arc::new(task_functions),
282            Arc::clone(&datalogic),
283            Arc::clone(&secrets),
284        ));
285
286        let workflow_executor =
287            Arc::new(WorkflowExecutor::new(task_executor, Arc::clone(&datalogic)));
288
289        // Build channel index for O(1) channel-based routing
290        let channel_index = build_channel_index(&sorted_workflows);
291
292        Ok(Self {
293            workflows: Arc::new(sorted_workflows),
294            channel_index: Arc::new(channel_index),
295            workflow_executor,
296            datalogic,
297            datalogic_operators,
298            engine_version: Arc::new(OwnedDataValue::String(
299                env!("CARGO_PKG_VERSION").to_string(),
300            )),
301            secrets,
302            ops_budget,
303        })
304    }
305
306    /// Start building an engine. The recommended construction path —
307    /// chains `register("name", handler)` and `with_workflow(w)` calls,
308    /// then `build()` to produce a `Result<Engine>`.
309    ///
310    /// ```no_run
311    /// use dataflow_rs::{Engine, Workflow};
312    /// # let workflow: Workflow = unimplemented!();
313    /// let engine = Engine::builder()
314    ///     .with_workflow(workflow)
315    ///     // .register("my_handler", MyHandler)  // any AsyncFunctionHandler
316    ///     .build()
317    ///     .unwrap();
318    /// ```
319    pub fn builder() -> EngineBuilder {
320        EngineBuilder::new()
321    }
322
323    /// Cached `OwnedDataValue::String` of the engine version.
324    pub fn engine_version_value(&self) -> &OwnedDataValue {
325        &self.engine_version
326    }
327
328    /// The top-level names in the secret store — what `{"secret": "name"}` can
329    /// resolve. Names only, never values; for a host's admin surface or a
330    /// did-you-mean on [`IssueCode::UnknownSecret`].
331    ///
332    /// Empty when the host configured no secrets. **Ordering is not
333    /// meaningful**, matching [`Engine::operator_names`].
334    pub fn declared_secrets(&self) -> impl Iterator<Item = &str> {
335        self.secrets.names()
336    }
337
338    /// Creates a new Engine with different workflows but the same custom function handlers.
339    ///
340    /// This is the hot-reload path. The existing engine remains valid for any
341    /// in-flight `process_message` calls. The returned engine shares the same
342    /// function registry (zero-copy Arc bump) but has freshly compiled logic
343    /// for the new workflow set.
344    ///
345    /// # Arguments
346    /// * `workflows` - The new set of workflows to compile and use
347    pub fn with_new_workflows(&self, workflows: Vec<Workflow>) -> Result<Self> {
348        // Extract the shared function registry from the existing executor
349        let task_functions = self.workflow_executor.task_functions();
350
351        // Compile new workflows with a fresh datalogic engine instance —
352        // re-registering the retained custom operators, so a hot reload keeps
353        // the same operator vocabulary as the engine it replaces.
354        let compiler = LogicCompiler::with_operators_and_secrets(
355            &self.datalogic_operators,
356            &self.secrets,
357            self.ops_budget,
358        );
359        refuse_authoring_issues(&workflows, &self.secrets)?;
360        let mut sorted_workflows = compiler.compile_workflows(workflows)?;
361        let datalogic = compiler.into_engine();
362
363        // Pre-parse Custom inputs against the existing handler registry —
364        // hot-reload still validates the new workflow set against the
365        // already-registered handlers.
366        precompile_custom_inputs(&mut sorted_workflows, &task_functions, &datalogic)?;
367
368        // Rebuild the executor stack, reusing the existing function registry
369        let task_executor = Arc::new(TaskExecutor::with_secrets(
370            task_functions,
371            Arc::clone(&datalogic),
372            Arc::clone(&self.secrets),
373        ));
374
375        // Carry the observer across the reload. Dropping it here would stop
376        // metrics silently at the first hot reload.
377        let mut executor = WorkflowExecutor::new(task_executor, Arc::clone(&datalogic));
378        if let Some(observer) = self.workflow_executor.observer() {
379            executor = executor.with_observer(Arc::clone(observer));
380        }
381        // Same reasoning as the observer: dropping this would silently stop
382        // recording failure codes at the first hot reload.
383        if let Some(cfg) = self.workflow_executor.error_context() {
384            executor = executor.with_error_context(Arc::clone(cfg));
385        }
386        let workflow_executor = Arc::new(executor);
387
388        // Build channel index for O(1) channel-based routing
389        let channel_index = build_channel_index(&sorted_workflows);
390
391        Ok(Self {
392            workflows: Arc::new(sorted_workflows),
393            channel_index: Arc::new(channel_index),
394            workflow_executor,
395            datalogic,
396            datalogic_operators: Arc::clone(&self.datalogic_operators),
397            engine_version: Arc::clone(&self.engine_version),
398            secrets: Arc::clone(&self.secrets),
399            ops_budget: self.ops_budget,
400        })
401    }
402
403    /// Attach a per-task [`ExecutionObserver`], returning the updated engine.
404    ///
405    /// The escape hatch matching [`Engine::new`] — [`EngineBuilder::with_observer`]
406    /// is the recommended path. Rebuilds the executor stack around the existing
407    /// handler registry and datalogic engine, so nothing is recompiled; the cost
408    /// is a few `Arc` bumps.
409    ///
410    /// Carried across [`Engine::with_new_workflows`], so a hot reload does not
411    /// silently stop reporting.
412    pub fn with_observer(self, observer: Arc<dyn ExecutionObserver>) -> Self {
413        self.rebuild_executor(|executor| executor.with_observer(observer))
414    }
415
416    /// Mirror per-task failure codes into the message context, returning the
417    /// updated engine.
418    ///
419    /// The escape hatch matching [`Engine::new`];
420    /// [`EngineBuilder::with_error_context_path`] is the recommended path and the
421    /// only one that validates the path. Carried across
422    /// [`Engine::with_new_workflows`] and [`Engine::with_observer`].
423    pub(crate) fn with_error_context(self, cfg: Arc<ErrorContextConfig>) -> Self {
424        self.rebuild_executor(|executor| executor.with_error_context(cfg))
425    }
426
427    /// Rebuild the executor stack around the existing handler registry and
428    /// datalogic engine, applying `configure` to the fresh executor.
429    ///
430    /// Nothing is recompiled; the cost is a few `Arc` bumps. Every knob the old
431    /// executor held is re-applied first, because the rebuild otherwise drops
432    /// them — that is what would make `.with_error_context(..)` followed by
433    /// `.with_observer(..)` silently lose the former.
434    fn rebuild_executor(
435        self,
436        configure: impl FnOnce(WorkflowExecutor) -> WorkflowExecutor,
437    ) -> Self {
438        let task_executor = Arc::new(TaskExecutor::with_secrets(
439            self.workflow_executor.task_functions(),
440            Arc::clone(&self.datalogic),
441            Arc::clone(&self.secrets),
442        ));
443        let mut executor = WorkflowExecutor::new(task_executor, Arc::clone(&self.datalogic));
444        if let Some(observer) = self.workflow_executor.observer() {
445            executor = executor.with_observer(Arc::clone(observer));
446        }
447        if let Some(cfg) = self.workflow_executor.error_context() {
448            executor = executor.with_error_context(Arc::clone(cfg));
449        }
450        Self {
451            workflows: self.workflows,
452            channel_index: self.channel_index,
453            workflow_executor: Arc::new(configure(executor)),
454            datalogic: self.datalogic,
455            datalogic_operators: self.datalogic_operators,
456            engine_version: self.engine_version,
457            secrets: self.secrets,
458            ops_budget: self.ops_budget,
459        }
460    }
461
462    /// Processes a message through workflows that match their conditions.
463    ///
464    /// This async method:
465    /// 1. Iterates through workflows sequentially in priority order (pre-sorted at construction)
466    /// 2. Delegates workflow execution to the WorkflowExecutor
467    /// 3. Updates message metadata
468    ///
469    /// # Error contract
470    ///
471    /// Errors flow through two complementary channels:
472    /// - `message.errors()` — **always** contains every error encountered
473    ///   (validation failures, task panics, 5xx-status outcomes, workflow
474    ///   wrappers). Callers that want a uniform view inspect this list.
475    /// - `Result::Err` — signals **only** that the engine stopped before
476    ///   processing every workflow. Callers that want fail-fast match on
477    ///   this. The error pushed to `message.errors` for the same failure
478    ///   carries the workflow context (id) that the bare `Err` doesn't.
479    ///
480    /// In particular: a workflow with `continue_on_error: true` records its
481    /// errors to `message.errors` and returns `Ok(())` here. A workflow
482    /// with `continue_on_error: false` records to `message.errors` *and*
483    /// returns `Result::Err` (which short-circuits the rest of this call).
484    ///
485    /// # Arguments
486    /// * `message` - The message to process through workflows
487    ///
488    /// # Returns
489    /// * `Result<()>` — `Ok(())` if every workflow completed (each may have
490    ///   pushed errors to `message.errors`); `Err(e)` if the engine
491    ///   stopped early on a hard failure.
492    pub async fn process_message(&self, message: &mut Message) -> Result<()> {
493        // Capture a single timestamp for the entire process_message call. The
494        // workflow executor reads it back via Message metadata if it needs to
495        // emit AuditTrail entries; this caps the number of `Utc::now()` syscalls
496        // at 1 per message (down from 3+ — one stamp here, one per AuditTrail).
497        self.process_all(message, None, Utc::now()).await
498    }
499
500    /// Processes a message through workflows with step-by-step tracing,
501    /// recording into a caller-owned trace.
502    ///
503    /// Identical to [`Engine::process_message_with_trace`] except that the
504    /// trace is borrowed rather than returned, so the steps completed before a
505    /// hard failure survive the `Err`. That makes this the method to reach for
506    /// when the run you want to inspect is the run that failed — a returned
507    /// trace is dropped by the `?` at the call site, a borrowed one is not.
508    ///
509    /// Steps are **appended** to `trace`; any steps already present are
510    /// preserved, so a caller can accumulate across a chain of calls.
511    ///
512    /// The error contract is unchanged: `Ok(())` means every workflow was
513    /// processed (each may still have pushed to `message.errors`), and `Err(e)`
514    /// means the engine stopped early. See [`Engine::process_message`] for the
515    /// full contract.
516    ///
517    /// Note that the failing task's *own* step is not recorded — the engine
518    /// propagates the failure before appending it — so the retained trace ends
519    /// at the last known-good step rather than at the error. The error itself
520    /// is available from the returned `Err` and from `message.errors()`.
521    ///
522    /// # Arguments
523    /// * `message` - The message to process through workflows
524    /// * `trace` - Caller-owned trace to append steps to
525    ///
526    /// # Returns
527    /// * `Result<()>` — `Ok(())` if every workflow completed; `Err(e)` if the
528    ///   engine stopped early. In both cases `trace` holds the steps that ran.
529    pub async fn process_message_tracing(
530        &self,
531        message: &mut Message,
532        trace: &mut ExecutionTrace,
533    ) -> Result<()> {
534        // The trace carries its own capture policy, so nothing to pass here.
535        self.process_all(message, Some(trace), Utc::now()).await
536    }
537
538    /// Shared driver behind [`Self::process_message`] and
539    /// [`Self::process_message_tracing`] — stamps processing metadata and runs
540    /// every registered workflow in priority order. Mirrors [`Self::process_channel`]
541    /// for the whole-registry case.
542    ///
543    /// `run_all_borrowed` groups consecutive fully-sync workflows into a
544    /// single shared-arena scope so the context is deep-walked once per run
545    /// rather than once per workflow. Passing the registry slice directly
546    /// avoids a per-message `Vec<&Workflow>` collect.
547    async fn process_all(
548        &self,
549        message: &mut Message,
550        trace: Option<&mut ExecutionTrace>,
551        now: chrono::DateTime<Utc>,
552    ) -> Result<()> {
553        set_processing_metadata(&mut message.context, &self.engine_version, now, None);
554        self.workflow_executor
555            .run_all_borrowed(&self.workflows[..], message, trace, now)
556            .await
557    }
558
559    /// Processes a message through workflows with step-by-step tracing.
560    ///
561    /// This method is similar to `process_message` but captures an execution trace
562    /// that can be used for debugging and step-by-step visualization.
563    ///
564    /// Because the trace is returned by value, a `?` at the call site discards
565    /// it — on a hard failure this yields `Err` and no steps at all. Use
566    /// [`Engine::process_message_tracing`] to keep the steps that ran.
567    ///
568    /// # Arguments
569    /// * `message` - The message to process through workflows
570    ///
571    /// # Returns
572    /// * `Result<ExecutionTrace>` - The execution trace with message snapshots
573    pub async fn process_message_with_trace(
574        &self,
575        message: &mut Message,
576    ) -> Result<ExecutionTrace> {
577        self.process_message_with_trace_options(message, TraceOptions::default())
578            .await
579    }
580
581    /// Processes a message with tracing under an explicit capture policy.
582    ///
583    /// The default policy — what [`Engine::process_message_with_trace`] uses —
584    /// takes a full [`Message`] snapshot per executed step, which is unbounded
585    /// in message size and quadratic in task count. A host that *persists*
586    /// traces should bound them here rather than trimming the result
587    /// afterwards; by then the peak memory has already been paid.
588    ///
589    /// See [`TraceOptions`] for the knobs, and
590    /// [`Engine::process_message_tracing`] if you also need the steps to survive
591    /// a hard failure.
592    ///
593    /// # Arguments
594    /// * `message` - The message to process through workflows
595    /// * `options` - What to record for each step
596    pub async fn process_message_with_trace_options(
597        &self,
598        message: &mut Message,
599        options: TraceOptions,
600    ) -> Result<ExecutionTrace> {
601        let mut trace = ExecutionTrace::with_options(options);
602        self.process_message_tracing(message, &mut trace).await?;
603        Ok(trace)
604    }
605
606    /// Processes a message through only the Active workflows registered for a given channel.
607    ///
608    /// Workflows are processed in priority order (lowest first), same as process_message().
609    /// If the channel does not exist or has no Active workflows, this is a no-op.
610    ///
611    /// # Arguments
612    /// * `channel` - The channel name to route the message through
613    /// * `message` - The message to process
614    pub async fn process_message_for_channel(
615        &self,
616        channel: &str,
617        message: &mut Message,
618    ) -> Result<()> {
619        self.process_channel(channel, message, None, Utc::now())
620            .await
621    }
622
623    /// Channel-scoped variant of [`Engine::process_message_tracing`].
624    ///
625    /// As with [`Engine::process_message_for_channel`], an unknown channel — or
626    /// a channel with no Active workflows — is a no-op: this returns `Ok(())`
627    /// and leaves `trace` untouched. Steps are appended, matching
628    /// [`Engine::process_message_tracing`].
629    ///
630    /// # Arguments
631    /// * `channel` - The channel name to route the message through
632    /// * `message` - The message to process
633    /// * `trace` - Caller-owned trace to append steps to
634    pub async fn process_message_for_channel_tracing(
635        &self,
636        channel: &str,
637        message: &mut Message,
638        trace: &mut ExecutionTrace,
639    ) -> Result<()> {
640        self.process_channel(channel, message, Some(trace), Utc::now())
641            .await
642    }
643
644    /// Shared driver behind [`Self::process_message_for_channel`] and
645    /// [`Self::process_message_for_channel_tracing`] — stamps processing
646    /// metadata and runs only the channel's Active workflows. An unknown
647    /// channel, or one with no Active workflows, is a no-op.
648    async fn process_channel(
649        &self,
650        channel: &str,
651        message: &mut Message,
652        trace: Option<&mut ExecutionTrace>,
653        now: chrono::DateTime<Utc>,
654    ) -> Result<()> {
655        set_processing_metadata(
656            &mut message.context,
657            &self.engine_version,
658            now,
659            Some(channel),
660        );
661
662        if let Some(indices) = self.channel_index.get(channel) {
663            // Channel-selected workflows are non-contiguous in the registry,
664            // so the pointer collect stays on this path.
665            let workflows: Vec<&Workflow> =
666                indices.iter().map(|&idx| &self.workflows[idx]).collect();
667            self.workflow_executor
668                .run_all_borrowed(&workflows, message, trace, now)
669                .await?;
670        }
671
672        Ok(())
673    }
674
675    /// Processes a message through a channel with step-by-step tracing.
676    ///
677    /// Because the trace is returned by value, a `?` at the call site discards
678    /// it — on a hard failure this yields `Err` and no steps at all. Use
679    /// [`Engine::process_message_for_channel_tracing`] to keep the steps that
680    /// ran.
681    ///
682    /// # Arguments
683    /// * `channel` - The channel name to route the message through
684    /// * `message` - The message to process
685    pub async fn process_message_for_channel_with_trace(
686        &self,
687        channel: &str,
688        message: &mut Message,
689    ) -> Result<ExecutionTrace> {
690        self.process_message_for_channel_with_trace_options(
691            channel,
692            message,
693            TraceOptions::default(),
694        )
695        .await
696    }
697
698    /// Channel-scoped variant of
699    /// [`Engine::process_message_with_trace_options`].
700    ///
701    /// # Arguments
702    /// * `channel` - The channel name to route the message through
703    /// * `message` - The message to process
704    /// * `options` - What to record for each step
705    pub async fn process_message_for_channel_with_trace_options(
706        &self,
707        channel: &str,
708        message: &mut Message,
709        options: TraceOptions,
710    ) -> Result<ExecutionTrace> {
711        let mut trace = ExecutionTrace::with_options(options);
712        self.process_message_for_channel_tracing(channel, message, &mut trace)
713            .await?;
714        Ok(trace)
715    }
716
717    /// Get a reference to the workflows (pre-sorted by priority)
718    pub fn workflows(&self) -> &Arc<Vec<Workflow>> {
719        &self.workflows
720    }
721
722    /// Look up a workflow by its ID
723    pub fn workflow_by_id(&self, id: &str) -> Option<&Workflow> {
724        self.workflows.iter().find(|w| w.id == id)
725    }
726
727    /// Every function this engine will dispatch: self-contained built-ins,
728    /// plus [`crate::BuiltinKind::RequiresHandler`] built-ins and custom names with a
729    /// registered handler.
730    ///
731    /// This is the authoring-side vocabulary — what a host needs to screen a
732    /// workflow definition, build a completion catalogue, or offer a
733    /// did-you-mean on an unknown name, without keeping its own copy of the
734    /// list.
735    ///
736    /// Aliases are grouped: `validate` is yielded once carrying
737    /// `["validation"]`, not twice. [`Engine::can_dispatch`] does accept an
738    /// alias, so the two are deliberately different sets.
739    ///
740    /// **Ordering is not meaningful** and may change without notice; treat the
741    /// result as a set, and collect and sort if you need stable output.
742    ///
743    /// ```
744    /// use dataflow_rs::{BuiltinKind, Engine};
745    ///
746    /// let engine = Engine::builder().build().unwrap();
747    /// let mut names: Vec<&str> = engine.dispatchable_functions().map(|f| f.name).collect();
748    /// names.sort_unstable();
749    ///
750    /// // Self-contained built-ins need no registration…
751    /// assert!(names.contains(&"map"));
752    /// // …but `enrich` ships as a config schema only, so with no handler
753    /// // registered this engine cannot run it.
754    /// assert!(!names.contains(&"enrich"));
755    ///
756    /// let validate = engine
757    ///     .dispatchable_functions()
758    ///     .find(|f| f.name == "validate")
759    ///     .unwrap();
760    /// assert_eq!(validate.kind, Some(BuiltinKind::SelfContained));
761    /// assert_eq!(validate.aliases, &["validation"]);
762    /// ```
763    pub fn dispatchable_functions(&self) -> impl Iterator<Item = DispatchableFunction<'_>> {
764        dispatchable_functions_in(self.workflow_executor.registry())
765    }
766
767    /// Whether this engine can actually run a task named `name`.
768    ///
769    /// `true` for a [`crate::BuiltinKind::SelfContained`] built-in, which this crate
770    /// executes itself, and for any name with a registered handler — including
771    /// an alias such as `validation`.
772    ///
773    /// `false` means the opposite is guaranteed: a task naming it fails with
774    /// [`DataflowError::FunctionNotFound`] on the first message that reaches
775    /// it. That is the whole point of the method — `Engine::build` is
776    /// deliberately permissive about `http_call` / `enrich` / `publish_kafka`,
777    /// which deserialize into typed built-in variants and so pass construction
778    /// even with no handler behind them.
779    ///
780    /// ```
781    /// use dataflow_rs::Engine;
782    ///
783    /// let engine = Engine::builder().build().unwrap();
784    ///
785    /// assert!(engine.can_dispatch("map"));
786    /// assert!(engine.can_dispatch("validation")); // alias of `validate`
787    ///
788    /// // Builds fine, would fail every message — this is the check that catches it.
789    /// assert!(!engine.can_dispatch("enrich"));
790    /// assert!(!engine.can_dispatch("never_registered"));
791    /// ```
792    pub fn can_dispatch(&self, name: &str) -> bool {
793        can_dispatch_in(self.workflow_executor.registry(), name)
794    }
795
796    /// Check a workflow against this engine's registered handlers and secret
797    /// store, without building anything.
798    ///
799    /// Answers the half of the question [`Workflow::validate_authored`] cannot:
800    /// that method proves the definition *parses and validates*, but
801    /// [`EngineBuilder::build`] also resolves every task to a handler and parses
802    /// custom inputs. A definition can therefore be structurally perfect and
803    /// still abort a build — which, in a host that builds one engine over many
804    /// stored definitions, takes down every workflow in the process.
805    ///
806    /// Reports rather than aborts, so a host screens one definition at a time.
807    /// Issues are anchored on [`WorkflowIssue::task_id`] — step ids are unique
808    /// across tasks and groups — with a path relative to that task
809    /// (`function.input`). Join it with the coordinate
810    /// [`walk_authored_steps`] reports for that id
811    /// to point at the authored document.
812    ///
813    /// `Workflow::tasks` is already flattened, so tasks inside groups are
814    /// covered with no extra traversal.
815    ///
816    /// ```
817    /// use dataflow_rs::{Engine, IssueCode, Workflow};
818    ///
819    /// let workflow = Workflow::from_json(r#"{
820    ///     "id": "w", "name": "w", "priority": 0,
821    ///     "tasks": [{"id": "lookup", "name": "lookup",
822    ///                "function": {"name": "enrich",
823    ///                             "input": {"connector": "c", "merge_path": "data.out"}}}]
824    /// }"#).unwrap();
825    ///
826    /// // Builds cleanly — that permissiveness is deliberate.
827    /// let engine = Engine::builder().build().unwrap();
828    ///
829    /// let issues = engine.check_workflow(&workflow);
830    /// assert_eq!(issues[0].code, IssueCode::MissingHandler);
831    /// assert_eq!(issues[0].task_id.as_deref(), Some("lookup"));
832    /// ```
833    pub fn check_workflow(&self, workflow: &Workflow) -> Vec<WorkflowIssue> {
834        let compiler = TemplateCompiler::new(Arc::clone(&self.datalogic));
835        authoring::check_against_registry(
836            workflow,
837            self.workflow_executor.registry(),
838            &compiler,
839            &self.secrets,
840        )
841    }
842
843    /// Every operator name this build evaluates: datalogic's core vocabulary,
844    /// the extension families compiled in, and operators registered via
845    /// [`EngineBuilder::with_datalogic_operator`].
846    ///
847    /// Because the engine runs datalogic in templating mode, an unknown
848    /// operator is not an error — the object echoes back as literal data. That
849    /// makes this the only way to answer the authoring-side question a lint
850    /// needs: **is this single-key object a live operator call, or inert
851    /// data?**
852    ///
853    /// Turning a family on is therefore not a no-op. With `ext-string`
854    /// disabled, `{"length": …}` is a value; with it enabled, the same JSON is
855    /// a call. The enumeration moves with the feature.
856    ///
857    /// **Ordering is not meaningful** and may change without notice; treat the
858    /// result as a set, matching
859    /// [`BUILTIN_FUNCTION_NAMES`](crate::BUILTIN_FUNCTION_NAMES) and
860    /// [`Engine::dispatchable_functions`].
861    ///
862    /// ```
863    /// use dataflow_rs::Engine;
864    /// use std::collections::HashSet;
865    ///
866    /// let engine = Engine::builder().build().unwrap();
867    /// let vocabulary: HashSet<&str> = engine.operator_names().collect();
868    ///
869    /// // Core datalogic, always present.
870    /// assert!(vocabulary.contains("var"));
871    /// assert!(vocabulary.contains("if"));
872    ///
873    /// // A name outside the vocabulary is inert data, not a call — which is
874    /// // exactly what a lint wants to warn about.
875    /// assert!(!vocabulary.contains("lenght"));
876    /// ```
877    pub fn operator_names(&self) -> impl Iterator<Item = &str> + '_ {
878        // The built-in half comes from datalogic's own `OPCODE_NAMES` table
879        // (5.3.0's `builtin_operator_names`), the same table its compiler
880        // resolves keys against — so this cannot drift from dispatch the way a
881        // host-side copy of the list could. It moves with the compiled feature
882        // set on its side, including families this crate exposes no cargo
883        // feature for but that another crate in the graph turned on.
884        //
885        // The `map` is a lifetime coercion, not a transformation: datalogic
886        // yields `&'static str`, and `chain` needs both halves to agree on the
887        // item type with the `&'a str` borrowed from the custom registry.
888        let builtins = || {
889            self.datalogic
890                .builtin_operator_names()
891                .map(|name| -> &str { name })
892        };
893        // A custom registration under a built-in name is still that one name;
894        // filtering here is what dedups the two sources.
895        let customs = self
896            .datalogic_operators
897            .keys()
898            .map(String::as_str)
899            .filter(move |name| !builtins().any(|b| b == *name));
900        // The engine's own `secret` operator is live on every build; it cannot
901        // be in `datalogic_operators` (construction refuses the name).
902        builtins()
903            .chain(customs)
904            .chain(std::iter::once(secrets::SECRET_OPERATOR))
905    }
906
907    /// The prefix that escapes an object key in a JSONLogic template, so the
908    /// key is emitted as data instead of resolving as an operator.
909    ///
910    /// Exactly one leading prefix is stripped from every template key.
911    /// `{"$cat": …}` emits the key `cat`; `{"$$cat": …}` emits the literal
912    /// `$cat`; an unprefixed `{"cat": …}` is still the `cat` operator.
913    ///
914    /// Fixed for the life of the engine and identical on every build — this
915    /// accessor exists so an authoring tool can render or validate the spelling
916    /// without hardcoding it, not because it varies.
917    ///
918    /// This is the companion to [`Self::operator_names`]. That answers *which
919    /// names are live*; this answers *how to opt a key out of being one*.
920    ///
921    /// ```
922    /// use dataflow_rs::Engine;
923    ///
924    /// let engine = Engine::builder().build().unwrap();
925    /// assert_eq!(engine.template_key_escape(), '$');
926    /// ```
927    pub fn template_key_escape(&self) -> char {
928        compiler::TEMPLATE_KEY_ESCAPE
929    }
930
931    /// Get a reference to the underlying datalogic v5 engine.
932    ///
933    /// The same `Arc` every compiled [`Workflow`] in this engine evaluates
934    /// against, so a caller that wants to evaluate an expression under the
935    /// engine's exact operator vocabulary — the extension families compiled
936    /// in, the `secret` operator, and anything registered through
937    /// [`EngineBuilder::with_datalogic_operator`] — should use this rather
938    /// than building a second engine.
939    pub fn datalogic(&self) -> &Arc<DatalogicEngine> {
940        &self.datalogic
941    }
942}
943
944/// Builder for [`Engine`]. The recommended construction path — chain
945/// `register("name", handler)` and `with_workflow(workflow)` calls, then
946/// `build()` to produce a `Result<Engine>`. Empty registration is fine; an
947/// engine with no custom handlers still resolves the built-in functions.
948///
949/// `register` takes any [`AsyncFunctionHandler`] and boxes it internally; the
950/// `Box<dyn DynAsyncFunctionHandler + Send + Sync>` plumbing stays out of
951/// user code.
952///
953/// ```no_run
954/// use dataflow_rs::{Engine, Workflow};
955/// # let workflow: Workflow = unimplemented!();
956/// let engine = Engine::builder()
957///     .with_workflow(workflow)
958///     // .register("my_handler", MyHandler)
959///     .build()
960///     .unwrap();
961/// ```
962#[must_use = "EngineBuilder must be `.build()` to produce an Engine"]
963#[derive(Default)]
964pub struct EngineBuilder {
965    workflows: Vec<Workflow>,
966    handlers: HashMap<String, BoxedFunctionHandler>,
967    observer: Option<Arc<dyn ExecutionObserver>>,
968    datalogic_operators: HashMap<String, Arc<dyn datalogic_rs::CustomOperator>>,
969    error_context_path: Option<String>,
970    error_context_limit: Option<usize>,
971    /// Validated on the way in, so `build()` and `check_workflow` read one
972    /// store; the `Err` is what `build()` returns for a non-object value.
973    secrets: Option<Result<Secrets>>,
974    /// Per-evaluation operation ceiling. Only settable under the `budget`
975    /// feature; the field itself is unconditional so `build()` needs no `cfg`.
976    ops_budget: Option<u64>,
977}
978
979impl EngineBuilder {
980    /// Create an empty builder. Equivalent to [`EngineBuilder::default`].
981    pub fn new() -> Self {
982        Self::default()
983    }
984
985    /// Register a custom async handler under `name`. Accepts any
986    /// `AsyncFunctionHandler`; boxing happens internally via the engine's
987    /// blanket impl.
988    pub fn register<F>(mut self, name: impl Into<String>, handler: F) -> Self
989    where
990        F: AsyncFunctionHandler,
991    {
992        self.handlers.insert(name.into(), Box::new(handler));
993        self
994    }
995
996    /// Register a pre-boxed handler. Useful when handlers are constructed
997    /// dynamically (e.g. plugin registries) and the concrete type isn't
998    /// known at the call site.
999    pub fn register_boxed(
1000        mut self,
1001        name: impl Into<String>,
1002        handler: BoxedFunctionHandler,
1003    ) -> Self {
1004        self.handlers.insert(name.into(), handler);
1005        self
1006    }
1007
1008    /// Every function this builder will dispatch once built.
1009    ///
1010    /// The pre-build twin of [`Engine::dispatchable_functions`], with identical
1011    /// semantics — the two agree by construction, since `build()` moves this
1012    /// registry into the engine unchanged. Takes `&self`, so screening a batch
1013    /// of definitions does not consume the builder.
1014    ///
1015    /// ```
1016    /// use dataflow_rs::Engine;
1017    ///
1018    /// let builder = Engine::builder();
1019    /// let names: Vec<&str> = builder.dispatchable_functions().map(|f| f.name).collect();
1020    ///
1021    /// assert!(names.contains(&"parse_json"));
1022    /// assert!(!names.contains(&"publish_kafka")); // config schema, no handler
1023    /// ```
1024    pub fn dispatchable_functions(&self) -> impl Iterator<Item = DispatchableFunction<'_>> {
1025        dispatchable_functions_in(&self.handlers)
1026    }
1027
1028    /// Whether the engine this builder produces will run a task named `name`.
1029    ///
1030    /// The pre-build twin of [`Engine::can_dispatch`]. Screening a workflow is
1031    /// then a filter over its tasks — note that `Workflow::tasks` is already
1032    /// flattened, so this covers members of task groups too:
1033    ///
1034    /// ```
1035    /// use dataflow_rs::{Engine, Workflow};
1036    ///
1037    /// let workflow = Workflow::from_json(r#"{
1038    ///     "id": "w", "name": "w", "priority": 0,
1039    ///     "tasks": [
1040    ///         {"id": "a", "name": "a", "function": {"name": "map", "input": {"mappings": []}}},
1041    ///         {"id": "b", "name": "b",
1042    ///          "function": {"name": "enrich",
1043    ///                       "input": {"connector": "c", "merge_path": "data.out"}}}
1044    ///     ]
1045    /// }"#).unwrap();
1046    ///
1047    /// let builder = Engine::builder();
1048    /// let unrunnable: Vec<&str> = workflow
1049    ///     .tasks
1050    ///     .iter()
1051    ///     .map(|t| t.function.function_name())
1052    ///     .filter(|name| !builder.can_dispatch(name))
1053    ///     .collect();
1054    ///
1055    /// assert_eq!(unrunnable, vec!["enrich"]);
1056    /// ```
1057    pub fn can_dispatch(&self, name: &str) -> bool {
1058        can_dispatch_in(&self.handlers, name)
1059    }
1060
1061    /// Check a workflow against this builder's registered handlers, operators
1062    /// and secrets, without consuming the builder or building an engine.
1063    ///
1064    /// The pre-build twin of [`Engine::check_workflow`], with identical
1065    /// semantics. Takes `&self`, so a host can screen a batch of definitions
1066    /// against the registrations it is about to build with.
1067    ///
1068    /// Templates are compiled against a datalogic engine configured exactly as
1069    /// [`Self::build`] will configure it — same custom operators, same
1070    /// templating mode — so a template that passes here compiles there.
1071    ///
1072    /// ```
1073    /// use dataflow_rs::{Engine, IssueCode, Workflow};
1074    ///
1075    /// let workflow = Workflow::from_json(r#"{
1076    ///     "id": "w", "name": "w", "priority": 0,
1077    ///     "tasks": [{"id": "t", "name": "t",
1078    ///                "function": {"name": "typo_handler", "input": {}}}]
1079    /// }"#).unwrap();
1080    ///
1081    /// let issues = Engine::builder().check_workflow(&workflow);
1082    /// assert_eq!(issues[0].code, IssueCode::UnknownFunction);
1083    /// assert_eq!(issues[0].task_id.as_deref(), Some("t"));
1084    /// ```
1085    pub fn check_workflow(&self, workflow: &Workflow) -> Vec<WorkflowIssue> {
1086        // Build the datalogic engine the same way `build()` does, so template
1087        // compilation here is the same operation it will be there — rather than
1088        // an approximation a caller has to keep in step by hand.
1089        let compiler = LogicCompiler::with_operators(&self.datalogic_operators);
1090        let template_compiler = TemplateCompiler::new(compiler.into_engine());
1091        // With no store configured, nothing is declared and a literal name is
1092        // genuinely unknown — reporting it is the right answer. A store that is
1093        // *malformed* is a different problem: it fails `build()`, and checking
1094        // against the empty store would report every literal name as unknown
1095        // and bury the one thing actually wrong. So that case reports the store
1096        // instead, and drops the name verdicts — the only ones that depend on
1097        // it — below.
1098        let store = match &self.secrets {
1099            Some(Ok(secrets)) => secrets,
1100            None | Some(Err(_)) => &secrets::EMPTY,
1101        };
1102        let mut issues =
1103            authoring::check_against_registry(workflow, &self.handlers, &template_compiler, store);
1104
1105        if let Some(Err(err)) = &self.secrets {
1106            issues.retain(|issue| issue.code != IssueCode::UnknownSecret);
1107            issues.insert(
1108                0,
1109                WorkflowIssue {
1110                    code: IssueCode::InvalidSecretStore,
1111                    message: format!("the configured secret store is unusable: {err}"),
1112                    path: None,
1113                    task_id: None,
1114                },
1115            );
1116        }
1117        issues
1118    }
1119
1120    /// Add a single workflow. Subsequent calls append.
1121    pub fn with_workflow(mut self, workflow: Workflow) -> Self {
1122        self.workflows.push(workflow);
1123        self
1124    }
1125
1126    /// Append every workflow in `workflows`. Accepts anything iterable —
1127    /// `Vec<Workflow>`, an array, an iterator. Existing workflows on the
1128    /// builder are kept; subsequent registers/workflows still chain.
1129    pub fn with_workflows<I>(mut self, workflows: I) -> Self
1130    where
1131        I: IntoIterator<Item = Workflow>,
1132    {
1133        self.workflows.extend(workflows);
1134        self
1135    }
1136
1137    /// Insert every handler in `handlers`, keeping any already registered.
1138    ///
1139    /// Same extend-not-replace semantics as [`EngineBuilder::with_workflows`].
1140    /// Exists because `register` is per-name, which pushed an embedder that
1141    /// builds a whole `HashMap<String, BoxedFunctionHandler>` in one place onto
1142    /// [`Engine::new`] and off the builder entirely — and therefore out of reach
1143    /// of [`EngineBuilder::with_observer`].
1144    pub fn with_handlers(mut self, handlers: HashMap<String, BoxedFunctionHandler>) -> Self {
1145        self.handlers.extend(handlers);
1146        self
1147    }
1148
1149    /// Attach a per-task [`ExecutionObserver`]. Later calls replace the previous
1150    /// one.
1151    ///
1152    /// This is the only way to time the sync built-ins, which are dispatched
1153    /// inside the executor and never reach the function registry. With no
1154    /// observer attached the instrumentation — including its clock reads — stays
1155    /// out of the dispatch path entirely.
1156    pub fn with_observer(mut self, observer: Arc<dyn ExecutionObserver>) -> Self {
1157        self.observer = Some(observer);
1158        self
1159    }
1160
1161    /// Mirror per-task failure codes into the message context at `path`, so a
1162    /// downstream `condition` or `map` can branch on *why* a task failed.
1163    ///
1164    /// Off unless called: with no path configured nothing is written and the
1165    /// mechanism costs one `Option` check on a path that only runs after a task
1166    /// has already failed.
1167    ///
1168    /// One record is appended per error a task contributes to
1169    /// [`Message::errors`](crate::engine::message::Message::errors):
1170    ///
1171    /// ```json
1172    /// { "workflow_id": "place_order", "task_id": "charge_payment",
1173    ///   "code": "TIMEOUT_ERROR", "status": 500 }
1174    /// ```
1175    ///
1176    /// so a later task can gate on the reason:
1177    ///
1178    /// ```json
1179    /// { "in": [ { "var": "metadata.errors.0.code" },
1180    ///           ["TIMEOUT_ERROR", "IO_ERROR"] ] }
1181    /// ```
1182    ///
1183    /// Coverage matches `errors()` exactly — a handler returning `Err`, a task
1184    /// returning a 5xx outcome, the `validation` built-in's per-rule failures, and
1185    /// anything a handler adds through
1186    /// [`TaskContext::add_error`](crate::engine::task_context::TaskContext::add_error)
1187    /// all appear. The workflow-level `WORKFLOW_ERROR` wrapper does not: it
1188    /// re-reports the same underlying failure, so mirroring it would double-count.
1189    ///
1190    /// `status` is the task's own status — `500` when the handler returned `Err`,
1191    /// otherwise the status the outcome carried (`400` for `validation`). That is
1192    /// the distinction `metadata.progress` cannot make, since its failure arm
1193    /// hard-codes `500`.
1194    ///
1195    /// The error `message` and the operator-only `detail` are deliberately **not**
1196    /// recorded: the context is serialized back to callers, and `detail` is
1197    /// documented as unsafe to hand to an untrusted one. Read those from
1198    /// `message.errors()` host-side.
1199    ///
1200    /// `path` must start with `data`, `metadata` or `temp_data` — the JSONLogic
1201    /// evaluation context is exactly those three slots — and may not be
1202    /// `metadata.progress`. Violations fail [`EngineBuilder::build`].
1203    pub fn with_error_context_path(mut self, path: impl Into<String>) -> Self {
1204        self.error_context_path = Some(path.into());
1205        self
1206    }
1207
1208    /// Cap the number of records retained at the error-context path, keeping the
1209    /// most recent (default 32).
1210    ///
1211    /// The bound is what keeps the option's memory cost independent of a looping
1212    /// workflow's iteration count: `Message.context` is deep-cloned into every
1213    /// trace snapshot, so an uncapped list in a loop with a failing body grows the
1214    /// trace quadratically. Conditions overwhelmingly read the latest failure, so
1215    /// the oldest records are the ones dropped.
1216    ///
1217    /// Setting a limit without a path is inert, not an error. A limit of `0` fails
1218    /// [`EngineBuilder::build`].
1219    pub fn with_error_context_limit(mut self, limit: usize) -> Self {
1220        self.error_context_limit = Some(limit);
1221        self
1222    }
1223
1224    /// Values expressions may read through `{"secret": "name"}` but the engine
1225    /// never records.
1226    ///
1227    /// `secrets` must be a JSON object; [`Self::build`] rejects anything else.
1228    /// Nested objects are allowed and reached with a dotted path
1229    /// (`{"secret": "partner.hmac"}`). The host owns resolution — pass the
1230    /// values, not references to a vault. Later calls replace the earlier store.
1231    ///
1232    /// The store never enters a [`Message`]: not its `Serialize`, not an
1233    /// [`ExecutionTrace`] snapshot, not a `mapping_contexts` clone. That is the
1234    /// point of the store, and the reason the values are not simply seeded into
1235    /// `metadata`.
1236    pub fn with_secrets(mut self, secrets: OwnedDataValue) -> Self {
1237        self.secrets = Some(Secrets::new(secrets));
1238        self
1239    }
1240
1241    /// [`Self::with_secrets`] from a `serde_json::Value`.
1242    pub fn with_secrets_json(self, secrets: &serde_json::Value) -> Self {
1243        self.with_secrets(OwnedDataValue::from(secrets))
1244    }
1245
1246    /// Bound every JSONLogic evaluation this engine performs to `budget`
1247    /// operations. Not calling this leaves evaluation unbounded, as before.
1248    ///
1249    /// One operation is one dispatched node, one item an iterator examines, or
1250    /// whatever an operator charges for the data it moves; literals and
1251    /// constant-folded subtrees cost nothing. Crossing the ceiling aborts that
1252    /// evaluation *before* the work is done — which is the point: a
1253    /// deterministic bound on untrusted rules, identical on every machine,
1254    /// rather than a wall-clock timeout that reports the cost only after
1255    /// paying it.
1256    ///
1257    /// The ceiling is per *evaluation*, not per task, message or workflow: a
1258    /// task that evaluates ten expressions gets `budget` operations for each.
1259    /// Sizing it is empirical — start well above the cost of your legitimate
1260    /// rules.
1261    ///
1262    /// # How a refusal reaches you depends on what was being evaluated
1263    ///
1264    /// The ceiling is installed on the engine, so it bounds *every* evaluation.
1265    /// How the refusal is reported is not uniform:
1266    ///
1267    /// - A handler's evaluation ([`TaskContext::eval`] and friends, and any
1268    ///   [`Template`] parameter) surfaces [`DataflowError::BudgetExceeded`],
1269    ///   recorded in `message.errors()` with code `BUDGET_EXCEEDED`.
1270    /// - A **condition** — on a workflow, task or group, or in `filter` —
1271    ///   fails closed to `false` and is reported only in the log, because
1272    ///   condition evaluation has no error channel: every datalogic failure
1273    ///   there has always collapsed to "did not match". So a refused condition
1274    ///   skips its workflow or task rather than rejecting the message.
1275    /// - `map`, `log` and `validation` log the refusal and continue, the same
1276    ///   way they treat any other evaluation failure.
1277    ///
1278    /// Only the first is distinguishable from an ordinary failure by code.
1279    ///
1280    /// Carried across [`Engine::with_new_workflows`], so a hot reload cannot
1281    /// silently lift the bound.
1282    ///
1283    /// Requires the `budget` feature.
1284    ///
1285    /// ```no_run
1286    /// # use dataflow_rs::Engine;
1287    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1288    /// let engine = Engine::builder().with_ops_budget(100_000).build()?;
1289    /// # let _ = engine;
1290    /// # Ok(())
1291    /// # }
1292    /// ```
1293    #[cfg(feature = "budget")]
1294    pub fn with_ops_budget(mut self, budget: u64) -> Self {
1295        self.ops_budget = Some(budget);
1296        self
1297    }
1298
1299    /// Register a custom JSONLogic operator on the engine's internal datalogic
1300    /// instance, under `name`. Later calls with the same name replace the
1301    /// earlier registration.
1302    ///
1303    /// This is the host's door for domain operators: the engine builds (and on
1304    /// [`Engine::with_new_workflows`] *rebuilds*) its datalogic engine
1305    /// internally, where registration is builder-only — so operators must
1306    /// enter here to exist at all, and are retained on the engine so every
1307    /// hot reload re-registers them.
1308    ///
1309    /// Semantics follow `datalogic_rs`: arguments arrive pre-evaluated, and a
1310    /// built-in operator name always wins over a custom registration — pick
1311    /// names no built-in uses. Because the engine always runs in templating
1312    /// mode, a name that is *not* registered is not an error: the object
1313    /// echoes back as literal data, exactly like a disabled operator family.
1314    /// Registering a name therefore converts previously-inert values into
1315    /// live operator calls, the same caveat the cargo features carry.
1316    ///
1317    /// `secret` is reserved for the engine's own operator (see
1318    /// [`Self::with_secrets`]); registering it fails [`Self::build`].
1319    pub fn with_datalogic_operator<T>(mut self, name: impl Into<String>, operator: T) -> Self
1320    where
1321        T: datalogic_rs::CustomOperator + 'static,
1322    {
1323        self.datalogic_operators
1324            .insert(name.into(), Arc::new(operator));
1325        self
1326    }
1327
1328    /// Compile the workflows, pre-parse Custom inputs, and produce the
1329    /// engine. Compile errors and missing handler references surface here —
1330    /// the engine never deserializes Custom config on the hot path.
1331    pub fn build(self) -> Result<Engine> {
1332        // Validated here rather than at the setter so an invalid path fails at
1333        // engine construction alongside every other config-shape error, instead
1334        // of on the first message that happens to fail a task.
1335        let error_context = match self.error_context_path {
1336            Some(path) => Some(Arc::new(ErrorContextConfig::new(
1337                path,
1338                self.error_context_limit
1339                    .unwrap_or(DEFAULT_ERROR_CONTEXT_LIMIT),
1340            )?)),
1341            None => None,
1342        };
1343        let secrets = Arc::new(match self.secrets {
1344            Some(secrets) => secrets?,
1345            None => Secrets::empty(),
1346        });
1347        let engine = Engine::new_inner(
1348            self.workflows,
1349            self.handlers,
1350            Arc::new(self.datalogic_operators),
1351            secrets,
1352            self.ops_budget,
1353        )?;
1354        let engine = match error_context {
1355            Some(cfg) => engine.with_error_context(cfg),
1356            None => engine,
1357        };
1358        Ok(match self.observer {
1359            Some(observer) => engine.with_observer(observer),
1360            None => engine,
1361        })
1362    }
1363}
1364
1365/// Fail construction on the first workflow with a refusable authoring issue —
1366/// a secret an expression may not read, or a template object whose keys
1367/// collide. The same checks `check_workflow` reports, so what builds and what
1368/// checks clean are one set. Runs on the authored workflows before
1369/// compilation; nothing here needs compiled logic.
1370///
1371/// `check_workflow` additionally reports `ESCAPED_TEMPLATE_KEY`, the one
1372/// template-key finding that is [`Severity::Advisory`]; it is deliberately
1373/// *not* refused, because after a migration a `$`-escaped key is exactly what
1374/// the author meant.
1375fn refuse_authoring_issues(workflows: &[Workflow], secrets: &Secrets) -> Result<()> {
1376    for workflow in workflows {
1377        let mut issues = authoring::check_secrets(workflow, secrets);
1378        issues.extend(authoring::refusing_template_key_issues(workflow));
1379        if !issues.is_empty() {
1380            let listed: Vec<String> = issues.iter().map(ToString::to_string).collect();
1381            return Err(DataflowError::Validation(format!(
1382                "workflow '{}': {}",
1383                workflow.id,
1384                listed.join("; ")
1385            )));
1386        }
1387    }
1388    Ok(())
1389}
1390
1391/// Walk every task in every workflow; for each `FunctionConfig::Custom`,
1392/// look up the registered handler and ask it to parse the raw `input` JSON
1393/// into its typed `Self::Input` (boxed as `dyn Any`). The cached result is
1394/// stored on the task — dispatch then hands the handler a `&dyn Any` it
1395/// downcasts in O(1).
1396///
1397/// Built-in async configs (`HttpCall`, `Enrich`, `PublishKafka`) are already
1398/// parsed by serde's `untagged` representation on `FunctionConfig`; they
1399/// need no second pass.
1400///
1401/// Returns `FunctionNotFound` when a Custom task references an unregistered
1402/// handler — moves the failure from "first message" to engine construction.
1403fn precompile_custom_inputs(
1404    workflows: &mut [Workflow],
1405    handlers: &HashMap<String, BoxedFunctionHandler>,
1406    datalogic: &Arc<DatalogicEngine>,
1407) -> Result<()> {
1408    let template_compiler = TemplateCompiler::new(Arc::clone(datalogic));
1409    for workflow in workflows {
1410        for task in &mut workflow.tasks {
1411            if let FunctionConfig::Custom {
1412                name,
1413                input,
1414                compiled_input,
1415            } = &mut task.function
1416            {
1417                let handler = handlers
1418                    .get(name)
1419                    .ok_or_else(|| function_not_found_error(name, handlers))?;
1420                let mut parsed = handler.parse_input_box(input)?;
1421                handler.compile_input_box(&mut *parsed, &template_compiler)?;
1422                *compiled_input = Some(CompiledCustomInput(Arc::from(parsed)));
1423            }
1424        }
1425    }
1426    Ok(())
1427}
1428
1429/// Build a `FunctionNotFound` error that lists both the registered custom
1430/// handlers and the names of built-in functions, so a user with a typo
1431/// (e.g. `htttp_call`) can immediately spot the intended name.
1432///
1433/// **This message is free-form and deliberately unpinned.** It is a diagnostic
1434/// for humans; its wording and layout may change in any release. No test
1435/// asserts on it, and none should — a caller that needs the built-in vocabulary
1436/// programmatically should use [`crate::BUILTIN_FUNCTION_NAMES`] and
1437/// [`crate::builtin_function_kind`], which exist for exactly that purpose and
1438/// answer the sharper question of whether a name needs a registered handler.
1439fn function_not_found_error(
1440    name: &str,
1441    handlers: &HashMap<String, BoxedFunctionHandler>,
1442) -> DataflowError {
1443    use crate::engine::functions::config::BUILTIN_FUNCTION_NAMES;
1444    let mut registered: Vec<&str> = handlers.keys().map(String::as_str).collect();
1445    registered.sort_unstable();
1446    let registered_part = if registered.is_empty() {
1447        String::from("none")
1448    } else {
1449        registered.join(", ")
1450    };
1451    DataflowError::FunctionNotFound(format!(
1452        "{name} (registered handlers: {registered_part}; built-ins: {})",
1453        BUILTIN_FUNCTION_NAMES.join(", ")
1454    ))
1455}
1456
1457/// Stamp the standard processing metadata (`processed_at`, `engine_version`,
1458/// and optionally `channel`) into the message context.
1459///
1460/// `now` is captured once at the top of `process_message` and reused so the
1461/// timestamp on `metadata.processed_at` matches the one used for every
1462/// `AuditTrail` entry within the same call.
1463///
1464/// Walks to the `metadata` object once and sets every key in a single pass,
1465/// instead of one full `"metadata.*"` path split + tree walk per key.
1466/// Mirrors `set_nested_value` semantics for the degenerate shapes: a
1467/// non-object context or a non-object existing `metadata` slot no-ops; a
1468/// missing `metadata` slot is created.
1469///
1470/// `(**engine_version).clone()` deep-clones the inner `String` — the
1471/// context owns its values, so one small allocation per message is
1472/// inherent; the cached `Arc` only saves re-formatting the version.
1473fn set_processing_metadata(
1474    context: &mut OwnedDataValue,
1475    engine_version: &Arc<OwnedDataValue>,
1476    now: chrono::DateTime<Utc>,
1477    channel: Option<&str>,
1478) {
1479    let OwnedDataValue::Object(top) = context else {
1480        return;
1481    };
1482    let metadata = match top.iter().position(|(k, _)| k == "metadata") {
1483        Some(i) => &mut top[i].1,
1484        None => {
1485            top.push(("metadata".to_string(), OwnedDataValue::Object(Vec::new())));
1486            &mut top.last_mut().expect("just pushed").1
1487        }
1488    };
1489    let OwnedDataValue::Object(meta) = metadata else {
1490        return;
1491    };
1492
1493    let mut set_key = |key: &str, value: OwnedDataValue| {
1494        if let Some(slot) = meta.iter_mut().find(|(k, _)| k == key) {
1495            slot.1 = value;
1496        } else {
1497            meta.push((key.to_string(), value));
1498        }
1499    };
1500    set_key("processed_at", OwnedDataValue::String(now.to_rfc3339()));
1501    set_key("engine_version", (**engine_version).clone());
1502    if let Some(channel) = channel {
1503        set_key("channel", OwnedDataValue::String(channel.to_string()));
1504    }
1505}