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
354                    .emit_signal
355                    .as_ref()
356                    .filter(|signal| !signals.contains(signal.get_id()))
357                {
358                    errors.push(format!(
359                        "escalation '{}' action '{}' emits undeclared signal '{}'",
360                        escalation.topic, action.id, signal
361                    ));
362                }
363            }
364        }
365
366        if errors.is_empty() {
367            Ok(())
368        } else {
369            Err(CreateProcessError::ValidationError(errors))
370        }
371    }
372
373    /// Lists nodes with no structural path from Start, in definition order.
374    ///
375    /// This is diagnostic rather than a registration error because hosts may
376    /// explicitly enqueue auxiliary nodes. Conditions are not evaluated.
377    pub fn unreachable_nodes(&self) -> Vec<IdField> {
378        let mut reached = HashSet::new();
379        let mut pending: Vec<&Node> = self.nodes.iter().filter(|node| node.is_start()).collect();
380        while let Some(node) = pending.pop() {
381            if !reached.insert(node.id()) {
382                continue;
383            }
384            for target in node_targets(node) {
385                if let Some(next) = self.nodes.iter().find(|node| node.id() == target) {
386                    pending.push(next);
387                }
388            }
389        }
390        self.nodes
391            .iter()
392            .filter(|node| !reached.contains(node.id()))
393            .map(|node| node.id().clone())
394            .collect()
395    }
396}
397
398fn node_branches(node: &Node) -> &[Branch] {
399    match node {
400        Node::Gateway { branches, .. } => branches,
401        Node::ServiceTask {
402            next: Some(Next::Routes(routes)),
403            ..
404        }
405        | Node::UserTask {
406            next: Some(Next::Routes(routes)),
407            ..
408        }
409        | Node::Wait {
410            next: Some(Next::Routes(routes)),
411            ..
412        } => &routes.branches,
413        _ => &[],
414    }
415}
416
417fn node_targets(node: &Node) -> Vec<&IdField> {
418    let mut targets: Vec<&IdField> = node_branches(node).iter().map(|b| &b.next).collect();
419    match node {
420        Node::Start { next, .. } => targets.push(next),
421        Node::Gateway { next, .. } => targets.extend(next),
422        Node::ServiceTask { next, .. } | Node::Wait { next, .. } | Node::UserTask { next, .. } => {
423            match next {
424                Some(Next::To(target)) => targets.push(target),
425                Some(Next::Routes(routes)) => targets.extend(&routes.default),
426                None => {}
427            }
428        }
429        Node::End { .. } => {}
430    }
431    match node {
432        Node::Wait {
433            timeout: Some(timer),
434            ..
435        }
436        | Node::UserTask {
437            timeout: Some(timer),
438            ..
439        } => targets.push(&timer.on_timeout),
440        _ => {}
441    }
442    if let Node::ServiceTask {
443        on_error: Some(error),
444        ..
445    } = node
446    {
447        targets.extend(&error.next);
448    }
449    targets
450}
451
452fn collect_unique_ids<'a>(
453    kind: &str,
454    values: impl Iterator<Item = &'a str>,
455    errors: &mut Vec<String>,
456) -> HashSet<&'a str> {
457    let mut result = HashSet::new();
458    for value in values {
459        if !result.insert(value) {
460            errors.push(format!("duplicate {kind} id '{value}'"));
461        }
462    }
463    result
464}
465
466fn check_on_error(
467    source: &str,
468    on_error: Option<&OnError>,
469    check_node: &impl Fn(&str, &str, &IdField, &mut Vec<String>),
470    errors: &mut Vec<String>,
471) {
472    if let Some(on_error) = on_error {
473        if let Some(next) = &on_error.next {
474            check_node(source, "on_error.next", next, errors);
475        }
476        if let Some(compensate) = &on_error.compensate {
477            check_node(source, "on_error.compensate", compensate, errors);
478        }
479    }
480}
481
482#[cfg(all(test, feature = "api"))]
483mod validation_tests {
484    use super::*;
485
486    const TK_ONLINE_DEFINITION: &str = include_str!("../../tests/fixtures/tk_online.yaml");
487    const CASH_LOAN_DEFINITION: &str = include_str!("../../tests/fixtures/cash_loan.yaml");
488
489    #[test]
490    fn a_process_definition_is_valid() {
491        let definition: ProcessDefinition = serde_yaml::from_str(TK_ONLINE_DEFINITION).unwrap();
492
493        definition.validate().unwrap();
494    }
495
496    #[test]
497    fn a_user_task_can_start_a_timeout_after_a_previous_signal() {
498        let definition: ProcessDefinition = serde_yaml::from_str(TK_ONLINE_DEFINITION).unwrap();
499
500        let open_node = definition
501            .nodes
502            .iter()
503            .find(|node| node.id().get_id() == "credit_info_open")
504            .unwrap();
505        let Node::UserTask {
506            wait_for: Some(wait_for),
507            timeout: None,
508            next: Some(Next::To(next)),
509            ..
510        } = open_node
511        else {
512            panic!("credit_info_open must wait for page opening without a timeout");
513        };
514        assert_eq!(wait_for.signals()[0].get_id(), "credit_info_opened");
515        assert_eq!(next.get_id(), "credit_info");
516
517        let timer_node = definition
518            .nodes
519            .iter()
520            .find(|node| node.id().get_id() == "credit_info")
521            .unwrap();
522        let Node::UserTask {
523            wait_for: Some(wait_for),
524            timeout: Some(timeout),
525            ..
526        } = timer_node
527        else {
528            panic!("credit_info must be the timed credit-info task");
529        };
530        assert_eq!(wait_for.signals()[0].get_id(), "terms_viewed");
531        assert_eq!(timeout.after.as_deref(), Some("PT3M"));
532    }
533
534    #[test]
535    fn a_wait_node_is_valid() {
536        let definition: ProcessDefinition = serde_yaml::from_str(CASH_LOAN_DEFINITION).unwrap();
537
538        definition.validate().unwrap();
539        let wait = definition
540            .nodes
541            .iter()
542            .find(|node| node.id().get_id() == "final_terms_after_reminder")
543            .unwrap();
544        assert!(matches!(wait, Node::Wait { .. }));
545    }
546
547    #[test]
548    fn a_user_task_can_route_on_multiple_signals_before_a_timeout() {
549        let definition: ProcessDefinition = serde_yaml::from_str(CASH_LOAN_DEFINITION).unwrap();
550
551        let open_node = definition
552            .nodes
553            .iter()
554            .find(|node| node.id().get_id() == "select_terms_open")
555            .unwrap();
556        let Node::UserTask {
557            wait_for: Some(wait_for),
558            timeout: None,
559            next: Some(Next::To(next)),
560            ..
561        } = open_node
562        else {
563            panic!("select_terms_open must wait for calculator signals without a timeout");
564        };
565        assert_eq!(
566            wait_for
567                .signals()
568                .iter()
569                .map(|signal| signal.get_id())
570                .collect::<Vec<_>>(),
571            vec!["calculator_interacted", "terms_selected"]
572        );
573        assert_eq!(next.get_id(), "select_terms_open_route");
574
575        let route_node = definition
576            .nodes
577            .iter()
578            .find(|node| node.id().get_id() == "select_terms_open_route")
579            .unwrap();
580        let Node::Gateway { branches, next, .. } = route_node else {
581            panic!("select_terms_open_route must route calculator signals");
582        };
583        assert_eq!(branches.len(), 2);
584        assert_eq!(
585            branches[0].when,
586            r#"ctx["_last_signal"] == "calculator_interacted""#
587        );
588        assert_eq!(branches[0].next.get_id(), "select_terms");
589        assert_eq!(
590            branches[1].when,
591            r#"ctx["_last_signal"] == "terms_selected""#
592        );
593        assert_eq!(branches[1].next.get_id(), "close_ticket_terms");
594        assert_eq!(next.as_ref().map(IdField::get_id), Some("finalize_reject"));
595
596        let timer_node = definition
597            .nodes
598            .iter()
599            .find(|node| node.id().get_id() == "select_terms")
600            .unwrap();
601        let Node::UserTask {
602            wait_for: Some(wait_for),
603            timeout: Some(timeout),
604            ..
605        } = timer_node
606        else {
607            panic!("select_terms must be the timed calculator task");
608        };
609        assert_eq!(wait_for.signals()[0].get_id(), "terms_selected");
610        assert_eq!(timeout.after.as_deref(), Some("PT1M"));
611    }
612
613    #[test]
614    fn validation_reports_all_broken_references() {
615        let definition: ProcessDefinition = serde_yaml::from_str(
616            r#"
617key: invalid_process
618name: Invalid process
619version: 1.0.0
620status: active
621effective_from: 2026-01-01T00:00:00Z
622signals: [known_signal]
623forms:
624  - id: known_form
625    roles: [client]
626stages: [known_stage]
627nodes:
628  - id: start
629    type: Start
630    next: missing_node
631    set_stage: missing_stage
632  - id: task
633    type: UserTask
634    form: missing_form
635    wait_for:
636      signals: [missing_signal]
637    next: also_missing
638    set_stage: null
639    timeout: null
640    on_error: null
641"#,
642        )
643        .unwrap();
644
645        let CreateProcessError::ValidationError(errors) = definition.validate().unwrap_err() else {
646            panic!("expected validation errors");
647        };
648        assert!(
649            errors
650                .iter()
651                .any(|error| error.contains("at least one End"))
652        );
653        assert!(errors.iter().any(|error| error.contains("missing_node")));
654        assert!(errors.iter().any(|error| error.contains("missing_stage")));
655        assert!(errors.iter().any(|error| error.contains("missing_form")));
656        assert!(errors.iter().any(|error| error.contains("missing_signal")));
657        assert!(errors.iter().any(|error| error.contains("also_missing")));
658    }
659}
660
661/// Lifecycle metadata serialized as `draft`, `active`, or `deprecated`.
662///
663/// Runtime starts only active versions within their effective dates. Existing
664/// instances remain bound to their original version after deprecation.
665#[derive(Debug, Clone, Serialize, Deserialize)]
666#[serde(rename_all = "lowercase")]
667pub enum ProcessStatus {
668    /// Definition marked as a draft.
669    Draft,
670    /// Definition marked as active.
671    Active,
672    /// Definition marked as deprecated.
673    Deprecated,
674}
675
676impl Display for ProcessStatus {
677    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
678        write!(f, "{:?}", self)
679    }
680}
681
682/// Optional ownership, service-level target, and version notes.
683#[derive(Debug, Clone, Default, Serialize, Deserialize)]
684pub struct ProcessMetadata {
685    /// Optional team or person responsible for the definition.
686    pub owner: Option<String>,
687    /// Descriptive ISO 8601 service-level target, such as `PT30M`; not enforced by the runtime.
688    pub sla: Option<String>,
689    /// Human-readable description of the changes introduced by this version.
690    pub comment: Option<String>,
691}
692
693/// A signal declaration serialized as a name or an object with a `name` field.
694#[derive(Debug, Clone, Serialize, Deserialize)]
695#[serde(untagged)]
696pub enum SignalDef {
697    /// Compact declaration containing only the identifier.
698    Name(IdField),
699    /// Expanded declaration with named fields.
700    Obj {
701        /// Signal identifier declared by this object.
702        name: IdField,
703    },
704}
705
706/// A host-rendered form and the roles supplied to its display hook.
707#[derive(Debug, Clone, Serialize, Deserialize)]
708pub struct FormDef {
709    /// Unique identifier within this declaration category.
710    pub id: IdField,
711    /// Role identifiers passed to the form-display hook.
712    pub roles: Vec<IdField>,
713}
714
715/// A named business stage, optionally carrying initial and final markers.
716#[derive(Clone, Debug, Serialize, Deserialize)]
717#[serde(untagged)]
718pub enum StageDef {
719    /// Expanded declaration with named fields.
720    Obj {
721        /// Unique identifier within this declaration category.
722        id: IdField,
723        /// Human-readable business-stage name.
724        name: String,
725        /// Marks the stage selected during startup; omitted means `false`.
726        #[serde(default)]
727        is_initial: Option<bool>,
728        /// Marks a business-final stage; omitted means `false`.
729        #[serde(default)]
730        is_final: Option<bool>,
731    },
732    /// Compact declaration containing only the identifier.
733    Name(IdField),
734}
735
736impl StageDef {
737    /// Returns the declared identifier.
738    pub fn id(&self) -> &IdField {
739        match self {
740            StageDef::Name(s) => s,
741            StageDef::Obj { id, .. } => id,
742        }
743    }
744
745    /// Returns the stage display name, falling back to its ID in compact declarations.
746    pub fn name(&self) -> &str {
747        match self {
748            StageDef::Name(s) => s.get_id(),
749            StageDef::Obj { name, .. } => name.as_str(),
750        }
751    }
752
753    /// Returns the initial-stage marker, defaulting to `false` for a plain stage ID.
754    pub fn is_initial(&self) -> bool {
755        match self {
756            StageDef::Obj { is_initial, .. } => is_initial.unwrap_or(false),
757            StageDef::Name(_) => false,
758        }
759    }
760}
761
762impl SignalDef {
763    /// Returns the declared signal name from either representation.
764    pub fn name(&self) -> &str {
765        match self {
766            SignalDef::Name(s) => s.get_id(),
767            SignalDef::Obj { name } => name.get_id(),
768        }
769    }
770
771    /// Returns the declared identifier.
772    pub fn id(&self) -> &IdField {
773        match self {
774            SignalDef::Name(s) => s,
775            SignalDef::Obj { name } => name,
776        }
777    }
778}
779
780/// A named string argument model; node arguments use `ContextMap` instead.
781#[derive(Debug, Clone, Serialize, Deserialize)]
782pub struct TaskArgument {
783    /// Argument identifier.
784    pub name: IdField,
785    /// String payload of the argument.
786    pub value: String,
787}
788
789/// An executable workflow node selected by the case-sensitive `type` field.
790#[derive(Debug, Clone, Serialize, Deserialize)]
791#[serde(tag = "type")]
792pub enum Node {
793    /// The unique process entry node; immediately enqueues its successor.
794    Start {
795        /// Unique identifier within this declaration category.
796        id: IdField,
797        /// Direct successor node ID.
798        next: IdField,
799        /// Optional business-stage assignment applied before this node executes.
800        set_stage: Option<SetStage>,
801    },
802
803    /// Terminal node; invokes the completion hook and enqueues no successor.
804    End {
805        /// Unique identifier within this declaration category.
806        id: IdField,
807        /// Optional business-stage assignment applied before this node executes.
808        set_stage: Option<SetStage>,
809    },
810
811    /// Invokes a registered backend handler, then applies its outcome.
812    ServiceTask {
813        /// Unique identifier within this declaration category.
814        id: IdField,
815        /// Registry key of the host handler to invoke.
816        handler: IdField,
817        /// Typed arguments passed unchanged to the registered handler.
818        #[serde(default)]
819        args: Option<ContextMap>,
820        /// Optional business-stage assignment applied before this node executes.
821        set_stage: Option<SetStage>,
822        /// Optional fixed-delay retry policy for failed service-task attempts.
823        #[serde(default)]
824        retries: Option<Retries>,
825        /// Optional successor ID or ordered conditional routes after success.
826        #[serde(default)]
827        next: Option<Next>,
828        /// Error routing metadata; only service-task `next` is currently executed.
829        #[serde(default)]
830        on_error: Option<OnError>,
831    },
832
833    /// Exposes a form through lifecycle hooks and waits for an accepted signal or timeout.
834    UserTask {
835        /// Unique identifier within this declaration category.
836        id: IdField,
837        /// Declared form identifier passed to the form lifecycle hooks.
838        form: IdField,
839        /// Signals accepted by this node; any one listed signal can complete the wait.
840        #[serde(default)]
841        wait_for: Option<WaitFor>,
842        /// Optional business-stage assignment applied before this node executes.
843        set_stage: Option<SetStage>,
844        /// Optional deadline whose event routes to `on_timeout` while this node is current.
845        #[serde(rename = "timeout")]
846        #[serde(default)]
847        timeout: Option<NodeTimeout>,
848
849        /// Successor selected after an accepted signal updates the context.
850        #[serde(default)]
851        next: Option<Next>,
852
853        /// Reserved error routing metadata; parsed and validated but not executed.
854        #[serde(default)]
855        on_error: Option<OnError>,
856    },
857
858    /// Technical wait state. Unlike `UserTask`, it does not expose a form and
859    /// does not invoke user-interface lifecycle handlers.
860    Wait {
861        /// Unique identifier within this declaration category.
862        id: IdField,
863        /// Signal names accepted by this wait; any one completes it.
864        wait_for: WaitFor,
865        /// Optional node deadline and the target to enqueue on expiration.
866        #[serde(default)]
867        timeout: Option<NodeTimeout>,
868        /// Optional direct successor or XOR routes after an accepted signal.
869        #[serde(default)]
870        next: Option<Next>,
871        /// Optional business-stage assignment applied before this node executes.
872        set_stage: Option<SetStage>,
873    },
874
875    /// Selects one successor according to the configured gateway rule.
876    Gateway {
877        /// Unique identifier within this declaration category.
878        id: IdField,
879        /// Optional business-stage assignment applied before this node executes.
880        set_stage: Option<SetStage>,
881        /// Branch selection rule; retain explicit `gateway: XOR` in definitions.
882        gateway: GatewayKind,
883        /// Conditions evaluated in declaration order.
884        #[serde(default)]
885        branches: Vec<Branch>,
886        /// Fallback target when no branch matches the gateway rule.
887        #[serde(default)]
888        next: Option<IdField>,
889    },
890}
891
892impl Node {
893    /// Returns the declared identifier.
894    pub fn id(&self) -> &IdField {
895        match self {
896            Node::Start { id, .. } => id,
897            Node::End { id, .. } => id,
898            Node::ServiceTask { id, .. } => id,
899            Node::UserTask { id, .. } => id,
900            Node::Wait { id, .. } => id,
901            Node::Gateway { id, .. } => id,
902        }
903    }
904    /// Returns whether this is the process entry node.
905    pub fn is_start(&self) -> bool {
906        matches!(self, Node::Start { .. })
907    }
908    /// Returns whether this is a terminal node.
909    pub fn is_end(&self) -> bool {
910        matches!(self, Node::End { .. })
911    }
912    /// Returns whether this node invokes a backend handler.
913    pub fn is_service_task(&self) -> bool {
914        matches!(self, Node::ServiceTask { .. })
915    }
916    /// Returns whether this node exposes a form.
917    pub fn is_user_task(&self) -> bool {
918        matches!(self, Node::UserTask { .. })
919    }
920    /// Returns the deadline configured for a waiting node, if any.
921    pub fn timeout(&self) -> Option<&NodeTimeout> {
922        match self {
923            Node::UserTask { timeout, .. } | Node::Wait { timeout, .. } => timeout.as_ref(),
924            _ => None,
925        }
926    }
927    /// Returns the optional stage assignment applied on node entry.
928    pub fn set_stage(&self) -> Option<&SetStage> {
929        match self {
930            Node::Start { set_stage, .. } => Option::from(set_stage),
931            Node::End { set_stage, .. } => Option::from(set_stage),
932            Node::ServiceTask { set_stage, .. } => Option::from(set_stage),
933            Node::UserTask { set_stage, .. } => Option::from(set_stage),
934            Node::Wait { set_stage, .. } => Option::from(set_stage),
935            Node::Gateway { set_stage, .. } => Option::from(set_stage),
936        }
937    }
938}
939
940/// A stage assignment serialized as an ID or `{ stage, reason }`.
941#[derive(Debug, Clone, Serialize, Deserialize)]
942#[serde(untagged)]
943pub enum SetStage {
944    /// Assigns a stage without a reason.
945    Stage(IdField),
946    /// Assigns a stage with a reason for the lifecycle hook.
947    StageWithReason(SetStageWithReason),
948}
949
950impl SetStage {
951    /// Normalizes either stage representation into an ID and optional reason.
952    pub fn stage_with_reason(&self) -> SetStageWithReason {
953        match self {
954            SetStage::Stage(s) => SetStageWithReason {
955                stage: s.clone(),
956                reason: None,
957            },
958            SetStage::StageWithReason(s) => SetStageWithReason {
959                stage: s.stage.clone(),
960                reason: s.reason.clone(),
961            },
962        }
963    }
964}
965
966/// Stage assignment passed to the stage-change lifecycle handler.
967///
968/// Queued execution commits the stage and reason atomically with the transition.
969/// The low-level `assign_stage` helper assigns a stage without a reason.
970#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct SetStageWithReason {
972    /// Declared business-stage identifier.
973    pub stage: IdField,
974    /// Optional explanation associated with this stage assignment.
975    pub reason: Option<String>,
976}
977
978/// Branch selection rule for an exclusive gateway.
979///
980/// `XOR` selects the first true condition. The explicit `gateway` field and its
981/// serialized value remain unchanged for existing process definitions.
982///
983/// # Examples
984///
985/// ```
986/// use fluxpro_engine::models::process_def::{GatewayKind, Node};
987///
988/// let node: Node = serde_json::from_value(serde_json::json!({
989///     "id": "decision", "type": "Gateway", "gateway": "XOR",
990///     "branches": [{ "when": "ctx.approved", "next": "accepted" }],
991///     "next": "rejected"
992/// })).unwrap();
993/// assert!(matches!(node, Node::Gateway { gateway: GatewayKind::XOR, .. }));
994/// ```
995#[derive(Debug, Clone, Serialize, Deserialize)]
996#[serde(rename_all = "UPPERCASE")]
997pub enum GatewayKind {
998    /// Selects the first branch evaluating to true, then the fallback.
999    XOR,
1000}
1001
1002/// A condition and the target selected when it matches the gateway rule.
1003#[derive(Debug, Clone, Serialize, Deserialize)]
1004pub struct Branch {
1005    /// Rhai boolean expression evaluated with typed context values exposed as `ctx`.
1006    pub when: String,
1007    /// Node ID selected when this branch matches the gateway rule.
1008    pub next: IdField,
1009}
1010
1011/// Fixed-delay retry policy for failed service-task queue attempts.
1012#[derive(Debug, Clone, Serialize, Deserialize)]
1013pub struct Retries {
1014    /// Maximum retries after the initial attempt; must be greater than zero.
1015    pub max: u32,
1016    /// Fixed ISO 8601 delay between failed attempts, such as `PT10S`.
1017    pub backoff: String,
1018}
1019
1020impl Retries {
1021    /// Returns the current UTC time plus the configured fixed backoff.
1022    ///
1023    /// # Errors
1024    ///
1025    /// Returns an error if the duration cannot be parsed or represented by Chrono.
1026    pub fn next_attempt_at(&self) -> anyhow::Result<DateTime<Utc>> {
1027        relative_deadline(&self.backoff)
1028    }
1029}
1030
1031/// A successor for service tasks and signal waits: an ID or conditional routes.
1032#[derive(Debug, Clone, Serialize, Deserialize)]
1033#[serde(untagged)]
1034pub enum Next {
1035    /// Routes directly to the specified node.
1036    To(IdField),
1037    /// Selects the first true branch, then falls back to the default target.
1038    Routes(NextRoutes),
1039}
1040
1041/// Ordered XOR branches with an optional fallback target.
1042#[derive(Debug, Clone, Serialize, Deserialize)]
1043pub struct NextRoutes {
1044    /// Fallback node when no conditional branch is selected.
1045    #[serde(default)]
1046    pub default: Option<IdField>,
1047    /// Conditions evaluated in declaration order.
1048    #[serde(default)]
1049    pub branches: Vec<Branch>,
1050}
1051
1052/// A wait condition accepting any one declared signal.
1053#[derive(Debug, Clone, Serialize, Deserialize)]
1054#[serde(untagged)]
1055pub enum WaitFor {
1056    /// Accepts the single named signal.
1057    Single {
1058        /// Signal name accepted by a waiting node.
1059        signal: IdField,
1060    },
1061    /// Accepts any one signal in the list; does not wait for all signals.
1062    Multi {
1063        /// Accepted signal names; the first matching delivery completes the wait.
1064        signals: Vec<IdField>,
1065    },
1066}
1067
1068impl WaitFor {
1069    /// Returns all accepted signal IDs; any one can complete the wait.
1070    pub fn signals(&self) -> Vec<IdField> {
1071        match self {
1072            WaitFor::Single { signal } => {
1073                vec![signal.clone()]
1074            }
1075            WaitFor::Multi { signals } => signals.clone(),
1076        }
1077    }
1078}
1079
1080/// A deadline for a user task or technical wait.
1081///
1082/// An absolute `at` takes precedence over `after`. The event only routes onward
1083/// if its originating node is still current. Cron schedules are not supported.
1084#[derive(Debug, Clone, Serialize, Deserialize)]
1085pub struct NodeTimeout {
1086    /// Relative ISO 8601 delay from node entry, such as `PT15M`.
1087    #[serde(default)]
1088    pub after: Option<String>,
1089    /// Absolute UTC deadline, taking precedence over `after` when both are supplied.
1090    #[serde(default)]
1091    pub at: Option<DateTime<Utc>>,
1092    /// Node ID to enqueue when the deadline fires; this is not a signal name.
1093    pub on_timeout: IdField,
1094    /// Typed values merged into process context when this deadline is accepted.
1095    ///
1096    /// This is useful for durable business facts such as a terminal reason. It
1097    /// is not applied when the timer is stale because the wait already ended.
1098    #[serde(default, skip_serializing_if = "ContextMap::is_empty")]
1099    pub context: ContextMap,
1100}
1101
1102impl NodeTimeout {
1103    /// Resolves the deadline, preferring `at` over a delay measured from now.
1104    ///
1105    /// # Errors
1106    ///
1107    /// Returns an error if neither a timestamp nor a parseable duration is present.
1108    pub fn after_now(&self) -> anyhow::Result<DateTime<Utc>> {
1109        if let Some(at) = self.at {
1110            return Ok(at);
1111        };
1112        if let Some(after) = &self.after {
1113            return relative_deadline(after);
1114        }
1115
1116        Err(Error::msg("Couldn't parse after"))
1117    }
1118}
1119
1120// The ISO parser accepts valid prefixes, so require a complete duration first.
1121fn relative_deadline(text: &str) -> anyhow::Result<DateTime<Utc>> {
1122    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");
1123    if !syntax.is_match(text) {
1124        return Err(Error::msg("invalid ISO 8601 duration"));
1125    }
1126    let parsed = text
1127        .parse::<iso8601::Duration>()
1128        .map_err(|e| Error::msg(e))?;
1129    let delay = Duration::from_std(std::time::Duration::from(parsed))?;
1130    if delay <= Duration::zero() {
1131        return Err(Error::msg("duration must be positive"));
1132    }
1133    Utc::now()
1134        .checked_add_signed(delay)
1135        .ok_or_else(|| Error::msg("duration is out of range"))
1136}
1137
1138/// Error routing metadata; only `ServiceTask.on_error.next` is executed.
1139#[derive(Debug, Clone, Serialize, Deserialize)]
1140pub struct OnError {
1141    /// Target after service-task retries are exhausted; unused for user tasks.
1142    #[serde(default)]
1143    pub next: Option<IdField>,
1144    /// Reserved compensation target; validated as a node reference but not executed.
1145    #[serde(default)]
1146    pub compensate: Option<IdField>,
1147}
1148
1149/// Lifecycle handler reference serialized as an ID or `{ handler }`.
1150#[derive(Debug, Clone, Serialize, Deserialize)]
1151#[serde(untagged)]
1152pub enum TaskHandler {
1153    /// Handler reference containing only its registry ID.
1154    Simple(IdField),
1155    /// Handler reference using the object representation.
1156    Extended(TaskHandlerDescription),
1157}
1158
1159impl TaskHandler {
1160    /// Returns the handler ID from either reference representation.
1161    pub fn handler(&self) -> IdField {
1162        match self {
1163            TaskHandler::Simple(h) => h.clone(),
1164            TaskHandler::Extended(h) => h.handler.clone(),
1165        }
1166    }
1167}
1168
1169/// Object form of a lifecycle handler reference.
1170#[derive(Debug, Clone, Serialize, Deserialize)]
1171pub struct TaskHandlerDescription {
1172    /// Registry key of the host handler to invoke.
1173    pub handler: IdField,
1174}
1175
1176/// Optional host callbacks for form, stage, and completion events.
1177///
1178/// Callbacks must be registered like service handlers. Their errors propagate,
1179/// and queued hooks require a successful status; their context patches are ignored.
1180/// During queued execution callbacks run before the database transition commits;
1181/// they may repeat after a failed attempt and must tolerate duplicate calls.
1182#[derive(Debug, Clone, Serialize, Deserialize)]
1183pub struct SpecialHandlers {
1184    /// Called with the proposed typed `stage` object before the queued transition commits.
1185    pub on_stage_change: Option<TaskHandler>,
1186    /// Called on user-task entry with `form_id` and `roles` arguments.
1187    pub on_show_form: Option<TaskHandler>,
1188    /// Called before entering the next queued node when the current node is a user task.
1189    pub on_hide_form: Option<TaskHandler>,
1190    /// Called on End entry with an `end_node_id` string argument.
1191    pub on_process_complete: Option<TaskHandler>,
1192}