Skip to main content

tembra_core/context_values/
frames.rs

1//! Immutable frames retained by their creating operation and live consumers.
2
3use super::{ContextContract, ContextValue, invalid};
4use crate::{Code, Error, Host, Id, Reason, Result};
5
6pub(crate) struct ContextFrame {
7    pub root: Id,
8    pub parent: Id,
9    pub depth: usize,
10    references: usize,
11    pub value: FrameValue,
12}
13
14/// Application metadata and private execution ancestry share the same retained frame lifetime.
15pub(crate) enum FrameValue {
16    Binding(ContextContract, ContextValue),
17    Execution(Id),
18}
19
20impl crate::host::Inner {
21    fn push_frame(
22        &mut self,
23        root: Id,
24        parent: Id,
25        call: Option<Id>,
26        value: FrameValue,
27    ) -> Result<Id> {
28        let depth = if parent == 0 {
29            1
30        } else {
31            self.context_frames[&parent].depth + 1
32        };
33        if depth > 64 || self.roots[&root].contexts.len() >= 4096 {
34            return Err(Error::new(
35                Code::Exhausted,
36                Reason::Context,
37                "context depth or frame limit reached",
38            ));
39        }
40        let id = self.id()?;
41        self.retain_frame(parent);
42        if let Some(call) = call {
43            self.call_contexts.entry(call).or_default().push(id);
44        }
45        self.context_frames.insert(
46            id,
47            ContextFrame {
48                root,
49                parent,
50                depth,
51                references: 1,
52                value,
53            },
54        );
55        self.roots
56            .get_mut(&root)
57            .expect("checked root")
58            .contexts
59            .insert(id);
60        self.context_peak = self.context_peak.max(self.context_frames.len());
61        Ok(id)
62    }
63
64    /// Retain a nonempty frame for a call or child frame.
65    pub(crate) fn retain_frame(&mut self, frame: Id) {
66        if frame != 0 {
67            self.context_frames
68                .get_mut(&frame)
69                .expect("validated frame")
70                .references += 1;
71        }
72    }
73
74    /// Return opaque leases for destruction after the kernel borrow is released.
75    pub(crate) fn release_frame(
76        &mut self,
77        mut id: Id,
78        leases: &mut Vec<crate::OpaqueContextValue>,
79    ) {
80        while id != 0 {
81            let frame = self.context_frames.get_mut(&id).expect("retained frame");
82            frame.references -= 1;
83            if frame.references != 0 {
84                break;
85            }
86            let frame = self.context_frames.remove(&id).expect("unreferenced frame");
87            self.roots
88                .get_mut(&frame.root)
89                .expect("frame retains root")
90                .contexts
91                .remove(&id);
92            if let FrameValue::Binding(_, ContextValue::Opaque(lease)) = frame.value {
93                leases.push(lease);
94            }
95            id = frame.parent;
96        }
97    }
98
99    /// Require a frame owned by this root, or the empty frame.
100    pub(crate) fn check_frame(&self, root: Id, frame: Id) -> Result<()> {
101        if frame != 0
102            && self
103                .context_frames
104                .get(&frame)
105                .is_none_or(|value| value.root != root)
106        {
107            return Err(invalid(
108                "context frame belongs to another root or has expired",
109            ));
110        }
111        Ok(())
112    }
113}
114
115impl Host {
116    /// Derive a frame retained by its creator and admitted consumers.
117    pub fn derive_context(
118        &self,
119        root: Id,
120        parent: Id,
121        call: Option<Id>,
122        key: ContextContract,
123        value: ContextValue,
124    ) -> Result<Id> {
125        let mut inner = self.inner.borrow_mut();
126        inner.check_root(root)?;
127        inner.check_frame(root, parent)?;
128        if call.is_some_and(|id| inner.calls.get(&id).is_none_or(|value| value.root != root)) {
129            return Err(invalid("originating invocation has ended"));
130        }
131        if let Some(call) = call {
132            inner.check_uncancelled(call)?;
133        }
134        if key.name.is_empty()
135            || key.name.len() > 256
136            || key.version == 0
137            || key.kind != value.kind()
138            || matches!(&value, ContextValue::Text(value) if value.len() > 4096)
139            || matches!(&value, ContextValue::Integer(value) if !(-9_007_199_254_740_991..=9_007_199_254_740_991).contains(value))
140        {
141            return Err(invalid("invalid context contract or value"));
142        }
143        let identity = (key.name.clone(), key.version);
144        if inner
145            .context_contracts
146            .get(&identity)
147            .is_some_and(|kind| *kind != key.kind)
148        {
149            return Err(invalid("incompatible context key contract"));
150        }
151        if !inner.context_contracts.contains_key(&identity) && inner.context_contracts.len() >= 1024
152        {
153            return Err(Error::new(
154                Code::Exhausted,
155                Reason::Context,
156                "context key limit reached",
157            ));
158        }
159        let kind = key.kind;
160        let id = inner.push_frame(root, parent, call, FrameValue::Binding(key, value))?;
161        inner.context_contracts.insert(identity, kind);
162        Ok(id)
163    }
164
165    /// Enter the actual isolated revision admitted by this invocation, without application keys.
166    /// The realm is derived by the kernel; callers cannot select another heap's identity.
167    pub fn enter_execution(&self, call: Id, parent: Id) -> Result<Id> {
168        let mut inner = self.inner.borrow_mut();
169        let invocation = inner
170            .calls
171            .get(&call)
172            .ok_or_else(|| invalid("originating invocation has ended"))?;
173        let root = invocation.root;
174        let realm = invocation.orb;
175        inner.check_uncancelled(call)?;
176        inner.check_root(root)?;
177        inner.check_frame(root, parent)?;
178        if !inner
179            .orbs
180            .get(&realm)
181            .is_some_and(|orb| orb.declaration.isolated)
182        {
183            return Err(invalid("execution requires an isolated revision"));
184        }
185        let mut current = parent;
186        while current != 0 {
187            let frame = &inner.context_frames[&current];
188            if matches!(frame.value, FrameValue::Execution(id) if id == realm) {
189                return Err(invalid(
190                    "causal reentry into the same interpreter is unsupported",
191                ));
192            }
193            current = frame.parent;
194        }
195        inner.push_frame(root, parent, Some(call), FrameValue::Execution(realm))
196    }
197
198    /// Read the nearest binding and refuse a mismatched contract.
199    pub fn context_value(
200        &self,
201        root: Id,
202        mut frame: Id,
203        key: &ContextContract,
204    ) -> Result<Option<ContextValue>> {
205        let inner = self.inner.borrow();
206        inner.check_root(root)?;
207        inner.check_frame(root, frame)?;
208        while frame != 0 {
209            let node = &inner.context_frames[&frame];
210            if let FrameValue::Binding(contract, value) = &node.value
211                && contract.name == key.name
212                && contract.version == key.version
213            {
214                if contract.kind != key.kind {
215                    return Err(invalid("incompatible context key contract"));
216                }
217                return Ok(Some(value.clone()));
218            }
219            frame = node.parent;
220        }
221        Ok(None)
222    }
223
224    /// Read live frames, peak frames and retained key contracts.
225    pub fn context_stats(&self) -> (usize, usize, usize) {
226        let inner = self.inner.borrow();
227        (
228            inner.context_frames.len(),
229            inner.context_peak,
230            inner.context_contracts.len(),
231        )
232    }
233}