a2a_protocol_server/tool_loop/journal/
memory.rs1use std::collections::HashMap;
7use std::sync::Mutex;
8
9use super::{JournalEntry, JournalError, JournalFuture, RunSummary, StepJournal};
10
11#[derive(Debug, Default)]
14pub struct InMemoryStepJournal {
15 runs: Mutex<HashMap<String, JournalEntry>>,
16}
17
18impl InMemoryStepJournal {
19 #[must_use]
21 pub fn new() -> Self {
22 Self::default()
23 }
24
25 #[must_use]
27 pub fn len(&self) -> usize {
28 self.lock().len()
29 }
30
31 #[must_use]
33 pub fn is_empty(&self) -> bool {
34 self.len() == 0
35 }
36
37 #[must_use]
39 pub fn unfinished(&self) -> usize {
40 self.lock().values().filter(|e| !e.completed).count()
41 }
42
43 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, JournalEntry>> {
44 self.runs
45 .lock()
46 .unwrap_or_else(std::sync::PoisonError::into_inner)
47 }
48}
49
50impl StepJournal for InMemoryStepJournal {
51 fn load<'a>(&'a self, key: &'a str) -> JournalFuture<'a, Option<JournalEntry>> {
52 Box::pin(async move { Ok(self.lock().get(key).cloned()) })
53 }
54
55 fn save<'a>(&'a self, key: &'a str, entry: &'a JournalEntry) -> JournalFuture<'a, ()> {
56 Box::pin(async move {
57 let mut runs = self.lock();
58 let stored = runs.get(key).map_or(0, |e| e.revision);
59 if stored.checked_add(1) != Some(entry.revision) {
60 return Err(JournalError::Conflict);
61 }
62 runs.insert(key.to_owned(), entry.clone());
63 drop(runs);
64 Ok(())
65 })
66 }
67
68 fn clear<'a>(&'a self, key: &'a str, revision: u64) -> JournalFuture<'a, ()> {
69 Box::pin(async move {
70 let mut runs = self.lock();
71 match runs.get(key).map(|e| e.revision) {
72 None => Ok(()),
73 Some(stored) if stored == revision => {
74 runs.remove(key);
75 drop(runs);
76 Ok(())
77 }
78 Some(_) => Err(JournalError::Conflict),
79 }
80 })
81 }
82
83 fn sweep(&self, completed_before_ms: i64, unfinished_before_ms: i64) -> JournalFuture<'_, u64> {
84 Box::pin(async move {
85 let mut runs = self.lock();
86 let before = runs.len();
87 runs.retain(|_, e| {
88 let cutoff = if e.completed {
89 completed_before_ms
90 } else {
91 unfinished_before_ms
92 };
93 e.updated_at_ms >= cutoff
94 });
95 let gone = before - runs.len();
96 drop(runs);
97 Ok(gone as u64)
98 })
99 }
100
101 fn runs_of<'a>(
102 &'a self,
103 principal: &'a str,
104 tenant: Option<&'a str>,
105 ) -> JournalFuture<'a, Vec<RunSummary>> {
106 Box::pin(async move {
107 let mut out: Vec<RunSummary> = self
108 .lock()
109 .iter()
110 .filter(|(_, e)| e.owner.is_of(principal, tenant))
111 .map(|(k, e)| e.summary(k))
112 .collect();
113 out.sort_by(|a, b| a.key.cmp(&b.key));
114 Ok(out)
115 })
116 }
117
118 fn erase<'a>(&'a self, principal: &'a str, tenant: Option<&'a str>) -> JournalFuture<'a, u64> {
119 Box::pin(async move {
120 let mut runs = self.lock();
121 let before = runs.len();
122 runs.retain(|_, e| !e.owner.is_of(principal, tenant));
123 let gone = before - runs.len();
124 drop(runs);
125 Ok(gone as u64)
126 })
127 }
128}