Skip to main content

tembra_runtime/host/
reference.rs

1//! Native reference claims and typed calls.
2
3use super::*;
4
5use crate::portable::{FromPayload, IntoPayload, Issuer, Origin, Payload};
6
7/// Encoding and decoding of one portable call. Arguments move by value so that capabilities
8/// can travel; decoding receives the calling claim to anchor owned results.
9type Boundary<A, R> = (
10    Box<dyn FnOnce(A) -> Result<Payload>>,
11    Box<dyn FnOnce(Payload, &Origin) -> Result<R>>,
12);
13
14/// A claim is released on drop. A running callback has its own physical kernel pin.
15pub struct Reference {
16    pub(super) host: Host,
17    pub(super) id: core::Id,
18    pub(super) object: core::Id,
19    pub(super) foreign_ready: Option<Shared<LocalBoxFuture<'static, Result<()>>>>,
20    pub(super) released: Rc<crate::readable::ReadLifetime>,
21}
22
23impl Reference {
24    /// Encode the provider's current state through its portable boundary while this claim is live.
25    pub fn state_snapshot(&self) -> Result<(core::Snapshot, Value)> {
26        if self.status()? != core::Status::Live {
27            return Err(Error::invalid(Reason::NotReady, "reference is not live"));
28        }
29        let snapshot = self.host.kernel().snapshot(self.object)?;
30        Ok((snapshot, self.host.portable_value(snapshot.value)?))
31    }
32
33    /// Read this reference's kernel identity.
34    pub fn id(&self) -> core::Id {
35        self.id
36    }
37
38    /// Read the object identity retained by this reference.
39    pub fn object(&self) -> core::Id {
40        self.object
41    }
42
43    /// Release this ownership claim once.
44    pub fn release(&self) -> Result<()> {
45        if !self.released.released.replace(true) {
46            self.released.close();
47            if self.foreign_ready.is_some() {
48                self.host
49                    .notify_foreign(super::signals::ForeignNotification::ReferenceReleased(
50                        self.id,
51                    ));
52            }
53
54            if !self.host.0.external_actions.get() {
55                self.host.tick();
56            }
57            if self.host.kernel().status(self.id).is_err() {
58                return Ok(());
59            }
60            self.host.kernel().release(self.id)?;
61            self.host.kernel().forget_reference(self.id)?;
62            self.host.flush();
63        }
64        Ok(())
65    }
66
67    /// Read this claim's lifecycle status, including deterministic release.
68    pub fn status(&self) -> Result<core::Status> {
69        if self.released.released.get() {
70            Ok(core::Status::Released)
71        } else {
72            self.host.kernel().status(self.id)
73        }
74    }
75
76    /// Waits for the kernel's activation program, including every resource opener.
77    pub async fn ready(&self) -> Result<()> {
78        self.activation().await?;
79        match self.host.kernel().status(self.id)? {
80            core::Status::Live => Ok(()),
81            _ => Err(Error::invalid(Reason::NotReady, "object is not live")),
82        }
83    }
84
85    async fn activation(&self) -> Result<()> {
86        let ready = self
87            .host
88            .0
89            .objects
90            .borrow()
91            .get(&self.object)
92            .and_then(|object| object.activation.clone());
93        let ready = ready.or_else(|| self.foreign_ready.clone());
94        if let Some(ready) = ready {
95            ready.await?;
96        }
97        Ok(())
98    }
99
100    /// Execute a typed local Rust call without requiring portable value traits.
101    /// Arguments and results move as Rust values; nothing is serialized.
102    pub async fn call<A: 'static, R: 'static>(
103        &self,
104        context: &Context,
105        method: &str,
106        arguments: A,
107    ) -> Result<R> {
108        self.invoke(context, method, arguments, None).await
109    }
110
111    /// Call the provider's portable entrypoint, whatever language or isolation it has.
112    /// JavaScript arguments use tuples or vectors to represent the method's argument list.
113    /// Results are decoded inside the managed call, so an owned capability that cannot be
114    /// delivered is closed rather than leaked.
115    pub async fn call_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
116        &self,
117        context: &Context,
118        method: &str,
119        arguments: A,
120    ) -> Result<R> {
121        let boundary: Boundary<A, R> = (Box::new(A::into_payload), Box::new(R::from_payload));
122        self.invoke(context, method, arguments, Some(boundary))
123            .await
124    }
125
126    /// Like [`Reference::call_portable`], but its caller keeps control of the admitted
127    /// invocation: once admitted, it receives the [`IssuedCall`], which cancels exactly this call
128    /// and waits for its physical end, and the call's result, which it may stop awaiting.
129    pub async fn issue_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
130        &self,
131        context: &Context,
132        method: &str,
133        arguments: A,
134    ) -> Result<(IssuedCall, LocalBoxFuture<'static, Result<R>>)> {
135        let boundary: Boundary<A, R> = (Box::new(A::into_payload), Box::new(R::from_payload));
136        self.issue(context, method, arguments, Some(boundary)).await
137    }
138
139    /// Only `Owned` can originate implicit self. Public payload arguments cannot forward a
140    /// provider's retained receiver into another call.
141    pub(crate) async fn call_borrowed<R: FromPayload + 'static>(
142        &self,
143        context: &Context,
144        method: &str,
145        arguments: Payload,
146    ) -> Result<R> {
147        let (_, result) = self.issue_borrowed(context, method, arguments).await?;
148        result.await
149    }
150
151    /// [`Reference::call_borrowed`] with control of the admitted invocation.
152    pub(crate) async fn issue_borrowed<R: FromPayload + 'static>(
153        &self,
154        context: &Context,
155        method: &str,
156        arguments: Payload,
157    ) -> Result<(IssuedCall, LocalBoxFuture<'static, Result<R>>)> {
158        let boundary: Boundary<Payload, R> = (Box::new(Ok), Box::new(R::from_payload));
159        self.issue(context, method, arguments, Some(boundary)).await
160    }
161
162    async fn invoke<A: 'static, R: 'static>(
163        &self,
164        context: &Context,
165        method: &str,
166        arguments: A,
167        boundary: Option<Boundary<A, R>>,
168    ) -> Result<R> {
169        let (_, result) = self.issue(context, method, arguments, boundary).await?;
170        result.await
171    }
172
173    /// Admit one call issued from `context` and start it as managed work. The call's guard, not
174    /// its caller, owns the invocation until it physically ends.
175    async fn issue<A: 'static, R: 'static>(
176        &self,
177        context: &Context,
178        method: &str,
179        arguments: A,
180        boundary: Option<Boundary<A, R>>,
181    ) -> Result<(IssuedCall, LocalBoxFuture<'static, Result<R>>)> {
182        if !self.host.same(&context.host) {
183            return Err(Error::invalid(Reason::Context, "foreign host context"));
184        }
185        context.check()?;
186        self.activation().await?;
187        context.check()?;
188        let call = self.host.kernel().begin_call_with_context(
189            self.id,
190            context.root,
191            method,
192            context.frame(),
193            context.issuer(),
194        )?;
195        let issued = IssuedCall {
196            host: self.host.clone(),
197            call: call.id,
198        };
199        let route = self.route(&call, method, boundary.is_some());
200        let foreign = matches!(route, Route::Foreign);
201        let origin = Origin::new(
202            self.host.clone(),
203            self.id,
204            self.object,
205            foreign,
206            call.orb,
207            call.root,
208        );
209        let method_name = method.to_owned();
210        let host = self.host.clone();
211        let entered = host.context(call.root, Some(call.clone()))?;
212        let receive = self.host.spawn_managed_settling(call.id, async move {
213            let result = match (route, boundary) {
214                (Route::Portable(environment, handle, issuer), Some((encode, decode))) => {
215                    let (arguments, receiver) = match encode(arguments)
216                        .and_then(|payload| payload.for_call(&issuer))
217                    {
218                        Ok(prepared) => prepared,
219                        Err(error) => return (Err(error), None),
220                    };
221                    let (head, physical) = match handle(environment, entered, arguments).await {
222                        Ok(outcome) => outcome.into_parts(),
223                        Err(error) => return (Err(error), None),
224                    };
225                    // The values the head issued become the object version's here, before the
226                    // head is bound and decoded, and published. A refused head is dropped,
227                    // closing what it carries. Native decoding, or a refused attachment's
228                    // close, may panic: only that step is caught, so the physical work and the
229                    // receiver pin below are never lost with it.
230                    let head = head.map(|payload| payload.issued_by(&issuer));
231                    let head = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
232                        head.and_then(|payload| {
233                            payload.bind_streams(&origin)?;
234                            decode(payload, &origin)
235                        })
236                        .map(|value| Box::new(value) as Box<dyn std::any::Any>)
237                    }))
238                    .unwrap_or_else(|_| {
239                        Err(Error::new(
240                            core::Code::Unavailable,
241                            "callback",
242                            "native result decoding panicked",
243                        ))
244                    });
245                    // Implicit self stays pinned until the call has physically ended; without
246                    // remaining work the pin drops here, before the invocation finishes.
247                    let physical = physical.map(|physical| {
248                        async move {
249                            let settled = physical.await;
250                            drop(receiver);
251                            settled
252                        }
253                        .boxed_local()
254                    });
255                    return (head, physical);
256                }
257                (Route::Local(environment, handle), None) => {
258                    handle(environment, entered, Box::new(arguments)).await
259                }
260                (Route::Foreign, Some((encode, decode))) => {
261                    async {
262                        let value = encode(arguments)?.data_only()?;
263                        let result = host
264                            .foreign(serde_json::json!({
265                                "kind": "invoke", "call": call.id, "frame": call.context, "input": value,
266                            }))
267                            .await?;
268                        Ok(Box::new(decode(Payload::data(result), &origin)?) as Box<dyn std::any::Any>)
269                    }
270                    .await
271                }
272                (Route::Foreign, None) => Err(Error::invalid(
273                    Reason::LocalValue,
274                    "use call_portable for a foreign service",
275                )),
276                (Route::LocalOnly, _) => Err(Error::invalid(
277                    Reason::LocalValue,
278                    format!("{method_name} is a host-local method without a portable entrypoint"),
279                )),
280                _ => Err(Error::invalid(Reason::NativeMethod, method_name)),
281            };
282            (result, None)
283        })?;
284        let result = async move {
285            let result = receive.await.map_err(|_| {
286                Error::invalid(Reason::Executor, "executor stopped before callback settled")
287            })??;
288            result
289                .downcast::<R>()
290                .map(|value| *value)
291                .map_err(|_| type_error())
292        }
293        .boxed_local();
294        Ok((issued, result))
295    }
296
297    /// Select the admitted call's entrypoint. Portable calls always use the provider's portable
298    /// entrypoint, even for an in-process native provider; typed calls use its local one.
299    fn route(&self, call: &core::Invocation, method: &str, portable: bool) -> Route {
300        if !self.host.has_orb(call.orb) {
301            return Route::Foreign;
302        }
303        let objects = self.host.0.objects.borrow();
304        let Some(object) = objects
305            .get(&call.object)
306            .and_then(|object| object.versions.get(&call.orb))
307        else {
308            return Route::Missing;
309        };
310        let environment = object.environment.clone();
311        let implementation = &object.implementation;
312        if portable {
313            match implementation.portable.get(method) {
314                Some(handle) => Route::Portable(environment, handle.clone(), object.issuer.clone()),
315                // A host-local method refuses every portable caller.
316                None if implementation.local_only(method) => Route::LocalOnly,
317                None => Route::Missing,
318            }
319        } else {
320            implementation
321                .local
322                .get(method)
323                .map_or(Route::Missing, |handle| {
324                    Route::Local(environment, handle.clone())
325                })
326        }
327    }
328}
329
330/// A dependency call as its caller issued it: the caller may cancel exactly this invocation,
331/// and wait until it has physically ended.
332///
333/// Cancellation is logical. The call, and the calls it issued, observe it through their
334/// context's signal, and admit no further work; their root, their caller and sibling calls are
335/// unaffected. The call keeps running, counted by the kernel and owned by its managed task,
336/// until it physically ends, however long a callee that ignores the signal takes.
337#[derive(Clone)]
338pub struct IssuedCall {
339    host: Host,
340    call: core::Id,
341}
342
343impl IssuedCall {
344    /// The admitted invocation's kernel identity.
345    pub fn id(&self) -> core::Id {
346        self.call
347    }
348
349    /// Cancel this invocation and the calls it issued. Doing so again, or after the call
350    /// ended, does nothing.
351    pub fn cancel(&self) {
352        let Ok(cancelled) = self.host.kernel().cancel_call(self.call) else {
353            return;
354        };
355        for call in cancelled {
356            self.host.cancel_call_signal(call);
357        }
358        self.host.flush();
359    }
360
361    /// Resolve once the invocation has physically ended: its managed task finished the call.
362    pub async fn settled(&self) {
363        while self.host.kernel().invocation(self.call).is_ok() {
364            let (send, receive) = oneshot::channel();
365            self.host.0.settled.borrow_mut().push(send);
366            let _ = receive.await;
367        }
368    }
369}
370
371/// The entrypoint an admitted call dispatches to.
372enum Route {
373    Portable(crate::orb::Data, crate::orb::PortableMethod, Rc<Issuer>),
374    Local(crate::orb::Data, crate::orb::LocalMethod),
375    Foreign,
376    LocalOnly,
377    Missing,
378}
379
380impl Host {
381    /// A second claim with exactly the same admission as `reference`, owned by the caller.
382    pub(crate) fn duplicate_reference(
383        &self,
384        reference: core::Id,
385        object: core::Id,
386    ) -> Result<Reference> {
387        let id = self.kernel().duplicate(reference)?;
388        Ok(Reference {
389            host: self.clone(),
390            id,
391            object,
392            foreign_ready: None,
393            released: Rc::new(crate::readable::ReadLifetime::default()),
394        })
395    }
396}
397
398impl Drop for Reference {
399    /// Release an unconsumed reference claim during destruction.
400    fn drop(&mut self) {
401        if let Err(error) = self.release() {
402            self.host.0.errors.borrow_mut().push(error);
403        }
404    }
405}
406
407impl Reference {
408    /// Read native typed state and bind all its observers to this claim's lifetime.
409    pub fn state<T: 'static>(&self) -> Result<crate::Readable<T>> {
410        if self.status()? != core::Status::Live {
411            return Err(Error::invalid(Reason::NotReady, "reference is not live"));
412        }
413        let view =
414            crate::Readable::new(self.host.clone(), self.object, Some(self.released.clone()));
415        view.value()?;
416        Ok(view)
417    }
418}