Skip to main content

tembra_core/host/
contexts.rs

1use super::*;
2use crate::Reason;
3
4impl Host {
5    /// Pin the current implementation version for a new operation root.
6    pub fn begin_root(&self, principal: impl Into<String>) -> Result<Id> {
7        let mut inner = self.inner.borrow_mut();
8        inner.open()?;
9        let version = inner.version;
10        inner.root(version, principal.into(), false)
11    }
12
13    /// Cleanup roots may call already-live dependencies during orderly shutdown.
14    pub fn cleanup_root(&self, principal: impl Into<String>) -> Result<Id> {
15        let mut inner = self.inner.borrow_mut();
16        if inner.closed {
17            return Err(Error::new(Code::Closed, Reason::Host, "host is closed"));
18        }
19        let version = inner.version;
20        inner.root(version, principal.into(), true)
21    }
22
23    /// Require an active root that has not been cancelled.
24    pub fn check_root(&self, root: Id) -> Result<()> {
25        self.inner.borrow().check_root(root).map(|_| ())
26    }
27
28    /// End logical admission while physical calls retain the root.
29    pub fn end_root(&self, root: Id) -> Result<()> {
30        let mut inner = self.inner.borrow_mut();
31        let record = inner
32            .roots
33            .get_mut(&root)
34            .ok_or_else(|| gone(Reason::Root))?;
35        record.active = false;
36        let leases = if record.calls == 0 {
37            inner.remove_root(root)
38        } else {
39            Vec::new()
40        };
41        drop(inner);
42        drop(leases);
43        Ok(())
44    }
45
46    /// Emit cancellation once without ending physical calls.
47    pub fn cancel_root(&self, root: Id) -> Result<()> {
48        let mut inner = self.inner.borrow_mut();
49        let record = inner
50            .roots
51            .get_mut(&root)
52            .ok_or_else(|| gone(Reason::Root))?;
53        if !record.cancelled {
54            record.cancelled = true;
55            inner.actions.push_back(Action::CancelRoot(root));
56        }
57        Ok(())
58    }
59
60    /// Read the identity retained by an active root.
61    pub fn root_principal(&self, root: Id) -> Result<String> {
62        Ok(self.inner.borrow().check_root(root)?.principal.clone())
63    }
64
65    /// Admits one physical call against its root's retained implementation version.
66    /// Refuses roots older than the object's minimum version before retaining a call.
67    pub fn begin_call(&self, reference: Id, root: Id, method: &str) -> Result<Invocation> {
68        self.begin_call_with_context(reference, root, method, 0, None)
69    }
70
71    /// Admit one call with its own immutable frame. `parent` is the live invocation issuing it,
72    /// if any: a cancelled parent admits nothing, and cancelling the parent later reaches this
73    /// call too.
74    pub fn begin_call_with_context(
75        &self,
76        reference: Id,
77        root: Id,
78        method: &str,
79        frame: Id,
80        parent: Option<Id>,
81    ) -> Result<Invocation> {
82        let mut inner = self.inner.borrow_mut();
83        inner.check_frame(root, frame)?;
84        inner.check_parent(root, parent)?;
85        let context = inner.check_root(root)?;
86        if inner.closing && !context.cleanup {
87            return Err(Error::new(Code::Closed, Reason::Host, "host is closing"));
88        }
89        let version = context.version;
90        let reference = inner
91            .references
92            .get(&reference)
93            .ok_or_else(|| gone(Reason::Reference))?;
94        if reference.released {
95            return Err(Error::new(
96                Code::Released,
97                Reason::Reference,
98                "reference is released",
99            ));
100        }
101        let object = reference.object;
102        #[cfg(feature = "views")]
103        if reference
104            .allowed
105            .as_ref()
106            .is_some_and(|allowed| !allowed.contains(method))
107        {
108            return Err(Error::new(
109                Code::Forbidden,
110                Reason::Method,
111                "method is not exposed",
112            ));
113        }
114        if !reference.methods.is_empty() && !reference.methods.contains(method) {
115            return Err(Error::new(
116                Code::Forbidden,
117                Reason::Method,
118                "method was not required",
119            ));
120        }
121        let record = inner
122            .objects
123            .get(&object)
124            .ok_or_else(|| gone(Reason::Object))?;
125        if record.phase != Status::Live || record.disposing {
126            return Err(Error::new(
127                Code::Unavailable,
128                Reason::NotReady,
129                "object is not live",
130            ));
131        }
132        if version < record.min_version {
133            return Err(conflict(Reason::UpgradeConflict));
134        }
135        if record
136            .gate
137            .as_ref()
138            .is_some_and(|allowed| !allowed.contains(&root))
139        {
140            return Err(conflict(Reason::UpgradeConflict));
141        }
142        let (orb, service) = inner.find_service(&record.address.service, version)?;
143        if !service.methods.contains(method) {
144            return Err(Error::invalid(Reason::Method, "method is not declared"));
145        }
146        let orb_owner = inner.check_orb(orb, root, version)?;
147        let id = inner.id()?;
148        let call = Invocation {
149            context: frame,
150            id,
151            root,
152            object,
153            orb,
154            code_version: version,
155            method: method.into(),
156        };
157        let call = inner.retain_call(call, orb_owner)?;
158        inner.link_call(call.id, parent);
159        Ok(call)
160    }
161
162    /// Cancel one invocation for its caller, and every live call it issued, directly or through
163    /// its descendants. Its root, its caller and sibling calls are unaffected. Cancellation is
164    /// logical: each call keeps running, counted, until [`Host::finish_call`]; a cancelled call
165    /// admits no further calls, operations or execution frames. Returns the calls cancelled now,
166    /// in order, each also announced once by [`Action::CancelCall`]; repeating it returns none.
167    pub fn cancel_call(&self, call: Id) -> Result<Vec<Id>> {
168        let mut inner = self.inner.borrow_mut();
169        if !inner.calls.contains_key(&call) {
170            return Err(gone(Reason::Call));
171        }
172        let mut cancelled = Vec::new();
173        let mut next = vec![call];
174        while let Some(call) = next.pop() {
175            // An already cancelled call's descendants were cancelled with it, and it admits none.
176            if !inner.cancelled_calls.insert(call) {
177                continue;
178            }
179            inner.actions.push_back(Action::CancelCall(call));
180            cancelled.push(call);
181            next.extend(inner.call_children.members(&call));
182        }
183        Ok(cancelled)
184    }
185
186    /// Require a live invocation that its caller has not cancelled.
187    pub fn check_call(&self, call: Id) -> Result<()> {
188        let inner = self.inner.borrow();
189        if !inner.calls.contains_key(&call) {
190            return Err(gone(Reason::Call));
191        }
192        inner.check_uncancelled(call)
193    }
194
195    /// Whether a caller cancelled this invocation (or one of its ancestors). An ended call reads
196    /// as not cancelled.
197    pub fn call_cancelled(&self, call: Id) -> bool {
198        self.inner.borrow().cancelled_calls.contains(&call)
199    }
200
201    /// Marks actual callback settlement, independently from logical cancellation or caller release.
202    pub fn finish_call(&self, call: Id) -> Result<()> {
203        let mut inner = self.inner.borrow_mut();
204        let call = inner
205            .calls
206            .remove(&call)
207            .ok_or_else(|| gone(Reason::Call))?;
208        inner.unlink_call(call.id);
209        #[cfg(feature = "hooks")]
210        inner.release_observation_call(call.id);
211        let mut leases = Vec::new();
212        for frame in inner.call_contexts.remove(&call.id).unwrap_or_default() {
213            inner.release_frame(frame, &mut leases);
214        }
215        inner.release_frame(call.context, &mut leases);
216        let orb_owner = inner.orbs[&call.orb].owner;
217        for owner in [
218            Owner::Host,
219            Owner::Orb(orb_owner),
220            Owner::Object(call.object),
221        ] {
222            inner.owner_calls.remove(&owner, call.id);
223            inner.settled_owner(owner);
224        }
225        let root = inner.roots.get_mut(&call.root).expect("call retains root");
226        root.calls -= 1;
227        if root.calls == 0 && !root.active {
228            leases.extend(inner.remove_root(call.root));
229        }
230        if call.object != 0 {
231            inner
232                .objects
233                .get_mut(&call.object)
234                .expect("call retains object")
235                .calls -= 1;
236            inner.maybe_dispose(call.object);
237        }
238        drop(inner);
239        drop(leases);
240        Ok(())
241    }
242
243    /// Read the record for a physically active call.
244    pub fn invocation(&self, call: Id) -> Result<Invocation> {
245        self.inner
246            .borrow()
247            .calls
248            .get(&call)
249            .cloned()
250            .ok_or_else(|| gone(Reason::Call))
251    }
252
253    /// Enters an orb-owned operation such as a hook contribution without exposing a service.
254    pub fn begin_operation(
255        &self,
256        orb: Id,
257        root: Id,
258        operation: Id,
259        object: Option<Id>,
260    ) -> Result<Invocation> {
261        self.begin_operation_with_context(orb, root, operation, object, 0, None)
262    }
263
264    /// Admit an orb operation with its caller's frame; `parent` as for
265    /// [`Host::begin_call_with_context`].
266    pub fn begin_operation_with_context(
267        &self,
268        orb: Id,
269        root: Id,
270        operation: Id,
271        object: Option<Id>,
272        frame: Id,
273        parent: Option<Id>,
274    ) -> Result<Invocation> {
275        let mut inner = self.inner.borrow_mut();
276        inner.check_frame(root, frame)?;
277        inner.check_parent(root, parent)?;
278        let context = inner.check_root(root)?;
279        let version = context.version;
280        let snapshot = inner
281            .versions
282            .get(&version)
283            .ok_or_else(|| conflict(Reason::Superseded))?;
284        if inner
285            .orbs
286            .get(&orb)
287            .is_none_or(|record| snapshot.get(&record.declaration.name) != Some(&orb))
288            || operation == 0
289        {
290            return Err(gone(Reason::Operation));
291        }
292        let orb_owner = inner.check_orb(orb, root, version)?;
293        if let Some(object) = object {
294            let record = inner
295                .objects
296                .get(&object)
297                .ok_or_else(|| gone(Reason::Object))?;
298            if record.phase != Status::Live || record.disposing {
299                return Err(gone(Reason::Object));
300            }
301            if version < record.min_version
302                || record
303                    .gate
304                    .as_ref()
305                    .is_some_and(|roots| !roots.contains(&root))
306            {
307                return Err(conflict(Reason::UpgradeConflict));
308            }
309            let (expected, _) = inner.find_service(&record.address.service, version)?;
310            if expected != orb {
311                return Err(conflict(Reason::OperationOwner));
312            }
313        }
314        let id = inner.id()?;
315        let invocation = Invocation {
316            context: frame,
317            id,
318            root,
319            object: object.unwrap_or(0),
320            orb,
321            code_version: version,
322            method: operation.to_string(),
323        };
324        let invocation = inner.retain_call(invocation, orb_owner)?;
325        inner.link_call(invocation.id, parent);
326        Ok(invocation)
327    }
328}
329
330impl Inner {
331    /// Refuse a call issued by an invocation that ended, belongs to another root or was
332    /// cancelled by its caller.
333    fn check_parent(&self, root: Id, parent: Option<Id>) -> Result<()> {
334        let Some(parent) = parent else {
335            return Ok(());
336        };
337        match self.calls.get(&parent) {
338            None => Err(gone(Reason::Call)),
339            Some(call) if call.root != root => Err(Error::invalid(
340                Reason::Context,
341                "the issuing invocation belongs to another root",
342            )),
343            Some(_) => self.check_uncancelled(parent),
344        }
345    }
346
347    /// Refuse new authority derived from a cancelled invocation.
348    pub(crate) fn check_uncancelled(&self, call: Id) -> Result<()> {
349        if self.cancelled_calls.contains(&call) {
350            return Err(Error::new(
351                Code::Cancelled,
352                Reason::Call,
353                "invocation was cancelled",
354            ));
355        }
356        Ok(())
357    }
358
359    /// Record which invocation issued a call.
360    fn link_call(&mut self, call: Id, parent: Option<Id>) {
361        if let Some(parent) = parent {
362            self.call_parents.insert(call, parent);
363            self.call_children.insert(parent, call);
364        }
365    }
366
367    /// Forget an ended call's lineage. Calls it issued that still run are handed to its own
368    /// parent, so cancelling an ancestor still reaches them.
369    fn unlink_call(&mut self, call: Id) {
370        self.cancelled_calls.remove(&call);
371        let parent = self.call_parents.remove(&call);
372        if let Some(parent) = parent {
373            self.call_children.remove(&parent, call);
374        }
375        for child in self.call_children.take(&call) {
376            match parent {
377                Some(parent) => {
378                    self.call_parents.insert(child, parent);
379                    self.call_children.insert(parent, child);
380                }
381                None => {
382                    self.call_parents.remove(&child);
383                }
384            }
385        }
386    }
387
388    /// Retain physical call ownership and its reverse indexes together.
389    fn retain_call(&mut self, call: Invocation, orb_owner: Id) -> Result<Invocation> {
390        #[cfg(feature = "hooks")]
391        self.claim_observation_call(&call)?;
392        self.orb_roots.insert(orb_owner, call.root);
393        self.owner_calls.insert(Owner::Host, call.id);
394        self.owner_calls.insert(Owner::Orb(orb_owner), call.id);
395        if call.object != 0 {
396            self.owner_calls.insert(Owner::Object(call.object), call.id);
397            self.object_roots.insert(call.object, call.root);
398            self.objects
399                .get_mut(&call.object)
400                .expect("checked object")
401                .calls += 1;
402        }
403        let root = self.roots.get_mut(&call.root).expect("checked root");
404        root.calls += 1;
405        root.orbs.insert(orb_owner);
406        if call.object != 0 {
407            root.touched.insert(call.object);
408        }
409        self.retain_frame(call.context);
410        self.calls.insert(call.id, call.clone());
411        Ok(call)
412    }
413}