1use crate::protocol::{Guard, Handler, OnTrigger, ProtocolAction, ProtocolProgram};
9use std::collections::BTreeMap;
10use crate::Performative;
11
12pub fn deadline_escalation(warn_ms: i64) -> Handler {
15 Handler {
16 trigger: OnTrigger::Timer { every_ms: warn_ms, guard: None, as_role: None },
17 guard: None,
18 actions: vec![ProtocolAction::Send {
19 performative: Performative::Progress,
20 to: None,
21 fields: Some(BTreeMap::from([(
22 "reason".into(),
23 "deadline approaching".into(),
24 )])),
25 retry: None,
26 }],
27 line: 0,
28 }
29}
30
31pub fn double_confirmation() -> Handler {
35 Handler {
36 trigger: OnTrigger::Event {
37 performative: Performative::Accept,
38 pattern: None,
39 from: None,
40 as_role: None,
41 phase: None,
42 },
43 guard: Some(Guard::Atom { name: "confirmed".into(), neg: false }),
44 actions: vec![ProtocolAction::Begin],
45 line: 0,
46 }
47}
48
49pub fn lookup(name: &str) -> Option<Vec<Handler>> {
51 match name {
52 "deadline_escalation" => Some(vec![deadline_escalation(60_000)]),
53 "double_confirmation" => Some(vec![double_confirmation()]),
54 _ => None,
55 }
56}
57
58pub fn apply_fragment(program: &mut ProtocolProgram, name: &str) -> Result<usize, String> {
60 let handlers = lookup(name).ok_or_else(|| format!("unknown fragment '{name}'"))?;
61 let mut added = 0;
62 for h in handlers {
63 let exists = program.handlers.iter().any(|x| {
64 x.trigger == h.trigger && x.actions == h.actions
65 });
66 if !exists {
67 program.handlers.push(h);
68 added += 1;
69 }
70 }
71 Ok(added)
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77 use crate::protocol::parse;
78
79 #[test]
80 fn fragments_merge_without_clash() {
81 let mut prog = parse(
82 "protocol p v1;\nroles a, b;\non query from a -> send inform to a;\non inform from b -> send bye;\n",
83 )
84 .unwrap();
85 assert_eq!(apply_fragment(&mut prog, "deadline_escalation").unwrap(), 1);
86 assert_eq!(apply_fragment(&mut prog, "deadline_escalation").unwrap(), 0);
88 assert_eq!(apply_fragment(&mut prog, "double_confirmation").unwrap(), 1);
89 assert_eq!(prog.handlers.len(), 4);
90 assert!(lookup("nope").is_none());
91 }
92}