Skip to main content

tembra_runtime/host/
values.rs

1//! Native values cross a language only through the selected codec.
2
3use super::*;
4
5impl Host {
6    /// Execute an admitted native call through its codec-compatible entrypoint.
7    pub async fn invoke_portable(&self, call: core::Invocation, arguments: Value) -> Result<Value> {
8        let (environment, handle) = {
9            let objects = self.0.objects.borrow();
10            let object = objects
11                .get(&call.object)
12                .and_then(|object| object.versions.get(&call.orb))
13                .ok_or_else(|| Error::invalid(Reason::NativeObject, "object is not activated"))?;
14            (
15                object.environment.clone(),
16                object
17                    .implementation
18                    .portable
19                    .get(&call.method)
20                    .cloned()
21                    .ok_or_else(|| Error::invalid(Reason::NativeMethod, &call.method))?,
22            )
23        };
24        let entered = self.context(call.root, Some(call))?;
25        // JSON and RPC callers are data-only: a capability-bearing result, including a stream
26        // end, is refused and closed. This boundary cannot hand out an early result, so it
27        // returns, with a value or an error, only after the call's physical work has ended.
28        let host = self.clone();
29        self.spawn(async move {
30            let (head, physical) = handle(
31                environment,
32                entered,
33                crate::portable::Payload::data(arguments),
34            )
35            .await?
36            .into_parts();
37            let value = head.and_then(crate::portable::Payload::data_only);
38            let settled = match physical {
39                Some(physical) => physical.await,
40                None => Ok(()),
41            };
42            match (value, settled) {
43                (Ok(value), settled) => settled.map(|()| value),
44                // The head's error is the one returned; a physical failure behind it would
45                // otherwise be lost, so it is recorded like any other late physical failure.
46                (Err(primary), Err(physical)) => {
47                    host.0.errors.borrow_mut().push(physical);
48                    Err(primary)
49                }
50                (Err(primary), Ok(())) => Err(primary),
51            }
52        })?
53        .await
54        .map_err(|_| Error::invalid(Reason::Executor, "native callback executor stopped"))?
55    }
56
57    /// Encode a value only if its declaration permits language crossing.
58    pub fn portable_value(&self, id: core::Id) -> Result<Value> {
59        let encoder = self
60            .0
61            .values
62            .borrow()
63            .get(&id)
64            .and_then(|record| record.portable.clone())
65            .ok_or_else(|| Error::invalid(Reason::LocalValue, "this Rust value is not portable"))?;
66        encoder()
67    }
68
69    /// Retain a typed value with an optional lazy portable encoder.
70    pub(crate) fn store<T: Serialize + 'static>(
71        &self,
72        value: T,
73        portable: bool,
74    ) -> Result<core::Id> {
75        let id = self.kernel().allocate_handle()?;
76        let value = Rc::new(value);
77        let serialized = value.clone();
78        let encoder: Option<Encoder> = portable.then(|| {
79            Rc::new(move || {
80                serde_json::to_value(&*serialized)
81                    .map_err(|error| Error::invalid(Reason::Serialization, error.to_string()))
82            }) as Encoder
83        });
84        self.0.values.borrow_mut().insert(
85            id,
86            ValueRecord {
87                value,
88                portable: encoder,
89            },
90        );
91        Ok(id)
92    }
93
94    /// Resolve a retained native value with checked type conversion.
95    pub(crate) fn value<T: 'static>(&self, id: core::Id) -> Result<Rc<T>> {
96        self.0
97            .values
98            .borrow()
99            .get(&id)
100            .ok_or_else(type_error)?
101            .value
102            .clone()
103            .downcast()
104            .map_err(|_| type_error())
105    }
106
107    /// Release one native bridge value.
108    pub fn drop_value(&self, id: core::Id) {
109        self.0.values.borrow_mut().remove(&id);
110    }
111}