Skip to main content

acl_core/
stdlib.rs

1//! §35.14: standard protocol fragments — battle-tested handler sets
2//! for common agent interaction patterns. Merge into a program with
3//! `apply_fragment`; the program's own handlers win on trigger clash.
4//!
5//! Fragments here are compiled Rust (not `.aclp`) because they are
6//! polymorphic over the host program's roles.
7
8use crate::protocol::{Guard, Handler, OnTrigger, ProtocolAction, ProtocolProgram};
9use std::collections::BTreeMap;
10use crate::Performative;
11
12/// escalate to the counterpart when a commitment nears expiry:
13/// `every <warn_ms> -> send progress to <other>`
14pub 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
31/// require a second confirmation before `begin`: an `accept` only
32/// activates the commitment when a `confirm` flag was set by a prior
33/// `inform`.
34pub 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
49/// register a fragment under a name
50pub 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
58/// merge fragment handlers into a program, skipping exact duplicates
59pub 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        // second apply is a no-op (dedup)
87        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}