Skip to main content

tembra_runtime/host/
context.rs

1//! A logical root stays pinned until physical work settles.
2
3use super::*;
4
5impl Host {
6    /// Issue a context for an active root and matching invocation.
7    pub fn context(&self, root: core::Id, invocation: Option<core::Invocation>) -> Result<Context> {
8        self.kernel().check_root(root)?;
9        if invocation.as_ref().is_some_and(|call| call.root != root) {
10            return Err(Error::invalid(
11                Reason::Context,
12                "invocation belongs to another root",
13            ));
14        }
15        Ok(Context {
16            host: self.clone(),
17            root,
18            frame: invocation.as_ref().map_or(0, |call| call.context),
19            call: invocation,
20            signal: self.context_signal(root),
21            owner: None,
22        })
23    }
24
25    /// Run an operation while a guard retains its root lifetime.
26    pub async fn root<T>(
27        &self,
28        principal: &str,
29        operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>>,
30    ) -> Result<T> {
31        let root = self.kernel().begin_root(principal)?;
32        let context = self.context(root, None)?;
33        let _guard = RootGuard {
34            host: self.clone(),
35            root,
36        };
37        operation(context).await
38    }
39}
40
41impl Host {
42    /// Run a root operation as a task of this host instead of the caller's future.
43    ///
44    /// The root lives until the operation itself completes, whoever (if anyone) awaits the
45    /// returned receiver: dropping it neither ends the root nor stops the operation. The task is
46    /// tracked like every callback, so [`Host::close`] waits for it. Use it when work admitted
47    /// under the root must outlive the caller's own wait, for example a response that keeps
48    /// streaming after its headers were handed to the application.
49    pub fn spawn_root<T: 'static>(
50        &self,
51        principal: &str,
52        operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>> + 'static,
53    ) -> Result<futures::channel::oneshot::Receiver<Result<T>>> {
54        let host = self.clone();
55        let principal = principal.to_owned();
56        self.spawn(async move { host.root(&principal, operation).await })
57    }
58}
59
60pub(super) struct RootGuard {
61    pub(super) host: Host,
62    pub(super) root: core::Id,
63}
64
65impl Drop for RootGuard {
66    /// End the root's logical lifetime and dispatch pending cleanup.
67    fn drop(&mut self) {
68        if let Err(error) = self.host.kernel().end_root(self.root) {
69            self.host.0.errors.borrow_mut().push(error);
70        }
71        self.host.end_context(self.root);
72        self.host
73            .notify_foreign(super::signals::ForeignNotification::RootEnded(self.root));
74        self.host.flush();
75    }
76}
77
78/// Contexts are issued by a host, and become unusable when their root or invocation ends.
79#[derive(Clone)]
80pub struct Context {
81    frame: core::Id,
82    pub(crate) host: Host,
83    pub root: core::Id,
84    call: Option<core::Invocation>,
85    /// The root's signal, which every context of the root holds: a signal of the root or of its
86    /// calls, first read once the kernel has forgotten the root, still finds whether it was
87    /// cancelled.
88    signal: Cancellation,
89    /// The owner of the resource whose opener or closer runs with this context, which has no
90    /// invocation: the Orb the record of a `log` is attributed to, and the object whose address
91    /// `address` answers, for a resource of an object.
92    owner: Option<Owner>,
93}
94
95/// The owner of a resource, as the context of its opener or closer knows it: the name of the Orb,
96/// read when the resource is declared, since the opener of a resource a reload adds runs before
97/// the kernel commits the new revision, and the closer of one a reload keeps runs after it has
98/// forgotten the revision that declared it; none for a resource of the host, which no Orb owns.
99#[derive(Clone)]
100pub(super) struct Owner {
101    pub(super) orb: Option<String>,
102    pub(super) object: Option<core::Id>,
103}
104
105impl Context {
106    /// This context as a resource's opener or closer gets it: attributed to the resource's owner,
107    /// and, for an opener, cancelled with the resource's own signal.
108    pub(super) fn owned(mut self, owner: Owner, signal: Option<Cancellation>) -> Self {
109        self.owner = Some(owner);
110        if let Some(signal) = signal {
111            self.signal = signal;
112        }
113        self
114    }
115}
116
117impl Context {
118    /// Read the frame identity for local adapter calls.
119    pub fn frame(&self) -> core::Id {
120        self.frame
121    }
122
123    /// Derive values without extending identity or invocation lifetime.
124    pub fn with<T: core::ContextDatum>(&self, key: &core::ContextKey<T>, value: T) -> Result<Self> {
125        self.check()?;
126        let frame = self.host.kernel().derive_context(
127            self.root,
128            self.frame,
129            self.call.as_ref().map(|call| call.id),
130            key.contract(),
131            value.into_value(),
132        )?;
133        Ok(Self {
134            host: self.host.clone(),
135            root: self.root,
136            call: self.call.clone(),
137            frame,
138            signal: self.signal.clone(),
139            owner: self.owner.clone(),
140        })
141    }
142
143    /// Retain the admitted isolated revision in this invocation's private execution ancestry.
144    pub fn enter_execution(&self) -> Result<Self> {
145        let call = self.invocation()?;
146        let frame = self.host.kernel().enter_execution(call.id, self.frame)?;
147        Ok(Self {
148            host: self.host.clone(),
149            root: self.root,
150            call: self.call.clone(),
151            frame,
152            signal: self.signal.clone(),
153            owner: self.owner.clone(),
154        })
155    }
156
157    /// Read typed metadata while this invocation remains valid.
158    pub fn value<T: core::ContextDatum>(&self, key: &core::ContextKey<T>) -> Result<Option<T>> {
159        self.check()?;
160        if self.frame == 0 {
161            return Ok(None);
162        }
163        self.host
164            .kernel()
165            .context_value(self.root, self.frame, &key.contract())?
166            .map(T::from_value)
167            .transpose()
168    }
169
170    /// Reject an expired root, or a completed invocation or one its caller cancelled.
171    pub fn check(&self) -> Result<()> {
172        self.host.kernel().check_root(self.root)?;
173        if let Some(call) = &self.call {
174            self.host.kernel().check_call(call.id)?;
175        }
176        Ok(())
177    }
178
179    /// Signal root cancellation without releasing physical ownership.
180    pub fn cancel(&self) -> Result<()> {
181        self.host.kernel().cancel_root(self.root)?;
182        self.host.cancel_context(self.root);
183        self.host.flush();
184        Ok(())
185    }
186
187    /// Read the identity retained by this root.
188    pub fn principal(&self) -> Result<String> {
189        self.host.kernel().root_principal(self.root)
190    }
191
192    /// Read the canonical address of the object running this invocation, as
193    /// [`Declaration::address`] reads it while the object declares; in the opener or closer of an
194    /// object's resource, the address of that object.
195    pub fn address(&self) -> Result<core::Address> {
196        let object = match (&self.call, &self.owner) {
197            (Some(call), _) => call.object,
198            (
199                None,
200                Some(Owner {
201                    object: Some(object),
202                    ..
203                }),
204            ) => *object,
205            (None, _) => self.invocation()?.object,
206        };
207        self.host.kernel().object_address(object)
208    }
209
210    /// The name of the Orb a record of this context is attributed to: the one running the
211    /// invocation, or the one owning the resource whose opener or closer runs, as it was named
212    /// when the resource was declared.
213    pub(super) fn attributed(&self) -> Result<String> {
214        match (&self.call, &self.owner) {
215            (Some(call), _) => Ok(self.host.kernel().orb(call.orb)?.declaration.name),
216            (None, Some(Owner { orb: Some(orb), .. })) => Ok(orb.clone()),
217            (None, _) => {
218                let call = self.invocation()?;
219                Ok(self.host.kernel().orb(call.orb)?.declaration.name)
220            }
221        }
222    }
223
224    /// The entered invocation that issues calls made from this context, if any.
225    pub(crate) fn issuer(&self) -> Option<core::Id> {
226        self.call.as_ref().map(|call| call.id)
227    }
228
229    /// Require an admitted call context for owner operations.
230    pub fn invocation(&self) -> Result<core::Invocation> {
231        self.call
232            .clone()
233            .ok_or_else(|| Error::invalid(Reason::Context, "an entered invocation is required"))
234    }
235}
236
237impl Context {
238    /// Observe cancellation of this operation's root, including host shutdown. An entered
239    /// invocation's signal also fires when its caller cancels that invocation (or one it
240    /// descends from); that never cancels the root or sibling calls.
241    pub fn signal(&self) -> Cancellation {
242        match &self.call {
243            Some(call) => self.host.call_signal(self.root, &self.signal, call.id),
244            None => self.signal.clone(),
245        }
246    }
247}
248
249impl Host {
250    /// One shared signal per entered invocation, created when first observed: cancelled at once
251    /// if its root or the invocation itself already was. The root's signal answers for the root,
252    /// as a signal read earlier would: its normal end cancels nothing of the call.
253    fn call_signal(
254        &self,
255        root: core::Id,
256        root_signal: &Cancellation,
257        call: core::Id,
258    ) -> Cancellation {
259        let mut signals = self.0.call_signals.borrow_mut();
260        signals.retain(|_, (_, signal)| signal.strong_count() != 0);
261        if let Some(signal) = signals.get(&call).and_then(|(_, signal)| signal.upgrade()) {
262            return Cancellation(signal);
263        }
264        let signal = Cancellation::new("root");
265        if root_signal.is_cancelled() {
266            signal.cancel();
267        } else if self.kernel().call_cancelled(call) {
268            signal.cancel_because("call");
269        }
270        signals.insert(call, (root, Rc::downgrade(&signal.0)));
271        signal
272    }
273
274    /// Mirror a kernel call cancellation into that invocation's signal, if it is observed.
275    pub fn cancel_call_signal(&self, call: core::Id) {
276        let signal = self
277            .0
278            .call_signals
279            .borrow()
280            .get(&call)
281            .and_then(|(_, signal)| signal.upgrade());
282        if let Some(signal) = signal {
283            Cancellation(signal).cancel_because("call");
284        }
285    }
286
287    /// The signal of a root, for a context of it: the one its other contexts hold, or a new one.
288    /// A context is issued only for a root neither ended nor cancelled, so a new signal starts
289    /// uncancelled, and the root's cancellation reaches it while a context holds it.
290    fn context_signal(&self, root: core::Id) -> Cancellation {
291        let mut signals = self.0.context_signals.borrow_mut();
292        // Each context of a root asks for its signal: only a new one sweeps the released ones.
293        if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
294            return Cancellation(signal);
295        }
296        signals.retain(|_, signal| signal.strong_count() != 0);
297        let signal = Cancellation::new("root");
298        signals.insert(root, Rc::downgrade(&signal.0));
299        signal
300    }
301
302    /// Private lifecycle notification for waiting acquisition, never exposed as Context::signal.
303    /// Normal root completion must not cancel admitted or streaming physical work.
304    fn root_end_signal(&self, root: core::Id) -> Cancellation {
305        let mut signals = self.0.root_end_signals.borrow_mut();
306        signals.retain(|_, signal| signal.strong_count() != 0);
307        if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
308            return Cancellation(signal);
309        }
310        let signal = Cancellation::new("root_end");
311        if self.kernel().check_root(root).is_err() {
312            signal.cancel();
313        }
314        signals.insert(root, Rc::downgrade(&signal.0));
315        signal
316    }
317
318    /// Mirror a shared kernel cancellation action into native context signals, and cancel the
319    /// stream ends delivered to this root at once.
320    pub fn cancel_context(&self, root: core::Id) {
321        if let Some(signal) = self
322            .0
323            .context_signals
324            .borrow()
325            .get(&root)
326            .and_then(std::rc::Weak::upgrade)
327        {
328            Cancellation(signal).cancel();
329        }
330        // Signals of the root's entered invocations observe the root too.
331        let calls: Vec<_> = self
332            .0
333            .call_signals
334            .borrow()
335            .values()
336            .filter(|(owner, _)| *owner == root)
337            .filter_map(|(_, signal)| signal.upgrade())
338            .collect();
339        for signal in calls {
340            Cancellation(signal).cancel_because("root");
341        }
342        for stream in self.root_streams(root, false) {
343            stream.cancel_root();
344        }
345    }
346
347    /// Bind a delivered stream end to the root that received it.
348    pub(crate) fn bind_root_stream(
349        &self,
350        root: core::Id,
351        stream: std::rc::Weak<dyn crate::portable::RootStream>,
352    ) -> Result<()> {
353        self.kernel().check_root(root)?;
354        let mut claims = self.0.root_references.borrow_mut();
355        let streams = &mut claims.entry(root).or_default().streams;
356        streams.retain(|stream| stream.strong_count() != 0);
357        streams.push(stream);
358        Ok(())
359    }
360
361    /// The live stream ends of a root, taken out of the registry when the root ends. Collected
362    /// first, so a stream's close never runs while the registry is borrowed.
363    fn root_streams(&self, root: core::Id, take: bool) -> Vec<Rc<dyn crate::portable::RootStream>> {
364        let mut claims = self.0.root_references.borrow_mut();
365        let Some(claims) = claims.get_mut(&root) else {
366            return Vec::new();
367        };
368        let streams = if take {
369            std::mem::take(&mut claims.streams)
370        } else {
371            claims.streams.clone()
372        };
373        streams.iter().filter_map(std::rc::Weak::upgrade).collect()
374    }
375}
376
377impl Context {
378    /// Acquire a reference whose claim is revoked when this operation's root ends.
379    pub fn get(
380        &self,
381        service: &str,
382        key: Vec<String>,
383        options: crate::AcquisitionOptions,
384    ) -> Result<Rc<Reference>> {
385        self.check()?;
386        let reference =
387            Rc::new(
388                self.host
389                    .get_with_options(service, key, &self.principal()?, options)?,
390            );
391        self.host
392            .0
393            .root_references
394            .borrow_mut()
395            .entry(self.root)
396            .or_default()
397            .references
398            .push(reference.clone());
399        Ok(reference)
400    }
401}
402
403impl Context {
404    /// Acquire under this root after the exact previous instance physically closes.
405    /// Cancellation or root expiry ends only this wait; it never interrupts the old cleanup.
406    /// The principal, context and admission requirements are checked again on every attempt.
407    /// Use [`Reference::ready`] separately to await the new instance's activation.
408    pub async fn get_wait(
409        &self,
410        service: &str,
411        key: Vec<String>,
412        options: crate::AcquisitionOptions,
413    ) -> Result<Rc<Reference>> {
414        let signal = self.signal();
415        loop {
416            match self.get(service, key.clone(), options.clone()) {
417                Ok(reference) => return Ok(reference),
418                Err(error) => {
419                    let wait = self
420                        .host
421                        .closing(service, &key, &self.principal()?, error)?;
422                    let root_signal = self.host.root_end_signal(self.root);
423                    let cancelled = std::pin::pin!(async {
424                        let call = std::pin::pin!(signal.cancelled());
425                        let root = std::pin::pin!(root_signal.cancelled());
426                        futures::future::select(call, root).await;
427                    });
428                    let wait = std::pin::pin!(wait);
429                    if let futures::future::Either::Left(_) =
430                        futures::future::select(cancelled, wait).await
431                    {
432                        self.check()?;
433                        signal.check()?;
434                        root_signal.check()?;
435                    }
436                }
437            }
438        }
439    }
440
441    /// Access the native environment shared by the currently entered orb.
442    pub fn orb<T: 'static>(&self) -> Result<Rc<T>> {
443        self.check()?;
444        let call = self.invocation()?;
445        self.host
446            .0
447            .orb_values
448            .borrow()
449            .get(&call.orb)
450            .cloned()
451            .ok_or_else(|| Error::invalid(Reason::Orb, "orb environment unavailable"))?
452            .downcast::<T>()
453            .map_err(|_| type_error())
454    }
455
456    /// Access a host-owned resource during an active operation.
457    pub fn resource<T: 'static>(&self, name: &str) -> Result<Resource<T>> {
458        self.check()?;
459        self.host.resource(name)
460    }
461}
462
463impl Host {
464    /// Revoke native claims acquired inside a root whose logical wait has ended.
465    /// Shared drivers call this for roots they issue themselves.
466    /// Stream ends delivered to the root are closed first, so their producers stop before the
467    /// root's claims are revoked; a retained end then refuses every read.
468    pub fn end_context(&self, root: core::Id) {
469        let ended = self
470            .0
471            .root_end_signals
472            .borrow_mut()
473            .remove(&root)
474            .and_then(|signal| signal.upgrade());
475        if let Some(ended) = ended {
476            Cancellation(ended).cancel();
477        }
478        for stream in self.root_streams(root, true) {
479            stream.end_root();
480        }
481        let references = self
482            .0
483            .root_references
484            .borrow_mut()
485            .remove(&root)
486            .unwrap_or_default()
487            .references;
488        for reference in references {
489            if let Err(error) = reference.release() {
490                self.0.errors.borrow_mut().push(error);
491            }
492        }
493    }
494}