1use super::*;
4
5use crate::portable::{FromPayload, IntoPayload, Issuer, Origin, Payload};
6
7type Boundary<A, R> = (
10 Box<dyn FnOnce(A) -> Result<Payload>>,
11 Box<dyn FnOnce(Payload, &Origin) -> Result<R>>,
12);
13
14pub 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 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 pub fn id(&self) -> core::Id {
35 self.id
36 }
37
38 pub fn object(&self) -> core::Id {
40 self.object
41 }
42
43 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 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 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 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 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 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 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 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 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 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 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 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 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#[derive(Clone)]
338pub struct IssuedCall {
339 host: Host,
340 call: core::Id,
341}
342
343impl IssuedCall {
344 pub fn id(&self) -> core::Id {
346 self.call
347 }
348
349 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 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
371enum 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 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 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 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}