Skip to main content

services/
session_values.rs

1//! Ultron session values: the documents of the local services, host modules, task journal, definition registry,
2//! usage ledger and memory journal kept as values of the session itself (format-4 session journal), as the
3//! TypeScript worker keeps them (`createSessionTaskStore` at `ultron.tasks/root`, `createSessionModuleStore` at
4//! `ultron.module/<name>`, `createSessionDefinitionStore` at `ultron.definitions/root`, `createSessionUsageStore` at
5//! `ultron.usage/root`, the memory journal at `ultron.memory.state/root`, the local services at `ultron.local/<key>`).
6//!
7//! Because they are session values, resuming a session restores them, a tree fork copies them at the fork point,
8//! and deleting a fork leaves its source untouched: no state lives beside the session to drift from it (A07).
9
10use kernel::store::DocumentStore;
11use kernel_apis::artifacts::KeyedDocuments;
12use serde_json::Value;
13use session_journal::{Session, Write};
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::{Arc, Mutex};
16
17/// An open session shared by the stores over its values; clones share it.
18#[derive(Clone)]
19pub struct SessionValues {
20    session: Arc<Mutex<Session>>,
21    /// Set once the worker hands the session to a successor: the journal is the successor's from then on, so what
22    /// this worker would still write is dropped.
23    handed_over: Option<Arc<AtomicBool>>,
24}
25
26impl SessionValues {
27    pub fn new(session: Session) -> Self {
28        SessionValues {
29            session: Arc::new(Mutex::new(session)),
30            handed_over: None,
31        }
32    }
33
34    /// Values of a session another owner holds open (the session actor's); clones share it.
35    pub fn shared(session: Arc<Mutex<Session>>) -> Self {
36        SessionValues {
37            session,
38            handed_over: Some(Arc::new(AtomicBool::new(false))),
39        }
40    }
41
42    /// The worker hands the session to a successor: from now on every write through these values is dropped.
43    pub fn hand_over(&self) {
44        if let Some(flag) = &self.handed_over {
45            flag.store(true, Ordering::SeqCst);
46        }
47    }
48
49    pub fn handed_over(&self) -> bool {
50        self.handed_over
51            .as_ref()
52            .is_some_and(|flag| flag.load(Ordering::SeqCst))
53    }
54
55    pub fn session(&self) -> &Arc<Mutex<Session>> {
56        &self.session
57    }
58
59    pub fn get(&self, namespace: &str, key: &str) -> Option<Value> {
60        jsrt::sync::lock(&self.session).value(namespace, key).cloned()
61    }
62
63    pub fn set(&self, namespace: &str, key: &str, value: &Value) -> Result<(), String> {
64        if self.handed_over() {
65            return Ok(());
66        }
67        jsrt::sync::lock(&self.session)
68            .commit(&[Write::set(namespace, key, value.clone())])
69            .map(drop)
70    }
71
72    pub fn document(&self, namespace: &str, key: &str) -> SessionDocument {
73        SessionDocument {
74            values: self.clone(),
75            namespace: namespace.into(),
76            key: key.into(),
77        }
78    }
79
80    /// Keyed documents under `namespace` (the local services' `ultron.local`).
81    pub fn keyed(&self, namespace: &str) -> SessionKeyed {
82        SessionKeyed {
83            values: self.clone(),
84            namespace: namespace.into(),
85        }
86    }
87}
88
89/// One session value read and replaced whole (a module store, the task journal, the usage ledger).
90#[derive(Clone)]
91pub struct SessionDocument {
92    values: SessionValues,
93    namespace: String,
94    key: String,
95}
96
97impl DocumentStore for SessionDocument {
98    fn read(&self) -> Result<Option<Value>, String> {
99        Ok(self.values.get(&self.namespace, &self.key))
100    }
101    fn write(&self, document: &Value) -> Result<(), String> {
102        self.values.set(&self.namespace, &self.key, document)
103    }
104}
105
106/// Keyed session values of one namespace; a listing scans the keys with a prefix (`scanValues`).
107#[derive(Clone)]
108pub struct SessionKeyed {
109    values: SessionValues,
110    namespace: String,
111}
112
113impl KeyedDocuments for SessionKeyed {
114    fn get(&self, key: &str) -> Result<Option<Value>, String> {
115        Ok(self.values.get(&self.namespace, key))
116    }
117    fn set(&self, key: &str, value: &Value) -> Result<(), String> {
118        self.values.set(&self.namespace, key, value)
119    }
120    fn list(&self, prefix: &str) -> Result<Vec<(String, Value)>, String> {
121        Ok(jsrt::sync::lock(&self.values.session)
122            .state()
123            .scan_values(&self.namespace, prefix)
124            .into_iter()
125            .map(|stored| (stored.key.clone(), stored.value.clone()))
126            .collect())
127    }
128}