Skip to main content

clm_rust_core/fiber/
context.rs

1//! Cordis Context and Fiber State Machine.
2//!
3//! Enforces:
4//! 1. The Empty Root Context (⊥)
5//! 2. 5-State Fiber Lifecycle (PENDING ➔ LOADING ➔ ACTIVE ➔ UNLOADING ➔ DISPOSED)
6//! 3. Demand-Driven Coeffects (@Inject)
7//! 4. Scoped Monadic Contexts & Algebraic Sub-Graph Isolation (ctx.user, ctx.channel, ctx.isolate)
8
9use super::disposable::DisposableList;
10use crate::layer0::fiber_transitions::{self as lifecycle, FiberBypass};
11pub use crate::layer0::fiber_transitions::FiberState;
12use dashmap::DashMap;
13use std::any::Any;
14use std::collections::HashSet;
15use std::sync::{Arc, Mutex};
16
17/// The table `step` reads: one profile's ordinary edges and its bypasses.
18pub struct FiberTable {
19    pub profile: &'static str,
20    pub valid: fn(&FiberState, &FiberState) -> bool,
21    /// The targets an ordinary transition may take from each state, in published names.
22    pub allowed: &'static [(&'static str, &'static [&'static str])],
23    pub bypasses: &'static [FiberBypass],
24}
25
26/// The generated table of this runtime's profile.
27pub const TABLE: FiberTable = FiberTable {
28    profile: lifecycle::PROFILE,
29    valid: lifecycle::valid_transition,
30    allowed: lifecycle::PUBLISHED_TRANSITIONS,
31    bypasses: lifecycle::BYPASSES,
32};
33
34/// What a caller asks of a fiber: move to `to` along an ordinary edge, or through a named bypass.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct FiberEvent {
37    pub to: FiberState,
38    pub bypass: Option<&'static FiberBypass>,
39}
40
41impl FiberEvent {
42    pub fn to(to: FiberState) -> Self {
43        Self { to, bypass: None }
44    }
45
46    pub fn bypass(bypass: &'static FiberBypass, to: FiberState) -> Self {
47        Self { to, bypass: Some(bypass) }
48    }
49}
50
51/// Work the caller owes once a move is stored.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum FiberEffect {
54    UnwindDisposables,
55}
56
57const NO_EFFECTS: &[FiberEffect] = &[];
58const UNWIND: &[FiberEffect] = &[FiberEffect::UnwindDisposables];
59
60/// A legal move: the state to store and the effects to apply.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Moved {
63    pub state: FiberState,
64    pub effects: &'static [FiberEffect],
65}
66
67/// A move the table does not carry; the state is unchanged.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Illegal {
70    pub profile: &'static str,
71    pub from: FiberState,
72    pub to: FiberState,
73    pub allowed: &'static [&'static str],
74}
75
76impl std::fmt::Display for Illegal {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        write!(
79            f,
80            "illegal fiber transition {} -> {} under the {} profile; allowed targets: {:?}",
81            self.from.published_name(),
82            self.to.published_name(),
83            self.profile,
84            self.allowed
85        )
86    }
87}
88
89/// Decides one lifecycle move. Reads only its arguments: no clock, no lock, no fiber.
90#[inline]
91pub fn step(table: &FiberTable, state: &FiberState, event: FiberEvent) -> Result<Moved, Illegal> {
92    let FiberEvent { to, bypass } = event;
93    let effects = if let Some(bypass) = bypass {
94        let fires = table.bypasses.contains(bypass)
95            && bypass.sources.contains(&state.name())
96            && bypass.targets.contains(&to.name());
97        fires.then_some(if bypass.drains { UNWIND } else { NO_EFFECTS })
98    } else {
99        (table.valid)(state, &to).then_some(NO_EFFECTS)
100    };
101    let Some(effects) = effects else {
102        let allowed = table
103            .allowed
104            .iter()
105            .find(|(from, _)| *from == state.published_name())
106            .map_or(NO_TARGETS, |(_, targets)| *targets);
107        return Err(Illegal { profile: table.profile, from: state.clone(), to, allowed });
108    };
109    Ok(Moved { state: to, effects })
110}
111
112/// Decides `event` with `step` and stores the state it returns. The only writer of a fiber's state.
113fn store(state: &mut FiberState, event: FiberEvent) -> Result<&'static [FiberEffect], Illegal> {
114    let moved = step(&TABLE, state, event)?;
115    *state = moved.state;
116    Ok(moved.effects)
117}
118
119const NO_TARGETS: &[&str] = &[];
120const DISPOSAL_ERRORS: &str = "Disposal errors encountered";
121
122/// A Cordis execution Fiber representing an isolated plugin, agent task, or service.
123pub struct Fiber {
124    pub id: String,
125    state: Mutex<FiberState>,
126    pub required_coeffects: HashSet<String>,
127    pub satisfied_coeffects: Mutex<HashSet<String>>,
128    pub disposables: Mutex<DisposableList>,
129    pub clm_ast: Mutex<Option<serde_json::Value>>,
130}
131
132impl Fiber {
133    pub fn new(id: impl Into<String>, required_coeffects: Vec<String>) -> Self {
134        let coeffects_set: HashSet<String> = required_coeffects.into_iter().collect();
135        Self {
136            id: id.into(),
137            state: Mutex::new(lifecycle::initial_state(coeffects_set.is_empty())),
138            required_coeffects: coeffects_set,
139            satisfied_coeffects: Mutex::new(HashSet::new()),
140            disposables: Mutex::new(DisposableList::new()),
141            clm_ast: Mutex::new(None),
142        }
143    }
144
145    /// The profile whose table this fiber's moves are decided by.
146    pub fn profile(&self) -> &'static str {
147        TABLE.profile
148    }
149
150    fn fire(&self, event: FiberEvent) -> Result<&'static [FiberEffect], Illegal> {
151        store(&mut self.state.lock().unwrap(), event)
152    }
153
154    /// Checks if all declared coeffects are satisfied and transitions to ACTIVE.
155    pub fn try_activate(&self) -> bool {
156        let mut state = self.state.lock().unwrap();
157        if *state != FiberState::Pending && *state != FiberState::Loading {
158            return *state == FiberState::Active;
159        }
160
161        let satisfied = self.satisfied_coeffects.lock().unwrap();
162        self.required_coeffects.is_subset(&satisfied)
163            && store(&mut state, FiberEvent::to(FiberState::Active)).is_ok()
164    }
165
166    /// Satisfies a specific coeffect requirement.
167    pub fn satisfy_coeffect(&self, coeffect: &str) -> bool {
168        self.satisfied_coeffects.lock().unwrap().insert(coeffect.to_string());
169        self.try_activate()
170    }
171
172    /// Registers a reversible cleanup effect with this fiber.
173    pub fn register_disposable<F>(&self, cleanup: F)
174    where
175        F: FnOnce() -> Result<(), String> + Send + 'static,
176    {
177        self.disposables.lock().unwrap().push(cleanup);
178    }
179
180    /// Transitions the Fiber to a new state along an ordinary edge of its profile.
181    pub fn transition_to(&self, new_state: FiberState) -> Result<(), String> {
182        self.fire(FiberEvent::to(new_state)).map(drop).map_err(|refused| refused.to_string())
183    }
184
185    /// Returns the current lifecycle state of the Fiber.
186    pub fn get_state(&self) -> FiberState {
187        self.state.lock().unwrap().clone()
188    }
189
190    /// Pauses the fiber execution, preparing for HMR or state snapshot.
191    pub fn pause(&self) -> Result<(), String> {
192        self.transition_to(FiberState::Paused)
193    }
194
195    /// Activates or resumes the fiber.
196    pub fn activate(&self) -> Result<(), String> {
197        self.transition_to(FiberState::Active)
198    }
199
200    /// Suspends the fiber execution awaiting a delimited continuation.
201    pub fn suspend(&self) -> Result<(), String> {
202        self.transition_to(FiberState::Suspended)
203    }
204
205    /// Resumes the fiber execution from suspended state back to Active.
206    pub fn resume(&self) -> Result<(), String> {
207        self.transition_to(FiberState::Active)
208    }
209
210    /// Unwinds disposables in LIFO order without setting Disposed state.
211    pub fn unwind_disposables(&self) -> Result<(), Vec<String>> {
212        let disposers = std::mem::take(&mut *self.disposables.lock().unwrap());
213        disposers.dispose()
214    }
215
216    /// Stores the CLM AST in this fiber.
217    pub fn set_ast(&self, ast: serde_json::Value) {
218        *self.clm_ast.lock().unwrap() = Some(ast);
219    }
220
221    /// Retrieves the stored CLM AST if present.
222    pub fn get_ast(&self) -> Option<serde_json::Value> {
223        self.clm_ast.lock().unwrap().clone()
224    }
225
226    /// Transitions the Fiber to DISPOSED, executing all disposables in strict LIFO order.
227    /// A fiber that is already disposed stays disposed and reports success.
228    pub fn dispose(&self) -> Result<(), Vec<String>> {
229        let fired = self.fire(FiberEvent::bypass(&lifecycle::RUST_DISPOSE, FiberState::Unloading));
230        if let Err(refused) = &fired {
231            if refused.from == FiberState::Disposed {
232                return Ok(());
233            }
234        }
235        let effects = fired.map_err(|refused| vec![refused.to_string()])?;
236        let unwound = if effects.contains(&FiberEffect::UnwindDisposables) {
237            self.unwind_disposables()
238        } else {
239            Ok(())
240        };
241        let end = if unwound.is_ok() {
242            FiberState::Disposed
243        } else {
244            FiberState::Failed(DISPOSAL_ERRORS.to_string())
245        };
246        let sealed = self.fire(FiberEvent::to(end)).map(drop).map_err(|refused| vec![refused.to_string()]);
247        unwound.and(sealed)
248    }
249}
250
251/// Where a context draws a fresh identifier. The default reads the clock.
252pub type IdSource = Arc<dyn Fn() -> String + Send + Sync>;
253
254/// A Scoped Monadic Context for Cordis plugin execution.
255#[derive(Clone)]
256pub struct Context {
257    pub scope_id: String,
258    pub services: Arc<DashMap<String, Arc<dyn Any + Send + Sync>>>,
259    pub fibers: Arc<DashMap<String, Arc<Fiber>>>,
260    ids: IdSource,
261}
262
263impl Context {
264    /// Creates the sovereign Empty Root Context (⊥) with zero privileged state.
265    pub fn root() -> Self {
266        Self::root_with_ids(Arc::new(crate::utils::clock_hex_id))
267    }
268
269    /// The root context with a caller-supplied identifier source, so a runner can fix the identifiers.
270    pub fn root_with_ids(ids: IdSource) -> Self {
271        Self {
272            scope_id: "root".to_string(),
273            services: Arc::new(DashMap::new()),
274            fibers: Arc::new(DashMap::new()),
275            ids,
276        }
277    }
278
279    /// A fresh identifier from this context's source.
280    pub fn fresh_id(&self) -> String {
281        (self.ids)()
282    }
283
284    /// Creates a scoped child context partitioned by user identity (Tenant Isolation).
285    pub fn user(&self, did: &str) -> Self {
286        Self {
287            scope_id: format!("{}/user:{}", self.scope_id, did),
288            services: self.services.clone(),
289            fibers: self.fibers.clone(),
290            ids: self.ids.clone(),
291        }
292    }
293
294    /// Creates a scoped child context partitioned by communication channel or session.
295    pub fn channel(&self, channel_id: &str) -> Self {
296        Self {
297            scope_id: format!("{}/channel:{}", self.scope_id, channel_id),
298            services: self.services.clone(),
299            fibers: self.fibers.clone(),
300            ids: self.ids.clone(),
301        }
302    }
303
304    /// Creates an isolated child sandbox with only the declared coeffects exposed.
305    pub fn isolate(&self, allowed_coeffects: &[&str]) -> Self {
306        let isolated_services = Arc::new(DashMap::new());
307        let allowed_set: HashSet<&str> = allowed_coeffects.iter().copied().collect();
308
309        for entry in self.services.iter() {
310            if allowed_set.contains(entry.key().as_str()) {
311                isolated_services.insert(entry.key().clone(), entry.value().clone());
312            }
313        }
314
315        Self {
316            scope_id: format!("{}/isolate:{}", self.scope_id, self.fresh_id()),
317            services: isolated_services,
318            fibers: Arc::new(DashMap::new()),
319            ids: self.ids.clone(),
320        }
321    }
322
323    /// Creates a masked child context with specific capabilities stripped.
324    pub fn mask(&self, denied_coeffects: &[&str]) -> Self {
325        let masked_services = Arc::new(DashMap::new());
326        let denied_set: HashSet<&str> = denied_coeffects.iter().copied().collect();
327
328        for entry in self.services.iter() {
329            if !denied_set.contains(entry.key().as_str()) {
330                masked_services.insert(entry.key().clone(), entry.value().clone());
331            }
332        }
333
334        Self {
335            scope_id: format!("{}/mask:{}", self.scope_id, self.fresh_id()),
336            services: masked_services,
337            fibers: Arc::new(DashMap::new()),
338            ids: self.ids.clone(),
339        }
340    }
341
342    /// Checks whether a specific coeffect capability is present in this context scope.
343    pub fn require(&self, coeffect: &str) -> bool {
344        self.services.contains_key(coeffect)
345    }
346
347    /// Provides a service capability into the context registry (alias for register_service).
348    pub fn provide<T: Send + Sync + 'static>(&self, name: &str, service: T) {
349        self.register_service(name, service);
350    }
351
352    /// Registers a service capability into the context registry.
353    pub fn register_service<T: Send + Sync + 'static>(&self, name: &str, service: T) {
354        self.services.insert(name.to_string(), Arc::new(service));
355
356        // Notify any pending fibers that this coeffect is now available
357        for fiber in self.fibers.iter() {
358            if fiber.required_coeffects.contains(name) {
359                fiber.satisfy_coeffect(name);
360            }
361        }
362    }
363
364    /// Retrieves a typed service capability from the registry.
365    pub fn get_service<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
366        self.services
367            .get(name)
368            .and_then(|any_arc| any_arc.clone().downcast::<T>().ok())
369    }
370
371    /// Mounts an MCard virtual filesystem into this context scope as a reactive coeffect (Sprint 191).
372    #[cfg(any(feature = "native", feature = "db"))]
373    pub fn mount_mcard_fs(&self, fs: crate::mcard_fs::MCardFileSystem) {
374        self.provide("mcard_fs", fs);
375    }
376
377    /// Retrieves the mounted MCard virtual filesystem if available.
378    #[cfg(any(feature = "native", feature = "db"))]
379    pub fn mcard_fs(&self) -> Option<Arc<crate::mcard_fs::MCardFileSystem>> {
380        self.get_service::<crate::mcard_fs::MCardFileSystem>("mcard_fs")
381    }
382
383    /// Ephemerally mounts an MCard virtual filesystem scoped to `prefix` on a Fiber,
384    /// registering LIFO cleanup on the fiber's DisposableList.
385    #[cfg(any(feature = "native", feature = "db"))]
386    pub fn mount_ephemeral_mcard_fs(
387        &self,
388        fiber_id: &str,
389        prefix: &str,
390    ) -> Result<crate::mcard_fs::MCardFileSystem, String> {
391        let fs = self.mcard_fs().ok_or_else(|| "mcard_fs service not mounted in context".to_string())?;
392        let fiber = self.get_fiber(fiber_id).ok_or_else(|| format!("fiber '{}' not found", fiber_id))?;
393        fs.ephemeral_mount(&fiber, prefix)
394            .map_err(|e| e.to_string())
395    }
396
397    /// Instantiates and registers a new Fiber within this context.
398    pub fn spawn_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Arc<Fiber> {
399        let fiber = Arc::new(Fiber::new(id, required_coeffects));
400
401        // Immediately satisfy any coeffects that already exist in this context
402        for coeffect in &fiber.required_coeffects {
403            if self.services.contains_key(coeffect) {
404                fiber.satisfy_coeffect(coeffect);
405            }
406        }
407
408        self.fibers.insert(id.to_string(), fiber.clone());
409        fiber
410    }
411
412    /// Looks up an active fiber by id.
413    pub fn get_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
414        self.fibers.get(id).map(|f| f.clone())
415    }
416
417    /// Lists all active fibers in this context.
418    pub fn list_fibers(&self) -> Vec<Arc<Fiber>> {
419        self.fibers.iter().map(|entry| entry.value().clone()).collect()
420    }
421
422    /// Creates and registers a new Fiber within this context.
423    pub fn create_fiber(&self, id: &str, required_coeffects: Vec<String>) -> Result<Arc<Fiber>, String> {
424        Ok(self.spawn_fiber(id, required_coeffects))
425    }
426
427    /// Removes an active fiber from the registry.
428    pub fn remove_fiber(&self, id: &str) -> Option<Arc<Fiber>> {
429        self.fibers.remove(id).map(|(_, f)| f)
430    }
431
432    /// Disposes all fibers associated with this context scope.
433    pub fn dispose(&self) -> Result<(), Vec<String>> {
434        let mut errors = Vec::new();
435        for fiber in self.fibers.iter() {
436            if let Err(mut e) = fiber.dispose() {
437                errors.append(&mut e);
438            }
439        }
440        if errors.is_empty() {
441            Ok(())
442        } else {
443            Err(errors)
444        }
445    }
446}
447
448#[cfg(test)]
449#[path = "context_tests.rs"]
450mod tests;