1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ProcessDefinition {
40 #[serde(skip)]
42 pub uuid: Option<Uuid>,
43 pub key: IdField,
45 pub name: String,
47 pub version: VersionId,
49
50 pub status: ProcessStatus,
52
53 pub effective_from: Option<DateTime<Utc>>,
55
56 #[serde(default)]
58 pub deprecated_at: Option<DateTime<Utc>>,
59
60 #[serde(default)]
62 pub metadata: ProcessMetadata,
63
64 #[serde(default)]
66 pub signals: Vec<SignalDef>,
67
68 #[serde(default)]
70 pub forms: Vec<FormDef>,
71
72 #[serde(default)]
74 pub stages: Vec<StageDef>,
75
76 pub special_handlers: Option<SpecialHandlers>,
78
79 #[serde(default)]
81 pub escalations: Vec<EscalationDef>,
82
83 pub nodes: Vec<Node>,
85}
86
87impl ProcessDefinition {
88 pub fn compile(&self) -> Result<JsonValue, CreateProcessError> {
94 self.validate()?;
95 Ok(json!(self))
96 }
97
98 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
666#[serde(rename_all = "lowercase")]
667pub enum ProcessStatus {
668 Draft,
670 Active,
672 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
684pub struct ProcessMetadata {
685 pub owner: Option<String>,
687 pub sla: Option<String>,
689 pub comment: Option<String>,
691}
692
693#[derive(Debug, Clone, Serialize, Deserialize)]
695#[serde(untagged)]
696pub enum SignalDef {
697 Name(IdField),
699 Obj {
701 name: IdField,
703 },
704}
705
706#[derive(Debug, Clone, Serialize, Deserialize)]
708pub struct FormDef {
709 pub id: IdField,
711 pub roles: Vec<IdField>,
713}
714
715#[derive(Clone, Debug, Serialize, Deserialize)]
717#[serde(untagged)]
718pub enum StageDef {
719 Obj {
721 id: IdField,
723 name: String,
725 #[serde(default)]
727 is_initial: Option<bool>,
728 #[serde(default)]
730 is_final: Option<bool>,
731 },
732 Name(IdField),
734}
735
736impl StageDef {
737 pub fn id(&self) -> &IdField {
739 match self {
740 StageDef::Name(s) => s,
741 StageDef::Obj { id, .. } => id,
742 }
743 }
744
745 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 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 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 pub fn id(&self) -> &IdField {
773 match self {
774 SignalDef::Name(s) => s,
775 SignalDef::Obj { name } => name,
776 }
777 }
778}
779
780#[derive(Debug, Clone, Serialize, Deserialize)]
782pub struct TaskArgument {
783 pub name: IdField,
785 pub value: String,
787}
788
789#[derive(Debug, Clone, Serialize, Deserialize)]
791#[serde(tag = "type")]
792pub enum Node {
793 Start {
795 id: IdField,
797 next: IdField,
799 set_stage: Option<SetStage>,
801 },
802
803 End {
805 id: IdField,
807 set_stage: Option<SetStage>,
809 },
810
811 ServiceTask {
813 id: IdField,
815 handler: IdField,
817 #[serde(default)]
819 args: Option<ContextMap>,
820 set_stage: Option<SetStage>,
822 #[serde(default)]
824 retries: Option<Retries>,
825 #[serde(default)]
827 next: Option<Next>,
828 #[serde(default)]
830 on_error: Option<OnError>,
831 },
832
833 UserTask {
835 id: IdField,
837 form: IdField,
839 #[serde(default)]
841 wait_for: Option<WaitFor>,
842 set_stage: Option<SetStage>,
844 #[serde(rename = "timeout")]
846 #[serde(default)]
847 timeout: Option<NodeTimeout>,
848
849 #[serde(default)]
851 next: Option<Next>,
852
853 #[serde(default)]
855 on_error: Option<OnError>,
856 },
857
858 Wait {
861 id: IdField,
863 wait_for: WaitFor,
865 #[serde(default)]
867 timeout: Option<NodeTimeout>,
868 #[serde(default)]
870 next: Option<Next>,
871 set_stage: Option<SetStage>,
873 },
874
875 Gateway {
877 id: IdField,
879 set_stage: Option<SetStage>,
881 gateway: GatewayKind,
883 #[serde(default)]
885 branches: Vec<Branch>,
886 #[serde(default)]
888 next: Option<IdField>,
889 },
890}
891
892impl Node {
893 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 pub fn is_start(&self) -> bool {
906 matches!(self, Node::Start { .. })
907 }
908 pub fn is_end(&self) -> bool {
910 matches!(self, Node::End { .. })
911 }
912 pub fn is_service_task(&self) -> bool {
914 matches!(self, Node::ServiceTask { .. })
915 }
916 pub fn is_user_task(&self) -> bool {
918 matches!(self, Node::UserTask { .. })
919 }
920 pub fn timeout(&self) -> Option<&NodeTimeout> {
922 match self {
923 Node::UserTask { timeout, .. } | Node::Wait { timeout, .. } => timeout.as_ref(),
924 _ => None,
925 }
926 }
927 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#[derive(Debug, Clone, Serialize, Deserialize)]
942#[serde(untagged)]
943pub enum SetStage {
944 Stage(IdField),
946 StageWithReason(SetStageWithReason),
948}
949
950impl SetStage {
951 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#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct SetStageWithReason {
972 pub stage: IdField,
974 pub reason: Option<String>,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize)]
996#[serde(rename_all = "UPPERCASE")]
997pub enum GatewayKind {
998 XOR,
1000}
1001
1002#[derive(Debug, Clone, Serialize, Deserialize)]
1004pub struct Branch {
1005 pub when: String,
1007 pub next: IdField,
1009}
1010
1011#[derive(Debug, Clone, Serialize, Deserialize)]
1013pub struct Retries {
1014 pub max: u32,
1016 pub backoff: String,
1018}
1019
1020impl Retries {
1021 pub fn next_attempt_at(&self) -> anyhow::Result<DateTime<Utc>> {
1027 relative_deadline(&self.backoff)
1028 }
1029}
1030
1031#[derive(Debug, Clone, Serialize, Deserialize)]
1033#[serde(untagged)]
1034pub enum Next {
1035 To(IdField),
1037 Routes(NextRoutes),
1039}
1040
1041#[derive(Debug, Clone, Serialize, Deserialize)]
1043pub struct NextRoutes {
1044 #[serde(default)]
1046 pub default: Option<IdField>,
1047 #[serde(default)]
1049 pub branches: Vec<Branch>,
1050}
1051
1052#[derive(Debug, Clone, Serialize, Deserialize)]
1054#[serde(untagged)]
1055pub enum WaitFor {
1056 Single {
1058 signal: IdField,
1060 },
1061 Multi {
1063 signals: Vec<IdField>,
1065 },
1066}
1067
1068impl WaitFor {
1069 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#[derive(Debug, Clone, Serialize, Deserialize)]
1085pub struct NodeTimeout {
1086 #[serde(default)]
1088 pub after: Option<String>,
1089 #[serde(default)]
1091 pub at: Option<DateTime<Utc>>,
1092 pub on_timeout: IdField,
1094 #[serde(default, skip_serializing_if = "ContextMap::is_empty")]
1099 pub context: ContextMap,
1100}
1101
1102impl NodeTimeout {
1103 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
1120fn 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#[derive(Debug, Clone, Serialize, Deserialize)]
1140pub struct OnError {
1141 #[serde(default)]
1143 pub next: Option<IdField>,
1144 #[serde(default)]
1146 pub compensate: Option<IdField>,
1147}
1148
1149#[derive(Debug, Clone, Serialize, Deserialize)]
1151#[serde(untagged)]
1152pub enum TaskHandler {
1153 Simple(IdField),
1155 Extended(TaskHandlerDescription),
1157}
1158
1159impl TaskHandler {
1160 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#[derive(Debug, Clone, Serialize, Deserialize)]
1171pub struct TaskHandlerDescription {
1172 pub handler: IdField,
1174}
1175
1176#[derive(Debug, Clone, Serialize, Deserialize)]
1183pub struct SpecialHandlers {
1184 pub on_stage_change: Option<TaskHandler>,
1186 pub on_show_form: Option<TaskHandler>,
1188 pub on_hide_form: Option<TaskHandler>,
1190 pub on_process_complete: Option<TaskHandler>,
1192}