Skip to main content

acl_core/
idempotency.rs

1//! Idempotency and ordering (spec §8.1).
2//!
3//! Retransmission semantics: a client retrying a request MUST reuse the
4//! same `msg_id` and body; the receiver deduplicates within a TTL window.
5//! `IdempotencyCache` implements that receiver side.
6
7use crate::{Body, Envelope};
8use std::collections::HashMap;
9
10/// Body -> JSON value (for hashing; Body itself isn't Hash).
11fn body_to_value(b: &Body) -> serde_json::Value {
12    match b {
13        Body::Task { description, input, deadline_ms, priority } => serde_json::json!({
14            "k": "Task", "d": description, "i": input, "dl": deadline_ms, "p": priority }),
15        Body::Result { output, artifacts } => serde_json::json!({
16            "k": "Result", "o": output, "a": artifacts }),
17        Body::Text { text } => serde_json::json!({ "k": "Text", "t": text }),
18        Body::Query { subject, parameters } => serde_json::json!({ "k": "Query", "s": subject, "p": parameters }),
19        Body::Proposal { terms, price, valid_until } => serde_json::json!({ "k": "Proposal", "t": terms, "p": price, "v": valid_until }),
20        Body::Ref { target_msg_id } => serde_json::json!({ "k": "Ref", "t": target_msg_id }),
21        Body::Progress { target_msg_id, percent, note } => serde_json::json!({ "k": "Progress", "t": target_msg_id, "p": percent, "n": note }),
22        Body::InputNeeded { target_msg_id, what, schema } => serde_json::json!({ "k": "InputNeeded", "t": target_msg_id, "w": what, "s": schema }),
23        Body::Failure { target_msg_id, code, reason, recoverable } => serde_json::json!({ "k": "Failure", "t": target_msg_id, "c": code, "r": reason, "rec": recoverable }),
24        Body::Error { code, message, taxonomy, details } => serde_json::json!({ "k": "Error", "c": code, "m": message, "t": taxonomy, "d": details }),
25        Body::Hello { nonce, .. } => serde_json::json!({ "k": "Hello", "n": nonce }),
26        Body::Sealed { ciphertext, .. } => serde_json::json!({ "k": "Sealed", "c": ciphertext }),
27        Body::Delegate { chain, .. } => serde_json::json!({ "k": "Delegate", "c": chain }),
28        Body::Cl { expressions } => serde_json::json!({ "k": "Cl", "e": expressions }),
29        Body::Subscribe { watch, until_ms } => serde_json::json!({ "k": "Subscribe", "w": watch, "u": until_ms }),
30        Body::Unsubscribe { target_msg_id } => serde_json::json!({ "k": "Unsubscribe", "t": target_msg_id }),
31        Body::KeyRotation { new_did, valid_from_ms, reason } => serde_json::json!({ "k": "KeyRotation", "d": new_did, "v": valid_from_ms, "r": reason }),
32    }
33}
34
35#[derive(Debug, Default)]
36pub struct IdempotencyCache {
37    /// msg_id -> (arrival monotonic-ish timestamp, body fingerprint)
38    seen: HashMap<String, (i64, u64)>,
39}
40
41/// Semantic fingerprint: performative + from/to + body. Deliberately
42/// EXCLUDES ts so a re-signed retransmission (new ts, same msg_id and
43/// body) is still recognized as a clean duplicate.
44fn fingerprint(env: &Envelope) -> u64 {
45    use std::hash::{Hash, Hasher};
46    let mut h = std::collections::hash_map::DefaultHasher::new();
47    env.performative.hash(&mut h);
48    env.from.hash(&mut h);
49    env.to.hash(&mut h);
50    let body_json = serde_json::to_string(&body_to_value(&env.body)).unwrap_or_default();
51    body_json.hash(&mut h);
52    h.finish()
53}
54
55impl IdempotencyCache {
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Returns `true` if this is the FIRST time we accept this message.
61    /// A duplicate (same msg_id, same fingerprint, still within TTL) is
62    /// rejected — the caller MUST NOT re-process it, but SHOULD re-send the
63    /// cached response if it has one.
64    /// A same-msg_id message with a DIFFERENT fingerprint is a protocol
65    /// violation: also rejected, and should be logged as an error.
66    pub fn check(&mut self, env: &Envelope, now_ms: i64) -> bool {
67        let fp = fingerprint(env);
68        match self.seen.get(&env.msg_id) {
69            // Any existing msg_id is a duplicate → never "first". The
70            // fingerprint equality only distinguishes clean duplicates
71            // from protocol violations (both rejected here; caller logs).
72            Some((_, old_fp)) => {
73                let _ = *old_fp == fp;
74                false
75            }
76            None => {
77                self.seen.insert(env.msg_id.clone(), (now_ms, fp));
78                true
79            }
80        }
81    }
82
83    /// Evict entries older than `ttl_ms` (call periodically).
84    pub fn evict_older_than(&mut self, now_ms: i64, ttl_ms: i64) {
85        self.seen.retain(|_, (ts, _)| now_ms - *ts <= ttl_ms);
86    }
87
88    pub fn len(&self) -> usize {
89        self.seen.len()
90    }
91
92    pub fn is_empty(&self) -> bool {
93        self.seen.is_empty()
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::{Aid, Body, Performative};
101
102    fn env_with_id(msg_id: &str, text: &str) -> Envelope {
103        let mut e = Envelope::new(
104            Aid::local(1, "t"),
105            Aid::new("did:x:y"),
106            Performative::Request,
107            Body::Text { text: text.into() },
108        );
109        e.msg_id = msg_id.into();
110        e
111    }
112
113    #[test]
114    fn first_accepts_duplicate_rejects() {
115        let mut c = IdempotencyCache::new();
116        let e = env_with_id("aaaa", "hello");
117        assert!(c.check(&e, 1000)); // first
118        assert!(!c.check(&e, 1100)); // clean duplicate
119        assert!(!c.check(&e, 5000)); // still duplicate (no eviction yet)
120    }
121
122    #[test]
123    fn same_id_different_body_is_violation() {
124        let mut c = IdempotencyCache::new();
125        assert!(c.check(&env_with_id("bbbb", "hello"), 1000));
126        assert!(!c.check(&env_with_id("bbbb", "EVIL"), 1100));
127    }
128
129    #[test]
130    fn eviction_frees_slot() {
131        let mut c = IdempotencyCache::new();
132        assert!(c.check(&env_with_id("cccc", "x"), 1000));
133        c.evict_older_than(1_000_000, 300_000);
134        assert!(c.is_empty());
135        // after eviction + TTL, reuse of the id is accepted again
136        assert!(c.check(&env_with_id("cccc", "x"), 1_000_001));
137    }
138
139    #[test]
140    fn distinct_ids_pass() {
141        let mut c = IdempotencyCache::new();
142        assert!(c.check(&env_with_id("d1", "x"), 1000));
143        assert!(c.check(&env_with_id("d2", "x"), 1000));
144        assert_eq!(c.len(), 2);
145    }
146}