Skip to main content

a2a_protocol_server/store/claim/
memory.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`TurnClaimStore`] in process memory: for tests that run several handlers
5//! over one in-memory store.
6
7use std::collections::HashMap;
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicI64, Ordering};
10use std::time::{Duration, Instant};
11
12use super::{Fut, Handed, HeldClaim, PendingSteering, TurnClaimStore};
13
14/// Claims in process memory, for tests that run several handlers over one
15/// in-memory store. Expiry is measured on this process's monotonic clock.
16///
17/// Steering messages handed to a claim ([`TurnClaimStore::hand_steering`])
18/// are kept here too, in process memory: this store is only as shared as the
19/// handlers holding it, which is why it is for tests and not for replicas.
20#[derive(Debug, Default)]
21pub struct InMemoryTurnClaims {
22    claims: Mutex<HashMap<(String, String), Entry>>,
23    /// Steering messages, oldest first.
24    steering: Mutex<Vec<Queued>>,
25    next_seq: AtomicI64,
26}
27
28#[derive(Debug)]
29struct Entry {
30    owner: String,
31    token: String,
32    cancel_requested: bool,
33    expires: Instant,
34}
35
36#[derive(Debug)]
37struct Queued {
38    seq: i64,
39    token: String,
40    message: String,
41}
42
43impl InMemoryTurnClaims {
44    /// No claims.
45    #[must_use]
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Whether `token` still holds a claim.
51    #[must_use]
52    pub fn holds(&self, token: &str) -> bool {
53        self.lock().values().any(|e| e.token == token)
54    }
55
56    /// How many steering messages are stored, for any claim: what a test
57    /// reads to see that a refused message left nothing behind.
58    #[cfg(test)]
59    pub(crate) fn queued(&self) -> usize {
60        self.queue().len()
61    }
62
63    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<(String, String), Entry>> {
64        self.claims
65            .lock()
66            .unwrap_or_else(std::sync::PoisonError::into_inner)
67    }
68
69    fn queue(&self) -> std::sync::MutexGuard<'_, Vec<Queued>> {
70        self.steering
71            .lock()
72            .unwrap_or_else(std::sync::PoisonError::into_inner)
73    }
74}
75
76impl TurnClaimStore for InMemoryTurnClaims {
77    fn claim<'a>(
78        &'a self,
79        scope: &'a str,
80        task_id: &'a str,
81        owner: &'a str,
82        token: &'a str,
83        ttl: Duration,
84    ) -> Fut<'a, bool> {
85        Box::pin(async move {
86            let now = Instant::now();
87            let entry = Entry {
88                owner: owner.to_owned(),
89                token: token.to_owned(),
90                cancel_requested: false,
91                expires: now + ttl,
92            };
93            let key = (scope.to_owned(), task_id.to_owned());
94            let mut claims = self.lock();
95            if claims.get(&key).is_some_and(|e| live(e.expires, now)) {
96                return Ok(false);
97            }
98            claims.insert(key, entry);
99            drop(claims);
100            Ok(true)
101        })
102    }
103
104    fn release<'a>(&'a self, token: &'a str) -> Fut<'a, ()> {
105        Box::pin(async move {
106            self.lock().retain(|_, e| e.token != token);
107            self.queue().retain(|q| q.token != token);
108            Ok(())
109        })
110    }
111
112    fn renew<'a>(
113        &'a self,
114        owner: &'a str,
115        tokens: &'a [String],
116        ttl: Duration,
117    ) -> Fut<'a, Vec<HeldClaim>> {
118        Box::pin(async move {
119            let expires = Instant::now() + ttl;
120            Ok(self
121                .lock()
122                .values_mut()
123                .filter(|e| e.owner == owner && tokens.contains(&e.token))
124                .map(|e| {
125                    e.expires = expires;
126                    HeldClaim {
127                        token: e.token.clone(),
128                        cancel_requested: e.cancel_requested,
129                    }
130                })
131                .collect())
132        })
133    }
134
135    fn request_cancel<'a>(&'a self, scope: &'a str, task_id: &'a str) -> Fut<'a, bool> {
136        Box::pin(async move {
137            let now = Instant::now();
138            Ok(self
139                .lock()
140                .get_mut(&(scope.to_owned(), task_id.to_owned()))
141                .filter(|e| live(e.expires, now))
142                .map(|e| e.cancel_requested = true)
143                .is_some())
144        })
145    }
146
147    fn sweep(&self, older_than: Duration) -> Fut<'_, u64> {
148        Box::pin(async move {
149            let now = Instant::now();
150            let mut claims = self.lock();
151            let before = claims.len();
152            claims.retain(|_, e| !swept(e.expires, older_than, now));
153            Ok((before - claims.len()) as u64)
154        })
155    }
156
157    fn hand_steering<'a>(
158        &'a self,
159        scope: &'a str,
160        task_id: &'a str,
161        message: &'a str,
162        capacity: usize,
163    ) -> Fut<'a, Handed> {
164        Box::pin(async move {
165            let now = Instant::now();
166            let token = self
167                .lock()
168                .get(&(scope.to_owned(), task_id.to_owned()))
169                .filter(|e| live(e.expires, now))
170                .map(|e| e.token.clone());
171            let Some(token) = token else {
172                return Ok(Handed::NoClaim);
173            };
174            let mut queue = self.queue();
175            if queue.iter().filter(|q| q.token == token).count() >= capacity {
176                return Ok(Handed::Full);
177            }
178            let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
179            queue.push(Queued {
180                seq,
181                token,
182                message: message.to_owned(),
183            });
184            drop(queue);
185            Ok(Handed::Queued)
186        })
187    }
188
189    fn peek_steering<'a>(
190        &'a self,
191        owner: &'a str,
192        tokens: &'a [String],
193        limit: usize,
194    ) -> Fut<'a, Vec<PendingSteering>> {
195        Box::pin(async move {
196            let now = Instant::now();
197            let held: Vec<String> = self
198                .lock()
199                .values()
200                .filter(|e| e.owner == owner && live(e.expires, now) && tokens.contains(&e.token))
201                .map(|e| e.token.clone())
202                .collect();
203            Ok(self
204                .queue()
205                .iter()
206                .filter(|q| held.contains(&q.token))
207                .take(limit)
208                .map(|q| PendingSteering {
209                    seq: q.seq,
210                    token: q.token.clone(),
211                    message: q.message.clone(),
212                })
213                .collect())
214        })
215    }
216
217    fn ack_steering<'a>(&'a self, seqs: &'a [i64]) -> Fut<'a, ()> {
218        Box::pin(async move {
219            self.queue().retain(|q| !seqs.contains(&q.seq));
220            Ok(())
221        })
222    }
223}
224
225/// Whether a claim expiring at `expires` still holds at `now`: until the
226/// instant it expires, and not at it, which is when another turn may take it.
227pub(super) fn live(expires: Instant, now: Instant) -> bool {
228    expires > now
229}
230
231/// Whether a claim that expired at `expires` is past the sweep's grace of
232/// `older_than` at `now`: swept at the instant the grace ends, not before.
233pub(super) fn swept(expires: Instant, older_than: Duration, now: Instant) -> bool {
234    expires + older_than <= now
235}