Skip to main content

kardia_core/
context.rs

1use std::fmt;
2use std::sync::Arc;
3
4use serde::de::DeserializeOwned;
5use serde_json::Value;
6
7use crate::key::{FiberId, Key, RealmId};
8use crate::root::RootInner;
9use crate::scope::{Overlay, Scope, ScopeKind};
10
11/// A cheap, clonable handle to a position in the runtime: a root, the fiber
12/// that owns effects created through it, and its derivation scope
13/// (isolation and interception overlays).
14#[derive(Clone)]
15pub struct Context {
16    pub(crate) root: Arc<RootInner>,
17    pub(crate) fiber: FiberId,
18    pub(crate) scope: Arc<Scope>,
19}
20
21impl Context {
22    /// Creates a new root context. Its fiber is the always-active root fiber.
23    #[allow(clippy::new_without_default)]
24    pub fn new() -> Self {
25        let root = RootInner::new();
26        let scope = root.with(|st| st.fibers[&FiberId::ROOT].scope.clone());
27        Self { root, fiber: FiberId::ROOT, scope }
28    }
29
30    pub(crate) fn of_root(root: &Arc<RootInner>) -> Self {
31        let scope = root.with(|st| st.fibers[&FiberId::ROOT].scope.clone());
32        Self { root: root.clone(), fiber: FiberId::ROOT, scope }
33    }
34
35    pub fn fiber_id(&self) -> FiberId {
36        self.fiber
37    }
38
39    pub fn is_root(&self) -> bool {
40        self.fiber == FiberId::ROOT
41    }
42
43    /// Whether both contexts belong to the same root.
44    pub fn same_root(&self, other: &Context) -> bool {
45        Arc::ptr_eq(&self.root, &other.root)
46    }
47
48    /// Whether both handles denote the very same derived context.
49    pub fn ptr_eq(&self, other: &Context) -> bool {
50        Arc::ptr_eq(&self.scope, &other.scope)
51    }
52
53    /// The root context.
54    pub fn root(&self) -> Context {
55        Self::of_root(&self.root)
56    }
57
58    /// Derives a context in which `key` lives in a fresh, private realm.
59    pub fn isolate(&self, key: impl Into<Key>) -> Context {
60        self.isolate_in(key, RealmId::new())
61    }
62
63    /// Derives a context in which `key` lives in the given (shared) realm.
64    pub fn isolate_in(&self, key: impl Into<Key>, realm: RealmId) -> Context {
65        self.derive(ScopeKind::Isolate(key.into(), realm))
66    }
67
68    /// Derives a context carrying interception metadata for `key`.
69    pub fn intercept(&self, key: impl Into<Key>, meta: Value) -> Context {
70        self.derive(ScopeKind::Intercept(key.into(), meta))
71    }
72
73    /// Derives a context with its own mutable isolation and interception
74    /// tables (see [`Overlay`]).
75    pub fn extend(&self) -> Context {
76        self.extend_with(&Overlay::new())
77    }
78
79    /// Derives a context backed by a given overlay; several contexts may
80    /// share one overlay.
81    pub fn extend_with(&self, overlay: &Arc<Overlay>) -> Context {
82        self.derive(ScopeKind::Overlay(overlay.clone()))
83    }
84
85    /// The overlay of this very context, if it was made by `extend`.
86    pub fn overlay(&self) -> Option<Arc<Overlay>> {
87        match &self.scope.kind {
88            ScopeKind::Overlay(overlay) => Some(overlay.clone()),
89            _ => None,
90        }
91    }
92
93    /// Re-attaches this context, with everything derived below it, under
94    /// `parent`. Like a re-pointed prototype, the returned handle belongs to
95    /// `parent`'s fiber.
96    pub fn reparent(&self, parent: &Context) -> Context {
97        self.scope.set_parent(parent.scope.clone());
98        Self { root: self.root.clone(), fiber: parent.fiber, scope: self.scope.clone() }
99    }
100
101    /// The overlay this context is directly derived from, if any.
102    pub fn parent_overlay(&self) -> Option<Arc<Overlay>> {
103        match &self.scope.parent()?.kind {
104            ScopeKind::Overlay(overlay) => Some(overlay.clone()),
105            _ => None,
106        }
107    }
108
109    /// The tag of the nearest tagged overlay on the derivation chain.
110    pub fn tag(&self) -> Option<u64> {
111        self.scope.tag()
112    }
113
114    /// Whether this context is derived from `ancestor` (or is it).
115    pub fn is_within(&self, ancestor: &Context) -> bool {
116        self.scope.is_within(&ancestor.scope)
117    }
118
119    /// Every key isolated somewhere on this context's derivation chain.
120    pub fn isolated_keys(&self) -> Vec<Key> {
121        self.scope.isolated_keys()
122    }
123
124    /// The realm `key` resolves to from this context, if it has one yet.
125    pub fn realm(&self, key: &str) -> Option<RealmId> {
126        self.root.with(|st| st.realm_of(&self.scope, key))
127    }
128
129    /// Whether this context isolates `key` itself rather than inheriting
130    /// the root realm.
131    pub fn has_isolation(&self, key: &str) -> bool {
132        self.scope.own_realm(key).is_some()
133    }
134
135    /// Interception metadata for `key` from the outermost context to this one.
136    pub fn intercepts(&self, key: &str) -> Vec<Value> {
137        self.scope.intercepts(key)
138    }
139
140    /// Interception metadata for `key`, merged right-biased and deserialized.
141    /// Malformed metadata yields the default.
142    pub fn intercept_meta<T: DeserializeOwned + Default>(&self, key: &str) -> T {
143        serde_json::from_value(merge_shallow(self.intercepts(key))).unwrap_or_default()
144    }
145
146    fn derive(&self, kind: ScopeKind) -> Context {
147        Self { root: self.root.clone(), fiber: self.fiber, scope: Scope::child(&self.scope, kind) }
148    }
149}
150
151/// Merges JSON objects key by key, later values winning (like `Object.assign`).
152pub fn merge_shallow(values: impl IntoIterator<Item = Value>) -> Value {
153    let mut result = serde_json::Map::new();
154    for value in values {
155        if let Value::Object(map) = value {
156            result.extend(map);
157        }
158    }
159    Value::Object(result)
160}
161
162impl fmt::Debug for Context {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        let name = self.root.with(|st| st.fiber_name(self.fiber));
165        write!(f, "Context <{name}>")
166    }
167}