Skip to main content

kernel_apis/
artifacts.rs

1//! Keyed durable documents (`DurableDocumentStorage` of `ultron/local-services.ts`), in memory or in one JSON file:
2//! the store of schedules, local services and prompt schedules. (TypeScript's `artifacts.*` host requests over the
3//! same store are not ported.)
4
5use kernel::store::DocumentStore;
6use serde_json::{Map, Value};
7use std::path::PathBuf;
8use std::sync::Mutex;
9
10/// Keyed durable documents (`DurableDocumentStorage`): listings keep insertion order.
11pub trait KeyedDocuments: Send + Sync {
12    fn get(&self, key: &str) -> Result<Option<Value>, String>;
13    fn set(&self, key: &str, value: &Value) -> Result<(), String>;
14    /// Every `(key, value)` whose key starts with `prefix`, in insertion order.
15    fn list(&self, prefix: &str) -> Result<Vec<(String, Value)>, String>;
16}
17
18/// In-memory documents (a JavaScript `Map`).
19#[derive(Default)]
20pub struct MemoryKeyedDocuments {
21    values: Mutex<Map<String, Value>>,
22}
23
24impl KeyedDocuments for MemoryKeyedDocuments {
25    fn get(&self, key: &str) -> Result<Option<Value>, String> {
26        Ok(jsrt::sync::lock(&self.values).get(key).cloned())
27    }
28    fn set(&self, key: &str, value: &Value) -> Result<(), String> {
29        jsrt::sync::lock(&self.values).insert(key.into(), value.clone());
30        Ok(())
31    }
32    fn list(&self, prefix: &str) -> Result<Vec<(String, Value)>, String> {
33        Ok(jsrt::sync::lock(&self.values)
34            .iter()
35            .filter(|(key, _)| key.starts_with(prefix))
36            .map(|(key, value)| (key.clone(), value.clone()))
37            .collect())
38    }
39}
40
41/// Documents in one JSON file (`{key: value}` in insertion order), replaced atomically on every write.
42pub struct FileKeyedDocuments {
43    store: kernel::store::FileDocumentStore,
44    guard: Mutex<()>,
45}
46
47impl FileKeyedDocuments {
48    pub fn new(path: impl Into<PathBuf>) -> Self {
49        FileKeyedDocuments {
50            store: kernel::store::FileDocumentStore::new(path),
51            guard: Mutex::new(()),
52        }
53    }
54
55    fn read(&self) -> Result<Map<String, Value>, String> {
56        match self.store.read()? {
57            None => Ok(Map::new()),
58            Some(Value::Object(map)) => Ok(map),
59            Some(_) => Err("Invalid artifact document file".into()),
60        }
61    }
62}
63
64impl KeyedDocuments for FileKeyedDocuments {
65    fn get(&self, key: &str) -> Result<Option<Value>, String> {
66        let _guard = jsrt::sync::lock(&self.guard);
67        Ok(self.read()?.get(key).cloned())
68    }
69    fn set(&self, key: &str, value: &Value) -> Result<(), String> {
70        let _guard = jsrt::sync::lock(&self.guard);
71        let mut map = self.read()?;
72        map.insert(key.into(), value.clone());
73        self.store.write(&Value::Object(map))
74    }
75    fn list(&self, prefix: &str) -> Result<Vec<(String, Value)>, String> {
76        let _guard = jsrt::sync::lock(&self.guard);
77        Ok(self
78            .read()?
79            .into_iter()
80            .filter(|(key, _)| key.starts_with(prefix))
81            .collect())
82    }
83}