1use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
4
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7
8use crate::error::{Error, JsonValidationError, Result};
9use crate::types::{JsonObject, JsonValue};
10
11#[derive(Debug, Clone, Default)]
26pub struct StateStore {
27 state: Arc<RwLock<JsonObject>>,
28}
29
30impl StateStore {
31 pub fn new() -> Self {
33 Self::default()
34 }
35
36 pub(crate) fn downgrade(&self) -> std::sync::Weak<RwLock<JsonObject>> {
38 Arc::downgrade(&self.state)
39 }
40
41 pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
47 let Some(value) = self.get_value(key) else {
48 return Ok(None);
49 };
50 decode(key, value).map(Some)
51 }
52
53 #[must_use]
55 pub fn get_value(&self, key: &str) -> Option<JsonValue> {
56 self.read().get(key).cloned()
57 }
58
59 pub fn set(&self, key: impl Into<String>, value: impl Serialize) -> Result<()> {
65 let key = key.into();
66 let value = encode(&key, value)?;
67 self.write().insert(key, value);
68 Ok(())
69 }
70
71 pub fn update<T, F>(&self, key: impl Into<String>, f: F) -> Result<()>
90 where
91 T: Serialize + DeserializeOwned,
92 F: FnOnce(Option<T>) -> T,
93 {
94 let key = key.into();
95 let mut state = self.write();
96 let current = state.get(&key).cloned().map(|value| decode(&key, value)).transpose()?;
97 let value = encode(&key, f(current))?;
98 state.insert(key, value);
99 Ok(())
100 }
101
102 pub fn delete(&self, key: &str) {
104 self.write().shift_remove(key);
105 }
106
107 pub fn clear(&self) {
109 self.write().clear();
110 }
111
112 #[must_use]
114 pub fn get_all(&self) -> JsonObject {
115 self.read().clone()
116 }
117
118 #[must_use]
120 pub fn keys(&self) -> Vec<String> {
121 self.read().keys().cloned().collect()
122 }
123
124 #[must_use]
126 pub fn snapshot(&self) -> Self {
127 Self::from(self.get_all())
128 }
129
130 #[allow(dead_code, reason = "the agent commits a model call's model state with it")]
132 pub(crate) fn replace_with(&self, other: &Self) {
133 let state = other.get_all();
134 *self.write() = state;
135 }
136
137 #[allow(dead_code, reason = "snapshots and sessions persist state with it")]
139 pub(crate) fn to_json(&self) -> JsonValue {
140 JsonValue::Object(self.get_all())
141 }
142
143 #[allow(dead_code, reason = "snapshots and sessions restore state with it")]
145 pub(crate) fn load_json(&self, json: JsonValue) {
146 let state = match json {
147 JsonValue::Object(map) => map,
148 _ => JsonObject::new(),
149 };
150 *self.write() = state;
151 }
152
153 fn read(&self) -> RwLockReadGuard<'_, JsonObject> {
154 self.state.read().unwrap_or_else(PoisonError::into_inner)
155 }
156
157 fn write(&self) -> RwLockWriteGuard<'_, JsonObject> {
158 self.state.write().unwrap_or_else(PoisonError::into_inner)
159 }
160}
161
162fn encode(key: &str, value: impl Serialize) -> Result<JsonValue> {
163 serde_json::to_value(value).map_err(|error| {
164 JsonValidationError::new(format!("value for key \"{key}\" cannot be serialized: {error}")).into()
165 })
166}
167
168fn decode<T: DeserializeOwned>(key: &str, value: JsonValue) -> Result<T> {
169 serde_json::from_value(value).map_err(|error| {
170 Error::other(format!(
171 "value for key \"{key}\" does not deserialize into the requested type: {error}"
172 ))
173 })
174}
175
176impl From<JsonObject> for StateStore {
177 fn from(state: JsonObject) -> Self {
178 Self {
179 state: Arc::new(RwLock::new(state)),
180 }
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use std::collections::BTreeMap;
187
188 use serde::Deserialize;
189 use serde_json::json;
190
191 use super::*;
192
193 fn store(value: JsonValue) -> StateStore {
194 match value {
195 JsonValue::Object(map) => StateStore::from(map),
196 _ => panic!("not an object"),
197 }
198 }
199
200 #[derive(Debug, PartialEq, Serialize, Deserialize)]
201 struct User {
202 name: String,
203 age: u32,
204 }
205
206 #[test]
207 fn creates_empty_state_when_no_initial_state_provided() {
208 assert!(StateStore::new().keys().is_empty());
209 }
210
211 #[test]
212 fn creates_state_with_initial_values() {
213 let state = store(json!({"key1": "value1", "key2": 42}));
214 assert_eq!(state.get_value("key1"), Some(json!("value1")));
215 assert_eq!(state.get_value("key2"), Some(json!(42)));
216 }
217
218 #[test]
219 fn stores_deep_copy_of_initial_state() {
220 let mut initial = json!({"nested": {"value": "test"}});
221 let state = store(initial.clone());
222 initial["nested"]["value"] = json!("changed");
223 assert_eq!(state.get_value("nested"), Some(json!({"value": "test"})));
224 }
225
226 #[test]
227 fn returns_undefined_when_key_does_not_exist() {
228 let state = StateStore::new();
229 assert_eq!(state.get_value("nonexistent"), None);
230 assert_eq!(state.get::<String>("nonexistent").unwrap(), None);
231 }
232
233 #[test]
234 fn returns_value_when_key_exists() {
235 let state = store(json!({"key1": "value1"}));
236 assert_eq!(state.get::<String>("key1").unwrap().as_deref(), Some("value1"));
237 }
238
239 #[test]
240 fn returns_deep_copy_that_cannot_mutate_stored_state() {
241 let state = store(json!({"nested": {"value": "test"}}));
242 let mut retrieved = state.get_value("nested").unwrap();
243 retrieved["value"] = json!("changed");
244 assert_eq!(state.get_value("nested"), Some(json!({"value": "test"})));
245 }
246
247 #[test]
248 fn infers_correct_type_with_generic_state_interface() {
249 let state = store(json!({"user": {"name": "John", "age": 30}, "count": 5, "items": ["a", "b"]}));
250 let user: Option<User> = state.get("user").unwrap();
251 assert_eq!(
252 user,
253 Some(User {
254 name: "John".into(),
255 age: 30
256 })
257 );
258 assert_eq!(state.get::<u32>("count").unwrap(), Some(5));
259 assert_eq!(
260 state.get::<Vec<String>>("items").unwrap(),
261 Some(vec!["a".into(), "b".into()])
262 );
263 }
264
265 #[test]
266 fn returns_undefined_for_non_existent_key_with_typed_interface() {
267 let state = store(json!({"existing": "value"}));
268 assert_eq!(state.get::<String>("existing").unwrap().as_deref(), Some("value"));
269 assert_eq!(StateStore::new().get::<String>("existing").unwrap(), None);
270 }
271
272 #[test]
273 fn get_fails_when_the_value_does_not_deserialize_into_the_type() {
274 let state = store(json!({"count": "five"}));
275 let error = state.get::<u32>("count").unwrap_err();
276 assert!(
277 error
278 .to_string()
279 .starts_with("value for key \"count\" does not deserialize into the requested type: "),
280 "{error}"
281 );
282 }
283
284 #[test]
285 fn update_reads_and_writes_in_one_step() {
286 let state = StateStore::new();
287 state
288 .update("count", |count: Option<u32>| count.unwrap_or(0) + 1)
289 .unwrap();
290 state
291 .update("count", |count: Option<u32>| count.unwrap_or(0) + 1)
292 .unwrap();
293 assert_eq!(state.get_value("count"), Some(json!(2)));
294 }
295
296 #[test]
297 fn update_leaves_the_value_unchanged_when_it_does_not_decode() {
298 let state = store(json!({"count": "five"}));
299 let error = state
300 .update("count", |count: Option<u32>| count.unwrap_or(0) + 1)
301 .unwrap_err();
302 assert!(error.to_string().contains("\"count\""), "{error}");
303 assert_eq!(state.get_value("count"), Some(json!("five")));
304 }
305
306 #[test]
307 fn concurrent_updates_do_not_lose_writes() {
308 let state = StateStore::new();
309 let threads: Vec<_> = (0..8)
310 .map(|_| {
311 let state = state.clone();
312 std::thread::spawn(move || {
313 for _ in 0..100 {
314 state
315 .update("count", |count: Option<u32>| count.unwrap_or(0) + 1)
316 .unwrap();
317 }
318 })
319 })
320 .collect();
321 for thread in threads {
322 thread.join().unwrap();
323 }
324 assert_eq!(state.get::<u32>("count").unwrap(), Some(800));
325 }
326
327 #[test]
328 fn sets_string_number_boolean_null_object_and_array_values() {
329 let state = StateStore::new();
330 state.set("string", "value1").unwrap();
331 state.set("number", 42).unwrap();
332 state.set("boolean", true).unwrap();
333 state.set("null", JsonValue::Null).unwrap();
334 state.set("object", json!({"nested": "value"})).unwrap();
335 state.set("array", [1, 2, 3]).unwrap();
336 assert_eq!(
337 JsonValue::Object(state.get_all()),
338 json!({
339 "string": "value1",
340 "number": 42,
341 "boolean": true,
342 "null": null,
343 "object": {"nested": "value"},
344 "array": [1, 2, 3],
345 })
346 );
347 }
348
349 #[test]
350 fn overwrites_existing_value() {
351 let state = store(json!({"key1": "old"}));
352 state.set("key1", "new").unwrap();
353 assert_eq!(state.get_value("key1"), Some(json!("new")));
354 }
355
356 #[test]
357 fn set_stores_deep_copy_that_cannot_mutate_stored_state() {
358 let state = StateStore::new();
359 let mut value = json!({"nested": {"value": "test"}});
360 state.set("key1", &value).unwrap();
361 value["nested"]["value"] = json!("changed");
362 assert_eq!(state.get_value("key1"), Some(json!({"nested": {"value": "test"}})));
363 }
364
365 #[test]
366 fn throws_error_for_a_value_that_cannot_be_serialized() {
367 let state = StateStore::new();
368 let value = BTreeMap::from([((1, 2), "tuple key")]);
369 let error = state.set("key1", value).unwrap_err();
370 assert_eq!(error.name(), "JsonValidationError");
371 assert!(
372 error
373 .to_string()
374 .starts_with("value for key \"key1\" cannot be serialized: "),
375 "{error}"
376 );
377 assert_eq!(state.get_value("key1"), None);
378 }
379
380 #[test]
381 fn accepts_typed_value_with_generic_state_interface() {
382 let state = StateStore::new();
383 state
384 .set(
385 "user",
386 User {
387 name: "Alice".into(),
388 age: 25,
389 },
390 )
391 .unwrap();
392 state.set("count", 10).unwrap();
393 assert_eq!(state.get_value("user"), Some(json!({"name": "Alice", "age": 25})));
394 assert_eq!(state.get_value("count"), Some(json!(10)));
395 }
396
397 #[test]
398 fn removes_existing_key() {
399 let state = store(json!({"key1": "value1", "key2": "value2"}));
400 state.delete("key1");
401 assert_eq!(state.get_value("key1"), None);
402 assert_eq!(state.get_value("key2"), Some(json!("value2")));
403 }
404
405 #[test]
406 fn does_not_throw_error_for_non_existent_key() {
407 StateStore::new().delete("nonexistent");
408 }
409
410 #[test]
411 fn delete_supports_typed_usage_with_generic_state_interface() {
412 let state = store(json!({"user": {"name": "Alice"}, "count": 5}));
413 state.delete("user");
414 assert_eq!(state.get::<User>("user").unwrap(), None);
415 assert_eq!(state.get::<u32>("count").unwrap(), Some(5));
416 }
417
418 #[test]
419 fn removes_all_values() {
420 let state = store(json!({"key1": "value1", "key2": "value2"}));
421 state.clear();
422 assert!(state.keys().is_empty());
423 assert_eq!(state.get_value("key1"), None);
424 assert_eq!(state.get_value("key2"), None);
425 }
426
427 #[test]
428 fn clear_works_on_empty_state() {
429 let state = StateStore::new();
430 state.clear();
431 assert!(state.keys().is_empty());
432 }
433
434 #[test]
435 fn returns_object_with_all_state() {
436 let state = store(json!({"key1": "value1", "key2": 42}));
437 assert_eq!(
438 JsonValue::Object(state.get_all()),
439 json!({"key1": "value1", "key2": 42})
440 );
441 }
442
443 #[test]
444 fn returns_empty_object_for_empty_state() {
445 assert!(StateStore::new().get_all().is_empty());
446 }
447
448 #[test]
449 fn keys_returns_empty_array_for_empty_state() {
450 assert!(StateStore::new().keys().is_empty());
451 }
452
453 #[test]
454 fn returns_array_of_all_keys() {
455 let state = store(json!({"key1": "value1", "key2": "value2"}));
456 assert_eq!(state.keys(), vec!["key1", "key2"]);
457 }
458
459 #[test]
460 fn returns_deep_copy_of_state() {
461 let state = store(json!({"key1": "value1", "nested": {"deep": true}}));
462 let mut json = state.to_json();
463 assert_eq!(json, json!({"key1": "value1", "nested": {"deep": true}}));
464 json["nested"]["deep"] = json!(false);
465 assert_eq!(state.get_value("nested"), Some(json!({"deep": true})));
466 }
467
468 #[test]
469 fn replaces_state_with_json_data() {
470 let state = store(json!({"old": "data"}));
471 state.load_json(json!({"new": "data", "count": 42}));
472 assert_eq!(state.to_json(), json!({"new": "data", "count": 42}));
473 }
474
475 #[test]
476 fn clears_state_when_given_non_object() {
477 let state = store(json!({"key": "value"}));
478 state.load_json(JsonValue::Null);
479 assert_eq!(state.to_json(), json!({}));
480 }
481
482 #[test]
483 fn clones_share_state_and_snapshots_do_not() {
484 let state = StateStore::new();
485 let shared = state.clone();
486 let snapshot = state.snapshot();
487 shared.set("key", 1).unwrap();
488 assert_eq!(state.get_value("key"), Some(json!(1)));
489 assert_eq!(snapshot.get_value("key"), None);
490 snapshot.set("other", 2).unwrap();
491 assert_eq!(state.get_value("other"), None);
492 }
493
494 #[test]
495 fn replace_with_copies_another_store() {
496 let state = store(json!({"old": 1}));
497 let next = store(json!({"responseId": "r1"}));
498 state.replace_with(&next);
499 next.set("later", true).unwrap();
500 assert_eq!(state.to_json(), json!({"responseId": "r1"}));
501 }
502}