1use std::collections::{BTreeMap, HashMap};
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use arc_swap::{ArcSwap, Guard};
7use async_channel::{Receiver, Sender};
8
9const ERR_TOOL_REQUEST_UNAVAILABLE: &str = include_str!("texts/tool_request_unavailable.txt");
10const ERR_TOOL_REQUEST_CANCELLED: &str = include_str!("texts/tool_request_cancelled.txt");
11
12#[derive(Debug)]
14pub struct ToolRequest<Args, Response> {
15 pub args: Args,
17 response_tx: Sender<Response>,
18}
19
20impl<Args, Response> ToolRequest<Args, Response> {
21 #[must_use]
23 pub const fn new(args: Args, response_tx: Sender<Response>) -> Self {
24 Self { args, response_tx }
25 }
26
27 pub fn respond(self, response: Response) -> Result<(), async_channel::TrySendError<Response>> {
33 self.response_tx.try_send(response)
34 }
35}
36
37#[derive(Debug, Clone)]
39pub struct ToolRequestBroker<Args, Response> {
40 tx: Sender<ToolRequest<Args, Response>>,
41}
42
43impl<Args, Response> ToolRequestBroker<Args, Response> {
44 pub async fn request(&self, args: Args) -> anyhow::Result<Response> {
51 let (response_tx, response_rx) = async_channel::bounded(1);
52 self.tx
53 .send(ToolRequest::new(args, response_tx))
54 .await
55 .map_err(|_| anyhow::anyhow!(ERR_TOOL_REQUEST_UNAVAILABLE.trim()))?;
56
57 response_rx
58 .recv()
59 .await
60 .map_err(|_| anyhow::anyhow!(ERR_TOOL_REQUEST_CANCELLED.trim()))
61 }
62}
63
64#[derive(Debug)]
66pub struct ToolRequestQueue<Args, Response> {
67 rx: Receiver<ToolRequest<Args, Response>>,
68}
69
70impl<Args, Response> ToolRequestQueue<Args, Response> {
71 pub async fn next(&self) -> Option<ToolRequest<Args, Response>> {
73 self.rx.recv().await.ok()
74 }
75
76 #[must_use]
78 pub fn is_empty(&self) -> bool {
79 self.rx.is_empty()
80 }
81}
82
83#[must_use]
85pub fn channel<Args, Response>() -> (
86 ToolRequestBroker<Args, Response>,
87 ToolRequestQueue<Args, Response>,
88) {
89 let (tx, rx) = async_channel::unbounded();
90 (ToolRequestBroker { tx }, ToolRequestQueue { rx })
91}
92
93#[must_use]
99pub fn bounded_channel<Args, Response>(
100 capacity: usize,
101) -> (
102 ToolRequestBroker<Args, Response>,
103 ToolRequestQueue<Args, Response>,
104) {
105 assert!(capacity > 0, "tool request queue capacity must be > 0");
106 let (tx, rx) = async_channel::bounded(capacity);
107 (ToolRequestBroker { tx }, ToolRequestQueue { rx })
108}
109
110struct PendingEntry<P, R> {
113 order: u64,
114 payload: P,
115 tx: Sender<R>,
116}
117
118struct RequestApproverState<P, R> {
119 order: BTreeMap<u64, String>,
120 pending: HashMap<String, PendingEntry<P, R>>,
121}
122
123impl<P: Clone, R> Clone for PendingEntry<P, R> {
124 fn clone(&self) -> Self {
125 Self {
126 order: self.order,
127 payload: self.payload.clone(),
128 tx: self.tx.clone(),
129 }
130 }
131}
132
133impl<P: Clone, R> Clone for RequestApproverState<P, R> {
134 fn clone(&self) -> Self {
135 Self {
136 order: self.order.clone(),
137 pending: self.pending.clone(),
138 }
139 }
140}
141
142pub struct RequestApprover<P, R> {
156 state: ArcSwap<RequestApproverState<P, R>>,
157 event: event_listener::Event,
158 next_id: AtomicU64,
159}
160
161impl<P, R> std::fmt::Debug for RequestApprover<P, R> {
162 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163 let pending_count = self.state.load().pending.len();
164 f.debug_struct("RequestApprover")
165 .field("pending_count", &pending_count)
166 .field("next_id", &self.next_id.load(Ordering::Relaxed))
167 .finish_non_exhaustive()
168 }
169}
170
171impl<P: Clone, R> Default for RequestApprover<P, R> {
172 fn default() -> Self {
173 Self::new()
174 }
175}
176
177impl<P: Clone, R> RequestApprover<P, R> {
178 #[must_use]
180 pub fn new() -> Self {
181 Self {
182 state: ArcSwap::from_pointee(RequestApproverState {
183 order: BTreeMap::new(),
184 pending: HashMap::new(),
185 }),
186 event: event_listener::Event::new(),
187 next_id: AtomicU64::new(0),
188 }
189 }
190
191 pub fn enqueue(&self, payload: P) -> (String, Receiver<R>) {
200 let order = self.next_id.fetch_add(1, Ordering::Relaxed);
201 let id = order.to_string();
202 let (tx, rx) = async_channel::bounded(1);
203 let entry = PendingEntry { order, payload, tx };
204 self.state.rcu(|state| {
205 let mut next = state.as_ref().clone();
206 next.order.insert(order, id.clone());
207 next.pending.insert(id.clone(), entry.clone());
208 next
209 });
210 self.event.notify(usize::MAX);
211 (id, rx)
212 }
213
214 pub fn respond(&self, id: &str, response: R) -> bool {
222 let mut found = None;
223 loop {
224 let current = self.state.load_full();
225 let Some(entry) = current.pending.get(id).cloned() else {
226 break;
227 };
228 let mut next = current.as_ref().clone();
229 next.pending.remove(id);
230 next.order.remove(&entry.order);
231 let previous = Guard::into_inner(
232 self.state
233 .compare_and_swap(¤t, std::sync::Arc::new(next)),
234 );
235 if std::sync::Arc::ptr_eq(¤t, &previous) {
236 found = Some(entry);
237 break;
238 }
239 }
240 self.event.notify(usize::MAX);
241 found.is_some_and(|entry| entry.tx.try_send(response).is_ok())
242 }
243
244 #[must_use]
250 pub fn peek(&self) -> Option<(String, P)> {
251 let state = self.state.load();
252 let (_order, id) = state.order.iter().next()?;
253 state
254 .pending
255 .get(id.as_str())
256 .map(|entry| (id.clone(), entry.payload.clone()))
257 }
258
259 #[must_use]
265 pub fn peek_filtered(&self, predicate: impl Fn(&P) -> bool) -> Option<(String, P)> {
266 let state = self.state.load();
267 for id in state.order.values() {
268 let Some(entry) = state.pending.get(id.as_str()) else {
269 continue;
270 };
271 if predicate(&entry.payload) {
272 return Some((id.clone(), entry.payload.clone()));
273 }
274 }
275 None
276 }
277
278 #[must_use]
284 pub fn get_payload(&self, id: &str) -> Option<P> {
285 self.state
286 .load()
287 .pending
288 .get(id)
289 .map(|entry| entry.payload.clone())
290 }
291
292 #[must_use]
298 pub fn is_empty(&self) -> bool {
299 self.state.load().pending.is_empty()
300 }
301
302 pub fn listen(&self) -> event_listener::EventListener {
314 self.event.listen()
315 }
316}
317
318#[cfg(test)]
319mod tests {
320 use super::RequestApprover;
321
322 #[test]
323 fn peek_returns_requests_in_fifo_order() {
324 let approver = RequestApprover::<&'static str, ()>::new();
325 let _first = approver.enqueue("first");
326 let _second = approver.enqueue("second");
327
328 let peeked = approver.peek().expect("first request should be visible");
329 assert_eq!(peeked, ("0".to_string(), "first"));
330 }
331
332 #[test]
333 fn peek_skips_resolved_requests() {
334 let approver = RequestApprover::<&'static str, ()>::new();
335 let (first_id, first_rx) = approver.enqueue("first");
336 let _second = approver.enqueue("second");
337
338 assert!(approver.respond(&first_id, ()));
339 drop(first_rx);
340
341 let peeked = approver.peek().expect("second request should remain");
342 assert_eq!(peeked, ("1".to_string(), "second"));
343 }
344}