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 key: ContextContract,
12    pub value: ContextValue,
13}
14
15impl crate::host::Inner {
16    /// Retain a nonempty frame for a call or child frame.
17    pub(crate) fn retain_frame(&mut self, frame: Id) {
18        if frame != 0 {
19            self.context_frames
20                .get_mut(&frame)
21                .expect("validated frame")
22                .references += 1;
23        }
24    }
25
26    /// Return opaque leases for destruction after the kernel borrow is released.
27    pub(crate) fn release_frame(
28        &mut self,
29        mut id: Id,
30        leases: &mut Vec<crate::OpaqueContextValue>,
31    ) {
32        while id != 0 {
33            let frame = self.context_frames.get_mut(&id).expect("retained frame");
34            frame.references -= 1;
35            if frame.references != 0 {
36                break;
37            }
38            let frame = self.context_frames.remove(&id).expect("unreferenced frame");
39            self.roots
40                .get_mut(&frame.root)
41                .expect("frame retains root")
42                .contexts
43                .remove(&id);
44            if let ContextValue::Opaque(lease) = frame.value {
45                leases.push(lease);
46            }
47            id = frame.parent;
48        }
49    }
50
51    /// Require a frame owned by this root, or the empty frame.
52    pub(crate) fn check_frame(&self, root: Id, frame: Id) -> Result<()> {
53        if frame != 0
54            && self
55                .context_frames
56                .get(&frame)
57                .is_none_or(|value| value.root != root)
58        {
59            return Err(invalid(
60                "context frame belongs to another root or has expired",
61            ));
62        }
63        Ok(())
64    }
65}
66
67impl Host {
68    /// Derive a frame retained by its creator and admitted consumers.
69    pub fn derive_context(
70        &self,
71        root: Id,
72        parent: Id,
73        call: Option<Id>,
74        key: ContextContract,
75        value: ContextValue,
76    ) -> Result<Id> {
77        let mut inner = self.inner.borrow_mut();
78        inner.check_root(root)?;
79        inner.check_frame(root, parent)?;
80        if call.is_some_and(|id| inner.calls.get(&id).is_none_or(|value| value.root != root)) {
81            return Err(invalid("originating invocation has ended"));
82        }
83        let depth = if parent == 0 {
84            1
85        } else {
86            inner.context_frames[&parent].depth + 1
87        };
88        if depth > 64 || inner.roots[&root].contexts.len() >= 4096 {
89            return Err(Error::new(
90                Code::Exhausted,
91                Reason::Context,
92                "context depth or frame limit reached",
93            ));
94        }
95        if key.name.is_empty()
96            || key.name.len() > 256
97            || key.version == 0
98            || key.kind != value.kind()
99            || matches!(&value, ContextValue::Text(value) if value.len() > 4096)
100            || matches!(&value, ContextValue::Integer(value) if !(-9_007_199_254_740_991..=9_007_199_254_740_991).contains(value))
101        {
102            return Err(invalid("invalid context contract or value"));
103        }
104        let identity = (key.name.clone(), key.version);
105        if inner
106            .context_contracts
107            .get(&identity)
108            .is_some_and(|kind| *kind != key.kind)
109        {
110            return Err(invalid("incompatible context key contract"));
111        }
112        if !inner.context_contracts.contains_key(&identity) && inner.context_contracts.len() >= 1024
113        {
114            return Err(Error::new(
115                Code::Exhausted,
116                Reason::Context,
117                "context key limit reached",
118            ));
119        }
120        let id = inner.id()?;
121        inner.retain_frame(parent);
122        if let Some(call) = call {
123            inner.call_contexts.entry(call).or_default().push(id);
124        }
125        inner.context_contracts.insert(identity, key.kind);
126        inner.context_frames.insert(
127            id,
128            ContextFrame {
129                root,
130                parent,
131                depth,
132                references: 1,
133                key,
134                value,
135            },
136        );
137        inner
138            .roots
139            .get_mut(&root)
140            .expect("checked root")
141            .contexts
142            .insert(id);
143        inner.context_peak = inner.context_peak.max(inner.context_frames.len());
144        Ok(id)
145    }
146
147    /// Read the nearest binding and refuse a mismatched contract.
148    pub fn context_value(
149        &self,
150        root: Id,
151        mut frame: Id,
152        key: &ContextContract,
153    ) -> Result<Option<ContextValue>> {
154        let inner = self.inner.borrow();
155        inner.check_root(root)?;
156        inner.check_frame(root, frame)?;
157        while frame != 0 {
158            let node = &inner.context_frames[&frame];
159            if node.key.name == key.name && node.key.version == key.version {
160                if node.key.kind != key.kind {
161                    return Err(invalid("incompatible context key contract"));
162                }
163                return Ok(Some(node.value.clone()));
164            }
165            frame = node.parent;
166        }
167        Ok(None)
168    }
169
170    /// Read live frames, peak frames and retained key contracts.
171    pub fn context_stats(&self) -> (usize, usize, usize) {
172        let inner = self.inner.borrow();
173        (
174            inner.context_frames.len(),
175            inner.context_peak,
176            inner.context_contracts.len(),
177        )
178    }
179}