1use crate::{Body, Envelope};
8use std::collections::HashMap;
9
10fn 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 seen: HashMap<String, (i64, u64)>,
39}
40
41fn 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 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 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 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)); assert!(!c.check(&e, 1100)); assert!(!c.check(&e, 5000)); }
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 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}