strands/agent/
invocation_state.rs1use std::fmt;
4use std::sync::{Arc, PoisonError, RwLock};
5
6#[derive(Clone, Default)]
29pub struct InvocationState {
30 values: Arc<RwLock<http::Extensions>>,
31}
32
33impl InvocationState {
34 pub fn new() -> Self {
36 Self::default()
37 }
38
39 pub(crate) fn copy(&self) -> Self {
42 let values = self.values.read().unwrap_or_else(PoisonError::into_inner).clone();
43 Self {
44 values: Arc::new(RwLock::new(values)),
45 }
46 }
47
48 pub fn insert<T: Clone + Send + Sync + 'static>(&self, value: T) -> Option<T> {
50 self.values
51 .write()
52 .unwrap_or_else(PoisonError::into_inner)
53 .insert(value)
54 }
55
56 #[must_use]
58 pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
59 self.values
60 .read()
61 .unwrap_or_else(PoisonError::into_inner)
62 .get::<T>()
63 .cloned()
64 }
65
66 #[must_use]
68 pub fn contains<T: Clone + Send + Sync + 'static>(&self) -> bool {
69 self.values
70 .read()
71 .unwrap_or_else(PoisonError::into_inner)
72 .get::<T>()
73 .is_some()
74 }
75
76 pub fn update<T, R>(&self, update: impl FnOnce(&mut T) -> R) -> R
80 where
81 T: Clone + Default + Send + Sync + 'static,
82 {
83 let mut values = self.values.write().unwrap_or_else(PoisonError::into_inner);
84 update(values.get_or_insert_default::<T>())
85 }
86
87 pub fn remove<T: Clone + Send + Sync + 'static>(&self) -> Option<T> {
89 self.values
90 .write()
91 .unwrap_or_else(PoisonError::into_inner)
92 .remove::<T>()
93 }
94
95 #[must_use]
97 pub fn is_empty(&self) -> bool {
98 self.values.read().unwrap_or_else(PoisonError::into_inner).is_empty()
99 }
100
101 #[must_use]
103 pub fn len(&self) -> usize {
104 self.values.read().unwrap_or_else(PoisonError::into_inner).len()
105 }
106
107 pub fn clear(&self) {
109 self.values.write().unwrap_or_else(PoisonError::into_inner).clear();
110 }
111}
112
113impl fmt::Debug for InvocationState {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.debug_struct("InvocationState").field("len", &self.len()).finish()
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use super::*;
122
123 #[derive(Clone, Debug, Default, PartialEq)]
124 struct Counter(u32);
125
126 #[test]
127 fn clones_share_values() {
128 let state = InvocationState::new();
129 let clone = state.clone();
130 assert_eq!(clone.insert(Counter(1)), None);
131 assert_eq!(state.get::<Counter>(), Some(Counter(1)));
132 assert_eq!(state.insert(Counter(2)), Some(Counter(1)));
133 assert!(clone.contains::<Counter>());
134 assert_eq!(clone.len(), 1);
135 assert_eq!(clone.remove::<Counter>(), Some(Counter(2)));
136 assert!(state.is_empty());
137 }
138
139 #[test]
140 fn update_inserts_a_default_and_mutates_in_place() {
141 let state = InvocationState::new();
142 state.update(|counter: &mut Counter| counter.0 += 1);
143 let total = state.update(|counter: &mut Counter| {
144 counter.0 += 1;
145 counter.0
146 });
147 assert_eq!(total, 2);
148 state.clear();
149 assert_eq!(state.get::<Counter>(), None);
150 }
151}