Skip to main content

fluxpro_engine/models/
process_def.rs

1//! Workflow schema and structural validation for JSON and YAML definitions.
2
3use crate::models::context_map::context_map::ContextMap;
4use crate::models::id_field::IdField;
5use crate::models::process_def::escalation_def::EscalationDef;
6use crate::models::process_def_error::CreateProcessError;
7use crate::models::version_id::VersionId;
8use anyhow::Error;
9use chrono::{DateTime, Duration, Utc};
10use serde::{Deserialize, Serialize};
11use serde_json::Value as JsonValue;
12use serde_json::json;
13use std::collections::HashSet;
14use std::fmt::Display;
15use uuid::Uuid;
16
17pub mod escalation_def;
18
19/// A versioned workflow definition with declarations and executable nodes.
20///
21/// # Examples
22///
23/// ```
24/// use fluxpro_engine::models::process_def::ProcessDefinition;
25///
26/// let definition: ProcessDefinition = serde_json::from_value(serde_json::json!({
27///     "key": "demo", "name": "Demo", "version": "1.0.0", "status": "active",
28///     "effective_from": "2026-01-01T00:00:00Z",
29///     "stages": [{ "id": "created", "name": "Created", "is_initial": true }],
30///     "nodes": [
31///         { "id": "start", "type": "Start", "next": "done" },
32///         { "id": "done", "type": "End" }
33///     ]
34/// })).unwrap();
35/// assert!(definition.validate().is_ok());
36/// assert_eq!(definition.compile().unwrap()["nodes"][0]["type"], "Start");
37/// ```
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ProcessDefinition {
40    /// Database identity; skipped in JSON/YAML and assigned after persistence.
41    #[serde(skip)]
42    pub uuid: Option<Uuid>,
43    /// Logical process key shared by all versions of this workflow.
44    pub key: IdField,
45    /// Human-readable process name.
46    pub name: String,
47    /// Normalized process definition version.
48    pub version: VersionId,
49
50    /// Only active definitions within their effective dates may start new instances.
51    pub status: ProcessStatus,
52
53    /// UTC time from which this definition can be selected.
54    pub effective_from: Option<DateTime<Utc>>,
55
56    /// UTC time after which this definition is excluded from runtime selection.
57    #[serde(default)]
58    pub deprecated_at: Option<DateTime<Utc>>,
59
60    /// Optional ownership, SLA, and version notes.
61    #[serde(default)]
62    pub metadata: ProcessMetadata,
63
64    /// Signal declarations available to the workflow.
65    #[serde(default)]
66    pub signals: Vec<SignalDef>,
67
68    /// Forms declared for user-task lifecycle hooks.
69    #[serde(default)]
70    pub forms: Vec<FormDef>,
71
72    /// Business stages; runtime startup requires an initial stage.
73    #[serde(default)]
74    pub stages: Vec<StageDef>,
75
76    /// Optional callbacks invoked during stage, form, and completion events.
77    pub special_handlers: Option<SpecialHandlers>,
78
79    /// Operator escalation topics and available actions.
80    #[serde(default)]
81    pub escalations: Vec<EscalationDef>,
82
83    /// Workflow graph; exactly one Start and at least one End are required.
84    pub nodes: Vec<Node>,
85}
86
87impl ProcessDefinition {
88    /// Validates references and serializes this definition to JSON.
89    ///
90    /// # Errors
91    ///
92    /// Returns structural failures and, with `runtime`, condition compilation errors.
93    pub fn compile(&self) -> Result<JsonValue, CreateProcessError> {
94        self.validate()?;
95        Ok(json!(self))
96    }
97
98    /// Checks unique IDs, start/end presence, references, and service retry settings.
99    ///
100    /// # Errors
101    ///
102    /// Returns accumulated validation messages, including initial stages and timers.
103    /// With `runtime`, also compiles conditions. Handler registration is host-owned.
104    /// Use `unreachable_nodes` for reachability diagnostics.
105    pub fn validate(&self) -> Result<(), CreateProcessError> {
106        let mut errors = Vec::new();
107        let node_ids = collect_unique_ids(
108            "node",
109            self.nodes.iter().map(|node| node.id().get_id()),
110            &mut errors,
111        );
112        let signals = collect_unique_ids(
113            "signal",
114            self.signals.iter().map(SignalDef::name),
115            &mut errors,
116        );
117        let forms = collect_unique_ids(
118            "form",
119            self.forms.iter().map(|form| form.id.get_id()),
120            &mut errors,
121        );
122        let stages = collect_unique_ids(
123            "stage",
124            self.stages.iter().map(|stage| stage.id().get_id()),
125            &mut errors,
126        );
127        let escalations = collect_unique_ids(
128            "escalation topic",
129            self.escalations
130                .iter()
131                .map(|escalation| escalation.topic.get_id()),
132            &mut errors,
133        );
134
135        let initial = self
136            .stages
137            .iter()
138            .filter(|stage| stage.is_initial())
139            .count();
140        if initial != 1 {
141            errors.push(format!(
142                "process must contain exactly one initial stage; found {initial}"
143            ));
144        }
145        if let (Some(from), Some(until)) = (self.effective_from, self.deprecated_at) {
146            if until <= from {
147                errors.push("deprecated_at must be later than effective_from".into());
148            }
149        }
150        let starts = self.nodes.iter().filter(|node| node.is_start()).count();
151        if starts != 1 {
152            errors.push(format!(
153                "process must contain exactly one Start node; found {starts}"
154            ));
155        }
156        if !self.nodes.iter().any(|node| node.is_end()) {
157            errors.push("process must contain at least one End node".into());
158        }
159
160        let check_node = |source: &str, field: &str, target: &IdField, errors: &mut Vec<String>| {
161            if !node_ids.contains(target.get_id()) {
162                errors.push(format!(
163                    "node '{source}' field '{field}' references missing node '{}'",
164                    target.get_id()
165                ));
166            }
167        };
168        let check_next = |source: &str, next: &Next, errors: &mut Vec<String>| match next {
169            Next::To(target) => check_node(source, "next", target, errors),
170            Next::Routes(routes) => {
171                if let Some(target) = &routes.default {
172                    check_node(source, "next.default", target, errors);
173                }
174                for (index, branch) in routes.branches.iter().enumerate() {
175                    check_node(
176                        source,
177                        &format!("next.branches[{index}].next"),
178                        &branch.next,
179                        errors,
180                    );
181                }
182            }
183        };
184        let check_stage = |node: &Node, errors: &mut Vec<String>| {
185            if let Some(stage) = node.set_stage() {
186                let stage = stage.stage_with_reason().stage;
187                if !stages.contains(stage.get_id()) {
188                    errors.push(format!(
189                        "node '{}' references undeclared stage '{}'",
190                        node.id(),
191                        stage
192                    ));
193                }
194            }
195        };
196
197        for node in &self.nodes {
198            let source = node.id().get_id();
199            check_stage(node, &mut errors);
200            if let Node::Wait { timeout, .. } | Node::UserTask { timeout, .. } = node {
201                if let Some(timer) = timeout {
202                    if let Err(error) = timer.after_now() {
203                        errors.push(format!("node '{source}' has invalid timeout: {error}"));
204                    }
205                }
206            }
207            let wait = match node {
208                Node::Wait { wait_for, .. } => Some(wait_for),
209                Node::UserTask { wait_for, .. } => wait_for.as_ref(),
210                _ => None,
211            };
212            if wait.is_some_and(|wait| wait.signals().is_empty()) {
213                errors.push(format!(
214                    "node '{source}' wait_for.signals must not be empty"
215                ));
216            }
217            #[cfg(feature = "runtime")]
218            for (index, branch) in node_branches(node).iter().enumerate() {
219                if let Err(error) = crate::service::expressions::validate_condition(&branch.when) {
220                    errors.push(format!("node '{source}' branch {index}: {error}"));
221                }
222            }
223            match node {
224                Node::Start { next, .. } => check_node(source, "next", next, &mut errors),
225                Node::End { .. } => {}
226                Node::ServiceTask {
227                    handler,
228                    args,
229                    next,
230                    on_error,
231                    retries,
232                    ..
233                } => {
234                    if let Some(next) = next {
235                        check_next(source, next, &mut errors);
236                    }
237                    check_on_error(source, on_error.as_ref(), &check_node, &mut errors);
238                    if let Some(retries) = retries {
239                        if retries.max == 0 {
240                            errors.push(format!(
241                                "node '{source}' retries.max must be greater than zero"
242                            ));
243                        }
244                        if retries.next_attempt_at().is_err() {
245                            errors.push(format!(
246                                "node '{source}' has invalid retries.backoff '{}'",
247                                retries.backoff
248                            ));
249                        }
250                    }
251                    if handler.get_id() == "create_support_ticket" {
252                        let topic_key = IdField::new("topic").expect("static topic ID is valid");
253                        let topic = args
254                            .as_ref()
255                            .and_then(|args| args.as_id_field(&topic_key))
256                            .map(|topic| topic.get_id().to_owned());
257                        match topic {
258                            Some(topic) if escalations.contains(topic.as_str()) => {}
259                            Some(topic) => errors.push(format!(
260                                "node '{source}' references undeclared escalation topic '{topic}'"
261                            )),
262                            None => errors.push(format!(
263                                "node '{source}' handler 'create_support_ticket' requires args.topic"
264                            )),
265                        }
266                    }
267                }
268                Node::UserTask {
269                    form,
270                    wait_for,
271                    timeout,
272                    next,
273                    on_error,
274                    ..
275                } => {
276                    if !forms.contains(form.get_id()) {
277                        errors.push(format!(
278                            "node '{source}' references undeclared form '{form}'"
279                        ));
280                    }
281                    if let Some(wait_for) = wait_for {
282                        for signal in wait_for.signals() {
283                            if !signals.contains(signal.get_id()) {
284                                errors.push(format!(
285                                    "node '{source}' waits for undeclared signal '{signal}'"
286                                ));
287                            }
288                        }
289                    }
290                    if let Some(timeout) = timeout {
291                        check_node(
292                            source,
293                            "timeout.on_timeout",
294                            &timeout.on_timeout,
295                            &mut errors,
296                        );
297                    }
298                    if let Some(next) = next {
299                        check_next(source, next, &mut errors);
300                    }
301                    check_on_error(source, on_error.as_ref(), &check_node, &mut errors);
302                }
303                Node::Wait {
304                    wait_for,
305                    timeout,
306                    next,
307                    ..
308                } => {
309                    for signal in wait_for.signals() {
310                        if !signals.contains(signal.get_id()) {
311                            errors.push(format!(
312                                "node '{source}' waits for undeclared signal '{signal}'"
313                            ));
314                        }
315                    }
316                    if let Some(timeout) = timeout {
317                        check_node(
318                            source,
319                            "timeout.on_timeout",
320                            &timeout.on_timeout,
321                            &mut errors,
322                        );
323                    }
324                    if let Some(next) = next {
325                        check_next(source, next, &mut errors);
326                    }
327                }
328                Node::Gateway { branches, next, .. } => {
329                    for (index, branch) in branches.iter().enumerate() {
330                        check_node(
331                            source,
332                            &format!("branches[{index}].next"),
333                            &branch.next,
334                            &mut errors,
335                        );
336                    }
337                    if let Some(next) = next {
338                        check_node(source, "next", next, &mut errors);
339                    }
340                }
341            }
342        }
343
344        for escalation in &self.escalations {
345            let mut action_ids = HashSet::new();
346            for action in &escalation.actions {
347                if !action_ids.insert(action.id.get_id()) {
348                    errors.push(format!(
349                        "escalation '{}' contains duplicate action id '{}'",
350                        escalation.topic, action.id
351                    ));
352                }
353                if let Some(signal) = &action.emit_signal
354                    && !signals.contains(signal.get_id())
355                {
356                    errors.push(format!(
357                        "escalation '{}' action '{}' emits undeclared signal '{}'",
358                        escalation.topic, action.id, signal
359                    ));
360                }
361            }
362        }
363
364        if errors.is_empty() {
365            Ok(())
366        } else {
367            Err(CreateProcessError::ValidationError(errors))
368        }
369    }
370
371    /// Lists nodes with no structural path from Start, in definition order.
372    ///
373    /// This is diagnostic rather than a registration error because hosts may
374    /// explicitly enqueue auxiliary nodes. Conditions are not evaluated.
375    pub fn unreachable_nodes(&self) -> Vec<IdField> {
376        let mut reached = HashSet::new();
377        let mut pending: Vec<&Node> = self.nodes.iter().filter(|node| node.is_start()).collect();
378        while let Some(node) = pending.pop() {
379            if !reached.insert(node.id()) {
380                continue;
381            }
382            for target in node_targets(node) {
383                if let Some(next) = self.nodes.iter().find(|node| node.id() == target) {
384                    pending.push(next);
385                }
386            }
387        }
388        self.nodes
389            .iter()
390            .filter(|node| !reached.contains(node.id()))
391            .map(|node| node.id().clone())
392            .collect()
393    }
394}
395
396fn node_branches(node: &Node) -> &[Branch] {
397    match node {
398        Node::Gateway { branches, .. } => branches,
399        Node::ServiceTask {
400            next: Some(Next::Routes(routes)),
401            ..
402        }
403        | Node::UserTask {
404            next: Some(Next::Routes(routes)),
405            ..
406        }
407        | Node::Wait {
408            next: Some(Next::Routes(routes)),
409            ..
410        } => &routes.branches,
411        _ => &[],
412    }
413}
414
415fn node_targets(node: &Node) -> Vec<&IdField> {
416    let mut targets: Vec<&IdField> = node_branches(node).iter().map(|b| &b.next).collect();
417    match node {
418        Node::Start { next, .. } => targets.push(next),
419        Node::Gateway { next, .. } => targets.extend(next),
420        Node::ServiceTask { next, .. } | Node::Wait { next, .. } | Node::UserTask { next, .. } => {
421            match next {
422                Some(Next::To(target)) => targets.push(target),
423                Some(Next::Routes(routes)) => targets.extend(&routes.default),
424                None => {}
425            }
426        }
427        Node::End { .. } => {}
428    }
429    match node {
430        Node::Wait {
431            timeout: Some(timer),
432            ..
433        }
434        | Node::UserTask {
435            timeout: Some(timer),
436            ..
437        } => targets.push(&timer.on_timeout),
438        _ => {}
439    }
440    if let Node::ServiceTask {
441        on_error: Some(error),
442        ..
443    } = node
444    {
445        targets.extend(&error.next);
446    }
447    targets
448}
449
450fn collect_unique_ids<'a>(
451    kind: &str,
452    values: impl Iterator<Item = &'a str>,
453    errors: &mut Vec<String>,
454) -> HashSet<&'a str> {
455    let mut result = HashSet::new();
456    for value in values {
457        if !result.insert(value) {
458            errors.push(format!("duplicate {kind} id '{value}'"));
459        }
460    }
461    result
462}
463
464fn check_on_error(
465    source: &str,
466    on_error: Option<&OnError>,
467    check_node: &impl Fn(&str, &str, &IdField, &mut Vec<String>),
468    errors: &mut Vec<String>,
469) {
470    if let Some(on_error) = on_error {
471        if let Some(next) = &on_error.next {
472            check_node(source, "on_error.next", next, errors);
473        }
474        if let Some(compensate) = &on_error.compensate {
475            check_node(source, "on_error.compensate", compensate, errors);
476        }
477    }
478}
479
480#[cfg(all(test, feature = "api"))]
481mod validation_tests {
482    use super::*;
483
484    const TK_ONLINE_DEFINITION: &str = include_str!("../../tests/fixtures/tk_online.yaml");
485    const CASH_LOAN_DEFINITION: &str = include_str!("../../tests/fixtures/cash_loan.yaml");
486
487    #[test]
488    fn a_process_definition_is_valid() {
489        let definition: ProcessDefinition = serde_yaml::from_str(TK_ONLINE_DEFINITION).unwrap();
490
491        definition.validate().unwrap();
492    }
493
494    #[test]
495    fn a_user_task_can_start_a_timeout_after_a_previous_signal() {
496        let definition: ProcessDefinition = serde_yaml::from_str(TK_ONLINE_DEFINITION).unwrap();
497
498        let open_node = definition
499            .nodes
500            .iter()
501            .find(|node| node.id().get_id() == "credit_info_open")
502            .unwrap();
503        let Node::UserTask {
504            wait_for: Some(wait_for),
505            timeout: None,
506            next: Some(Next::To(next)),
507            ..
508        } = open_node
509        else {
510            panic!("credit_info_open must wait for page opening without a timeout");
511        };
512        assert_eq!(wait_for.signals()[0].get_id(), "credit_info_opened");
513        assert_eq!(next.get_id(), "credit_info");
514
515        let timer_node = definition
516            .nodes
517            .iter()
518            .find(|node| node.id().get_id() == "credit_info")
519            .unwrap();
520        let Node::UserTask {
521            wait_for: Some(wait_for),
522            timeout: Some(timeout),
523            ..
524        } = timer_node
525        else {
526            panic!("credit_info must be the timed credit-info task");
527        };
528        assert_eq!(wait_for.signals()[0].get_id(), "terms_viewed");
529        assert_eq!(timeout.after.as_deref(), Some("PT3M"));
530    }
531
532    #[test]
533    fn a_wait_node_is_valid() {
534        let definition: ProcessDefinition = serde_yaml::from_str(CASH_LOAN_DEFINITION).unwrap();
535
536        definition.validate().unwrap();
537        let wait = definition
538            .nodes
539            .iter()
540            .find(|node| node.id().get_id() == "final_terms_after_reminder")
541            .unwrap();
542        assert!(matches!(wait, Node::Wait { .. }));
543    }
544
545    #[test]
546    fn a_user_task_can_route_on_multiple_signals_before_a_timeout() {
547        let definition: ProcessDefinition = serde_yaml::from_str(CASH_LOAN_DEFINITION).unwrap();
548
549        let open_node = definition
550            .nodes
551            .iter()
552            .find(|node| node.id().get_id() == "select_terms_open")
553            .unwrap();
554        let Node::UserTask {
555            wait_for: Some(wait_for),
556            timeout: None,
557            next: Some(Next::To(next)),
558            ..
559        } = open_node
560        else {
561            panic!("select_terms_open must wait for calculator signals without a timeout");
562        };
563        assert_eq!(
564            wait_for
565                .signals()
566                .iter()
567                .map(|signal| signal.get_id())
568                .collect::<Vec<_>>(),
569            vec!["calculator_interacted", "terms_selected"]
570        );
571        assert_eq!(next.get_id(), "select_terms_open_route");
572
573        let route_node = definition
574            .nodes
575            .iter()
576            .find(|node| node.id().get_id() == "select_terms_open_route")
577            .unwrap();
578        let Node::Gateway { branches, next, .. } = route_node else {
579            panic!("select_terms_open_route must route calculator signals");
580        };
581        assert_eq!(branches.len(), 2);
582        assert_eq!(
583            branches[0].when,
584            r#"ctx["_last_signal"] == "calculator_interacted""#
585        );
586        assert_eq!(branches[0].next.get_id(), "select_terms");
587        assert_eq!(
588            branches[1].when,
589            r#"ctx["_last_signal"] == "terms_selected""#
590        );
591        assert_eq!(branches[1].next.get_id(), "close_ticket_terms");
592        assert_eq!(next.as_ref().map(IdField::get_id), Some("finalize_reject"));
593
594        let timer_node = definition
595            .nodes
596            .iter()
597            .find(|node| node.id().get_id() == "select_terms")
598            .unwrap();
599        let Node::UserTask {
600            wait_for: Some(wait_for),
601            timeout: Some(timeout),
602            ..
603        } = timer_node
604        else {
605            panic!("select_terms must be the timed calculator task");
606        };
607        assert_eq!(wait_for.signals()[0].get_id(), "terms_selected");
608        assert_eq!(timeout.after.as_deref(), Some("PT1M"));
609    }
610
611    #[test]
612    fn validation_reports_all_broken_references() {
613        let definition: ProcessDefinition = serde_yaml::from_str(
614            r#"
615key: invalid_process
616name: Invalid process
617version: 1.0.0
618status: active
619effective_from: 2026-01-01T00:00:00Z
620signals: [known_signal]
621forms:
622  - id: known_form
623    roles: [client]
624stages: [known_stage]
625nodes:
626  - id: start
627    type: Start
628    next: missing_node
629    set_stage: missing_stage
630  - id: task
631    type: UserTask
632    form: missing_form
633    wait_for:
634      signals: [missing_signal]
635    next: also_missing
636    set_stage: null
637    timeout: null
638    on_error: null
639"#,
640        )
641        .unwrap();
642
643        let CreateProcessError::ValidationError(errors) = definition.validate().unwrap_err() else {
644            panic!("expected validation errors");
645        };
646        assert!(
647            errors
648                .iter()
649                .any(|error| error.contains("at least one End"))
650        );
651        assert!(errors.iter().any(|error| error.contains("missing_node")));
652        assert!(errors.iter().any(|error| error.contains("missing_stage")));
653        assert!(errors.iter().any(|error| error.contains("missing_form")));
654        assert!(errors.iter().any(|error| error.contains("missing_signal")));
655        assert!(errors.iter().any(|error| error.contains("also_missing")));
656    }
657}
658
659/// Lifecycle metadata serialized as `draft`, `active`, or `deprecated`.
660///
661/// Runtime starts only active versions within their effective dates. Existing
662/// instances remain bound to their original version after deprecation.
663#[derive(Debug, Clone, Serialize, Deserialize)]
664#[serde(rename_all = "lowercase")]
665pub enum ProcessStatus {
666    /// Definition marked as a draft.
667    Draft,
668    /// Definition marked as active.
669    Active,
670    /// Definition marked as deprecated.
671    Deprecated,
672}
673
674impl Display for ProcessStatus {
675    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
676        write!(f, "{:?}", self)
677    }
678}
679
680/// Optional ownership, service-level target, and version notes.
681#[derive(Debug, Clone, Default, Serialize, Deserialize)]
682pub struct ProcessMetadata {
683    /// Optional team or person responsible for the definition.
684    pub owner: Option<String>,
685    /// Descriptive ISO 8601 service-level target, such as `PT30M`; not enforced by the runtime.
686    pub sla: Option<String>,
687    /// Human-readable description of the changes introduced by this version.
688    pub comment: Option<String>,
689}
690
691/// A signal declaration serialized as a name or an object with a `name` field.
692#[derive(Debug, Clone, Serialize, Deserialize)]
693#[serde(untagged)]
694pub enum SignalDef {
695    /// Compact declaration containing only the identifier.
696    Name(IdField),
697    /// Expanded declaration with named fields.
698    Obj {
699        /// Signal identifier declared by this object.
700        name: IdField,
701    },
702}
703
704/// A host-rendered form and the roles supplied to its display hook.
705#[derive(Debug, Clone, Serialize, Deserialize)]
706pub struct FormDef {
707    /// Unique identifier within this declaration category.
708    pub id: IdField,
709    /// Role identifiers passed to the form-display hook.
710    pub roles: Vec<IdField>,
711}
712
713/// A named business stage, optionally carrying initial and final markers.
714#[derive(Clone, Debug, Serialize, Deserialize)]
715#[serde(untagged)]
716pub enum StageDef {
717    /// Expanded declaration with named fields.
718    Obj {
719        /// Unique identifier within this declaration category.
720        id: IdField,
721        /// Human-readable business-stage name.
722        name: String,
723        /// Marks the stage selected during startup; omitted means `false`.
724        #[serde(default)]
725        is_initial: Option<bool>,
726        /// Marks a business-final stage; omitted means `false`.
727        #[serde(default)]
728        is_final: Option<bool>,
729    },
730    /// Compact declaration containing only the identifier.
731    Name(IdField),
732}
733
734impl StageDef {
735    /// Returns the declared identifier.
736    pub fn id(&self) -> &IdField {
737        match self {
738            StageDef::Name(s) => s,
739            StageDef::Obj { id, .. } => id,
740        }
741    }
742
743    /// Returns the stage display name, falling back to its ID in compact declarations.
744    pub fn name(&self) -> &str {
745        match self {
746            StageDef::Name(s) => s.get_id(),
747            StageDef::Obj { name, .. } => name.as_str(),
748        }
749    }
750
751    /// Returns the initial-stage marker, defaulting to `false` for a plain stage ID.
752    pub fn is_initial(&self) -> bool {
753        match self {
754            StageDef::Obj { is_initial, .. } => is_initial.unwrap_or(false),
755            StageDef::Name(_) => false,
756        }
757    }
758}
759
760impl SignalDef {
761    /// Returns the declared signal name from either representation.
762    pub fn name(&self) -> &str {
763        match self {
764            SignalDef::Name(s) => s.get_id(),
765            SignalDef::Obj { name } => name.get_id(),
766        }
767    }
768
769    /// Returns the declared identifier.
770    pub fn id(&self) -> &IdField {
771        match self {
772            SignalDef::Name(s) => s,
773            SignalDef::Obj { name } => name,
774        }
775    }
776}
777
778/// A named string argument model; node arguments use `ContextMap` instead.
779#[derive(Debug, Clone, Serialize, Deserialize)]
780pub struct TaskArgument {
781    /// Argument identifier.
782    pub name: IdField,
783    /// String payload of the argument.
784    pub value: String,
785}
786
787/// An executable workflow node selected by the case-sensitive `type` field.
788#[derive(Debug, Clone, Serialize, Deserialize)]
789#[serde(tag = "type")]
790pub enum Node {
791    /// The unique process entry node; immediately enqueues its successor.
792    Start {
793        /// Unique identifier within this declaration category.
794        id: IdField,
795        /// Direct successor node ID.
796        next: IdField,
797        /// Optional business-stage assignment applied before this node executes.
798        set_stage: Option<SetStage>,
799    },
800
801    /// Terminal node; invokes the completion hook and enqueues no successor.
802    End {
803        /// Unique identifier within this declaration category.
804        id: IdField,
805        /// Optional business-stage assignment applied before this node executes.
806        set_stage: Option<SetStage>,
807    },
808
809    /// Invokes a registered backend handler, then applies its outcome.
810    ServiceTask {
811        /// Unique identifier within this declaration category.
812        id: IdField,
813        /// Registry key of the host handler to invoke.
814        handler: IdField,
815        /// Typed arguments passed unchanged to the registered handler.
816        #[serde(default)]
817        args: Option<ContextMap>,
818        /// Optional business-stage assignment applied before this node executes.
819        set_stage: Option<SetStage>,
820        /// Optional fixed-delay retry policy for failed service-task attempts.
821        #[serde(default)]
822        retries: Option<Retries>,
823        /// Optional successor ID or ordered conditional routes after success.
824        #[serde(default)]
825        next: Option<Next>,
826        /// Error routing metadata; only service-task `next` is currently executed.
827        #[serde(default)]
828        on_error: Option<OnError>,
829    },
830
831    /// Exposes a form through lifecycle hooks and waits for an accepted signal or timeout.
832    UserTask {
833        /// Unique identifier within this declaration category.
834        id: IdField,
835        /// Declared form identifier passed to the form lifecycle hooks.
836        form: IdField,
837        /// Signals accepted by this node; any one listed signal can complete the wait.
838        #[serde(default)]
839        wait_for: Option<WaitFor>,
840        /// Optional business-stage assignment applied before this node executes.
841        set_stage: Option<SetStage>,
842        /// Optional deadline whose event routes to `on_timeout` while this node is current.
843        #[serde(rename = "timeout")]
844        #[serde(default)]
845        timeout: Option<NodeTimeout>,
846
847        /// Successor selected after an accepted signal updates the context.
848        #[serde(default)]
849        next: Option<Next>,
850
851        /// Reserved error routing metadata; parsed and validated but not executed.
852        #[serde(default)]
853        on_error: Option<OnError>,
854    },
855
856    /// Technical wait state. Unlike `UserTask`, it does not expose a form and
857    /// does not invoke user-interface lifecycle handlers.
858    Wait {
859        /// Unique identifier within this declaration category.
860        id: IdField,
861        /// Signal names accepted by this wait; any one completes it.
862        wait_for: WaitFor,
863        /// Optional node deadline and the target to enqueue on expiration.
864        #[serde(default)]
865        timeout: Option<NodeTimeout>,
866        /// Optional direct successor or XOR routes after an accepted signal.
867        #[serde(default)]
868        next: Option<Next>,
869        /// Optional business-stage assignment applied before this node executes.
870        set_stage: Option<SetStage>,
871    },
872
873    /// Selects one successor according to the configured gateway rule.
874    Gateway {
875        /// Unique identifier within this declaration category.
876        id: IdField,
877        /// Optional business-stage assignment applied before this node executes.
878        set_stage: Option<SetStage>,
879        /// Branch selection rule; retain explicit `gateway: XOR` in definitions.
880        gateway: GatewayKind,
881        /// Conditions evaluated in declaration order.
882        #[serde(default)]
883        branches: Vec<Branch>,
884        /// Fallback target when no branch matches the gateway rule.
885        #[serde(default)]
886        next: Option<IdField>,
887    },
888}
889
890impl Node {
891    /// Returns the declared identifier.
892    pub fn id(&self) -> &IdField {
893        match self {
894            Node::Start { id, .. } => id,
895            Node::End { id, .. } => id,
896            Node::ServiceTask { id, .. } => id,
897            Node::UserTask { id, .. } => id,
898            Node::Wait { id, .. } => id,
899            Node::Gateway { id, .. } => id,
900        }
901    }
902    /// Returns whether this is the process entry node.
903    pub fn is_start(&self) -> bool {
904        matches!(self, Node::Start { .. })
905    }
906    /// Returns whether this is a terminal node.
907    pub fn is_end(&self) -> bool {
908        matches!(self, Node::End { .. })
909    }
910    /// Returns whether this node invokes a backend handler.
911    pub fn is_service_task(&self) -> bool {
912        matches!(self, Node::ServiceTask { .. })
913    }
914    /// Returns whether this node exposes a form.
915    pub fn is_user_task(&self) -> bool {
916        matches!(self, Node::UserTask { .. })
917    }
918    /// Returns the optional stage assignment applied on node entry.
919    pub fn set_stage(&self) -> Option<&SetStage> {
920        match self {
921            Node::Start { set_stage, .. } => Option::from(set_stage),
922            Node::End { set_stage, .. } => Option::from(set_stage),
923            Node::ServiceTask { set_stage, .. } => Option::from(set_stage),
924            Node::UserTask { set_stage, .. } => Option::from(set_stage),
925            Node::Wait { set_stage, .. } => Option::from(set_stage),
926            Node::Gateway { set_stage, .. } => Option::from(set_stage),
927        }
928    }
929}
930
931/// A stage assignment serialized as an ID or `{ stage, reason }`.
932#[derive(Debug, Clone, Serialize, Deserialize)]
933#[serde(untagged)]
934pub enum SetStage {
935    /// Assigns a stage without a reason.
936    Stage(IdField),
937    /// Assigns a stage with a reason for the lifecycle hook.
938    StageWithReason(SetStageWithReason),
939}
940
941impl SetStage {
942    /// Normalizes either stage representation into an ID and optional reason.
943    pub fn stage_with_reason(&self) -> SetStageWithReason {
944        match self {
945            SetStage::Stage(s) => SetStageWithReason {
946                stage: s.clone(),
947                reason: None,
948            },
949            SetStage::StageWithReason(s) => SetStageWithReason {
950                stage: s.stage.clone(),
951                reason: s.reason.clone(),
952            },
953        }
954    }
955}
956
957/// Stage assignment passed to the stage-change lifecycle handler.
958///
959/// Queued execution commits the stage and reason atomically with the transition.
960/// The low-level `assign_stage` helper assigns a stage without a reason.
961#[derive(Debug, Clone, Serialize, Deserialize)]
962pub struct SetStageWithReason {
963    /// Declared business-stage identifier.
964    pub stage: IdField,
965    /// Optional explanation associated with this stage assignment.
966    pub reason: Option<String>,
967}
968
969/// Branch selection rule for an exclusive gateway.
970///
971/// `XOR` selects the first true condition. The explicit `gateway` field and its
972/// serialized value remain unchanged for existing process definitions.
973///
974/// # Examples
975///
976/// ```
977/// use fluxpro_engine::models::process_def::{GatewayKind, Node};
978///
979/// let node: Node = serde_json::from_value(serde_json::json!({
980///     "id": "decision", "type": "Gateway", "gateway": "XOR",
981///     "branches": [{ "when": "ctx.approved", "next": "accepted" }],
982///     "next": "rejected"
983/// })).unwrap();
984/// assert!(matches!(node, Node::Gateway { gateway: GatewayKind::XOR, .. }));
985/// ```
986#[derive(Debug, Clone, Serialize, Deserialize)]
987#[serde(rename_all = "UPPERCASE")]
988pub enum GatewayKind {
989    /// Selects the first branch evaluating to true, then the fallback.
990    XOR,
991}
992
993/// A condition and the target selected when it matches the gateway rule.
994#[derive(Debug, Clone, Serialize, Deserialize)]
995pub struct Branch {
996    /// Rhai boolean expression evaluated with typed context values exposed as `ctx`.
997    pub when: String,
998    /// Node ID selected when this branch matches the gateway rule.
999    pub next: IdField,
1000}
1001
1002/// Fixed-delay retry policy for failed service-task queue attempts.
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1004pub struct Retries {
1005    /// Maximum retries after the initial attempt; must be greater than zero.
1006    pub max: u32,
1007    /// Fixed ISO 8601 delay between failed attempts, such as `PT10S`.
1008    pub backoff: String,
1009}
1010
1011impl Retries {
1012    /// Returns the current UTC time plus the configured fixed backoff.
1013    ///
1014    /// # Errors
1015    ///
1016    /// Returns an error if the duration cannot be parsed or represented by Chrono.
1017    pub fn next_attempt_at(&self) -> anyhow::Result<DateTime<Utc>> {
1018        relative_deadline(&self.backoff)
1019    }
1020}
1021
1022/// A successor for service tasks and signal waits: an ID or conditional routes.
1023#[derive(Debug, Clone, Serialize, Deserialize)]
1024#[serde(untagged)]
1025pub enum Next {
1026    /// Routes directly to the specified node.
1027    To(IdField),
1028    /// Selects the first true branch, then falls back to the default target.
1029    Routes(NextRoutes),
1030}
1031
1032/// Ordered XOR branches with an optional fallback target.
1033#[derive(Debug, Clone, Serialize, Deserialize)]
1034pub struct NextRoutes {
1035    /// Fallback node when no conditional branch is selected.
1036    #[serde(default)]
1037    pub default: Option<IdField>,
1038    /// Conditions evaluated in declaration order.
1039    #[serde(default)]
1040    pub branches: Vec<Branch>,
1041}
1042
1043/// A wait condition accepting any one declared signal.
1044#[derive(Debug, Clone, Serialize, Deserialize)]
1045#[serde(untagged)]
1046pub enum WaitFor {
1047    /// Accepts the single named signal.
1048    Single {
1049        /// Signal name accepted by a waiting node.
1050        signal: IdField,
1051    },
1052    /// Accepts any one signal in the list; does not wait for all signals.
1053    Multi {
1054        /// Accepted signal names; the first matching delivery completes the wait.
1055        signals: Vec<IdField>,
1056    },
1057}
1058
1059impl WaitFor {
1060    /// Returns all accepted signal IDs; any one can complete the wait.
1061    pub fn signals(&self) -> Vec<IdField> {
1062        match self {
1063            WaitFor::Single { signal } => {
1064                vec![signal.clone()]
1065            }
1066            WaitFor::Multi { signals } => signals.clone(),
1067        }
1068    }
1069}
1070
1071/// A deadline for a user task or technical wait.
1072///
1073/// An absolute `at` takes precedence over `after`. The event only routes onward
1074/// if its originating node is still current. Cron schedules are not supported.
1075#[derive(Debug, Clone, Serialize, Deserialize)]
1076pub struct NodeTimeout {
1077    /// Relative ISO 8601 delay from node entry, such as `PT15M`.
1078    #[serde(default)]
1079    pub after: Option<String>,
1080    /// Absolute UTC deadline, taking precedence over `after` when both are supplied.
1081    #[serde(default)]
1082    pub at: Option<DateTime<Utc>>,
1083    /// Node ID to enqueue when the deadline fires; this is not a signal name.
1084    pub on_timeout: IdField,
1085}
1086
1087impl NodeTimeout {
1088    /// Resolves the deadline, preferring `at` over a delay measured from now.
1089    ///
1090    /// # Errors
1091    ///
1092    /// Returns an error if neither a timestamp nor a parseable duration is present.
1093    pub fn after_now(&self) -> anyhow::Result<DateTime<Utc>> {
1094        if let Some(at) = self.at {
1095            return Ok(at);
1096        };
1097        if let Some(after) = &self.after {
1098            return relative_deadline(after);
1099        }
1100
1101        Err(Error::msg("Couldn't parse after"))
1102    }
1103}
1104
1105// The ISO parser accepts valid prefixes, so require a complete duration first.
1106fn relative_deadline(text: &str) -> anyhow::Result<DateTime<Utc>> {
1107    let syntax = regex::Regex::new(r"^P(?:[0-9]+W|(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:[.,][0-9]{1,3})?S)?)?)$").expect("duration regex");
1108    if !syntax.is_match(text) {
1109        return Err(Error::msg("invalid ISO 8601 duration"));
1110    }
1111    let parsed = text
1112        .parse::<iso8601::Duration>()
1113        .map_err(|e| Error::msg(e))?;
1114    let delay = Duration::from_std(std::time::Duration::from(parsed))?;
1115    if delay <= Duration::zero() {
1116        return Err(Error::msg("duration must be positive"));
1117    }
1118    Utc::now()
1119        .checked_add_signed(delay)
1120        .ok_or_else(|| Error::msg("duration is out of range"))
1121}
1122
1123/// Error routing metadata; only `ServiceTask.on_error.next` is executed.
1124#[derive(Debug, Clone, Serialize, Deserialize)]
1125pub struct OnError {
1126    /// Target after service-task retries are exhausted; unused for user tasks.
1127    #[serde(default)]
1128    pub next: Option<IdField>,
1129    /// Reserved compensation target; validated as a node reference but not executed.
1130    #[serde(default)]
1131    pub compensate: Option<IdField>,
1132}
1133
1134/// Lifecycle handler reference serialized as an ID or `{ handler }`.
1135#[derive(Debug, Clone, Serialize, Deserialize)]
1136#[serde(untagged)]
1137pub enum TaskHandler {
1138    /// Handler reference containing only its registry ID.
1139    Simple(IdField),
1140    /// Handler reference using the object representation.
1141    Extended(TaskHandlerDescription),
1142}
1143
1144impl TaskHandler {
1145    /// Returns the handler ID from either reference representation.
1146    pub fn handler(&self) -> IdField {
1147        match self {
1148            TaskHandler::Simple(h) => h.clone(),
1149            TaskHandler::Extended(h) => h.handler.clone(),
1150        }
1151    }
1152}
1153
1154/// Object form of a lifecycle handler reference.
1155#[derive(Debug, Clone, Serialize, Deserialize)]
1156pub struct TaskHandlerDescription {
1157    /// Registry key of the host handler to invoke.
1158    pub handler: IdField,
1159}
1160
1161/// Optional host callbacks for form, stage, and completion events.
1162///
1163/// Callbacks must be registered like service handlers. Their errors propagate,
1164/// and queued hooks require a successful status; their context patches are ignored.
1165/// During queued execution callbacks run before the database transition commits;
1166/// they may repeat after a failed attempt and must tolerate duplicate calls.
1167#[derive(Debug, Clone, Serialize, Deserialize)]
1168pub struct SpecialHandlers {
1169    /// Called with the proposed typed `stage` object before the queued transition commits.
1170    pub on_stage_change: Option<TaskHandler>,
1171    /// Called on user-task entry with `form_id` and `roles` arguments.
1172    pub on_show_form: Option<TaskHandler>,
1173    /// Called before entering the next queued node when the current node is a user task.
1174    pub on_hide_form: Option<TaskHandler>,
1175    /// Called on End entry with an `end_node_id` string argument.
1176    pub on_process_complete: Option<TaskHandler>,
1177}