Skip to main content

tembra_runtime/
portable.rs

1//! Host-issued capabilities at the native portable boundary.
2//!
3//! A portable call moves one [`Payload`]: JSON-shaped data plus host-issued capabilities that
4//! JSON cannot express. The issuing executor supplies each capability as an opaque
5//! [`Capability`] backend; this crate never names the executor's types. Ownership is plain Rust
6//! ownership. Dropping the last holder of an issued capability is its close request, so a
7//! result that is refused, undelivered or abandoned closes exactly once.
8//!
9//! Capabilities never authorize calls by themselves. An [`Owned`] handle calls through its own
10//! duplicated kernel claim with the ordinary admission checks. The implicit `self` travels as a
11//! [`Loan`] that only the issuer can interpret.
12//!
13//! A native exporter issues a plain Rust value as a capability of a WIT resource type: the type
14//! names its resource type ([`Issuable`]), [`Payload::issue`] issues the value and places its
15//! [`Slot`] wherever the result's data names it, and a method reads its implicit `self` back as
16//! the value through the [`Receiver`] of [`Payload::receiver`], or holds it across its awaits with
17//! the receiver's [`Guard`]. The value belongs to the object version that issued it, as a compiled
18//! exporter's instance belongs to its Store: it closes with its last owner, and with that version
19//! when the exporter is reloaded or released or the host closes, whatever handles remain, once the
20//! calls holding it have ended. A method on such a handle then answers as it would for
21//! a compiled exporter: `Gone/resource` from the reloaded exporter, and the kernel's refusal of
22//! the call once the object is released or the host has closed.
23//!
24//! A payload may also carry the end of a byte stream ([`ByteStream`]). The physical work that
25//! produces it never travels in a payload: a provider returns it beside its result in an
26//! [`Outcome`], and the call's own managed task keeps driving it under the call's invocation.
27use crate::{Context, Error, Host, Reference, Result, core, core::Reason};
28use futures::{FutureExt, future::LocalBoxFuture};
29use serde::{Serialize, de::DeserializeOwned};
30use serde_json::Value;
31use std::{
32    any::Any,
33    cell::{Cell, RefCell},
34    collections::BTreeMap,
35    future::Future,
36    marker::PhantomData,
37    rc::{Rc, Weak},
38};
39
40mod stream;
41pub(crate) use stream::RootStream;
42pub use stream::{ByteSource, ByteStream};
43
44/// Defining identity of a WIT resource type: its canonical interface and resource name.
45#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
46pub struct Nominal {
47    pub interface: String,
48    pub name: String,
49}
50
51/// An issuer's backend for one capability. Its `Drop` is the physical close request.
52/// Issuers recover their own type from a [`Loan`] with [`Loan::with_backend`].
53pub trait Capability: Any {
54    /// The resource type this capability was issued for.
55    fn nominal(&self) -> &Nominal;
56}
57
58/// A capability freshly issued into a payload. It has one owner, and the issuer keeps no
59/// strong reference to it.
60pub struct Issued(Rc<dyn Capability>);
61
62impl Issued {
63    /// Issue a capability whose backend is now owned only by the payload that carries it.
64    pub fn new(capability: impl Capability) -> Self {
65        Self(Rc::new(capability))
66    }
67
68    pub fn nominal(&self) -> &Nominal {
69        self.0.nominal()
70    }
71}
72
73/// A Rust type whose values a native exporter issues as capabilities of one WIT resource type.
74pub trait Issuable: 'static {
75    /// The resource type the values are issued as.
76    fn nominal() -> Nominal;
77}
78
79/// The issuing object version of a native exporter's resources. It owns the values it issued,
80/// as a compiled exporter's Store owns its instances; a handle only names an entry. The last
81/// owner's drop removes its entry, and the version's end drops the table, which closes every
82/// value still owned: the drain compiled exporters do on release and host close.
83#[derive(Default)]
84pub(crate) struct Issuer {
85    values: RefCell<BTreeMap<u64, Rc<dyn Any>>>,
86    next: Cell<u64>,
87}
88
89impl Issuer {
90    fn adopt(&self, value: Rc<dyn Any>) -> u64 {
91        let key = self.next.get();
92        self.next.set(key + 1);
93        self.values.borrow_mut().insert(key, value);
94        key
95    }
96
97    fn value(&self, key: u64) -> Option<Rc<dyn Any>> {
98        self.values.borrow().get(&key).cloned()
99    }
100
101    /// Remove a value. It drops outside the table's borrow: its drop may close other handles.
102    fn close(&self, key: u64) {
103        let value = self.values.borrow_mut().remove(&key);
104        drop(value);
105    }
106}
107
108/// The backend of an issued Rust value. It holds the value until the managed call that returns
109/// it stamps the issuing object, so a result refused or undelivered before then closes the value
110/// with the backend; afterwards it names the issuer's entry, which its last owner removes. A
111/// method's `self` stays pinned by the managed call until that call has physically ended.
112struct Backend {
113    nominal: Nominal,
114    place: RefCell<Place>,
115}
116
117enum Place {
118    Pending(Rc<dyn Any>),
119    Issued { issuer: Weak<Issuer>, key: u64 },
120}
121
122impl Backend {
123    fn adopt(&self, issuer: &Rc<Issuer>) {
124        let mut place = self.place.borrow_mut();
125        if let Place::Pending(value) = &*place {
126            let key = issuer.adopt(value.clone());
127            *place = Place::Issued {
128                issuer: Rc::downgrade(issuer),
129                key,
130            };
131        }
132    }
133}
134
135impl Capability for Backend {
136    fn nominal(&self) -> &Nominal {
137        &self.nominal
138    }
139}
140
141impl Drop for Backend {
142    /// The last owner's drop closes the value, unless its issuer has drained it already.
143    fn drop(&mut self) {
144        if let Place::Issued { issuer, key } = self.place.get_mut()
145            && let Some(issuer) = issuer.upgrade()
146        {
147            issuer.close(*key);
148        }
149    }
150}
151
152/// The implicit `self` of one call, read as the value a native exporter issued it from. The
153/// call pins the value, so the receiver reads it across awaits within the call. It cannot
154/// extend the value's life: retained beyond the call, it reads while an owner lives and answers
155/// `Gone/resource` once the last owner or the issuing object has closed the value.
156pub struct Receiver<T> {
157    issuer: Weak<Issuer>,
158    key: u64,
159    marker: PhantomData<T>,
160}
161
162impl<T: Issuable> Receiver<T> {
163    /// Read the value, or refuse as `Gone/resource` once it has closed.
164    pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> Result<R> {
165        let value = self
166            .issuer
167            .upgrade()
168            .and_then(|issuer| issuer.value(self.key))
169            .ok_or_else(resource_closed)?;
170        let value = (*value).downcast_ref::<T>().ok_or_else(mistyped)?;
171        Ok(read(value))
172    }
173
174    /// Hold the value for the rest of the call, for a method that awaits: the guard reads as the
175    /// value and keeps it alive while held, so a `&T` borrowed from it stays valid across the
176    /// method's awaits, as a component's `&self` does while its method is suspended. Held by the
177    /// method's future, it lasts until the call ends, also when the issuing object is reloaded or
178    /// released meanwhile. A value that has closed is refused as `Gone/resource`.
179    pub fn guard(&self) -> Result<Guard<'_, T>> {
180        let value = self
181            .issuer
182            .upgrade()
183            .and_then(|issuer| issuer.value(self.key))
184            .ok_or_else(resource_closed)?;
185        if !(*value).is::<T>() {
186            return Err(mistyped());
187        }
188        Ok(Guard {
189            value,
190            receiver: PhantomData,
191        })
192    }
193}
194
195/// A method's `self` held for the rest of its call, from [`Receiver::guard`]: it reads as the value,
196/// which it keeps alive while held. It borrows the receiver, which the call took from its payload.
197pub struct Guard<'a, T> {
198    value: Rc<dyn Any>,
199    receiver: PhantomData<&'a Receiver<T>>,
200}
201
202impl<T: Issuable> std::ops::Deref for Guard<'_, T> {
203    type Target = T;
204
205    fn deref(&self) -> &T {
206        (*self.value)
207            .downcast_ref::<T>()
208            .expect("a guard holds a value of its receiver's type")
209    }
210}
211
212/// The data slot of a capability issued by [`Payload::issue`]. It serializes as the capability's
213/// payload-local index, wherever the result's data names the resource: the whole result, a
214/// record field, a list element, a tuple position, an option, or a variant or result payload.
215#[must_use = "a slot names its capability in the result's data"]
216pub struct Slot(u32);
217
218impl Serialize for Slot {
219    fn serialize<S: serde::Serializer>(
220        &self,
221        serializer: S,
222    ) -> std::result::Result<S::Ok, S::Error> {
223        serializer.serialize_u32(self.0)
224    }
225}
226
227/// The payload-local index, for a result whose data is written without serde.
228impl From<Slot> for u32 {
229    fn from(slot: Slot) -> Self {
230        slot.0
231    }
232}
233
234/// The implicit `self` of one call. The managed call holds its physical owner separately;
235/// retaining this weak loan cannot extend the resource's lifetime.
236pub struct Loan(Weak<dyn Capability>);
237
238impl Loan {
239    /// Inspect the issuer's backend while it is alive; another issuer or an expired loan
240    /// yields `None`. The backend reference cannot escape the operation.
241    pub fn with_backend<T: Capability, R>(&self, operation: impl FnOnce(&T) -> R) -> Option<R> {
242        let owner = self.0.upgrade()?;
243        (&*owner as &dyn Any).downcast_ref::<T>().map(operation)
244    }
245}
246
247/// The one internal payload of portable calls: data plus capabilities addressed by
248/// payload-local indices. A bare number in `value` names nothing outside this payload.
249pub struct Payload {
250    value: Value,
251    owned: Vec<Issued>,
252    moved: Vec<Moved>,
253    receiver: Option<Loan>,
254    streams: Vec<ByteStream>,
255    /// The object version serving the call these arguments enter, stamped by the managed call.
256    issuer: Option<Weak<Issuer>>,
257}
258
259impl Payload {
260    /// A payload carrying only data.
261    pub fn data(value: Value) -> Self {
262        Self {
263            value,
264            owned: Vec::new(),
265            moved: Vec::new(),
266            receiver: None,
267            streams: Vec::new(),
268            issuer: None,
269        }
270    }
271
272    pub fn value(&self) -> &Value {
273        &self.value
274    }
275
276    /// Replace the data in place, keeping every capability.
277    pub fn map_value(mut self, map: impl FnOnce(Value) -> Result<Value>) -> Result<Self> {
278        self.value = map(std::mem::take(&mut self.value))?;
279        Ok(self)
280    }
281
282    /// Attach an owned capability and return its payload-local index for the data slot.
283    pub fn attach(&mut self, issued: Issued) -> u32 {
284        self.owned.push(issued);
285        u32::try_from(self.owned.len() - 1).expect("payload attachment count fits u32")
286    }
287
288    /// Move an existing resource into an argument. The caller relinquishes its owner now;
289    /// refused admission consumes and closes it rather than recreating a Wasm handle.
290    pub fn attach_argument(&mut self, owner: Owned) -> Result<u32> {
291        Ok(self.attach_moved(Moved::from_shared(Rc::new(owner))?))
292    }
293
294    /// Attach a move already redeemed by a trusted executor, without duplicating its claim.
295    pub fn attach_moved(&mut self, moved: Moved) -> u32 {
296        self.moved.push(moved);
297        u32::try_from(self.moved.len() - 1).expect("payload attachment count fits u32")
298    }
299
300    /// Consume the typed owned arguments; their data positions are checked by the executor.
301    pub fn take_arguments(&mut self) -> Vec<Moved> {
302        std::mem::take(&mut self.moved)
303    }
304
305    /// Attach a stream end and return its payload-local index for the data slot.
306    pub fn attach_stream(&mut self, stream: ByteStream) -> u32 {
307        self.streams.push(stream);
308        u32::try_from(self.streams.len() - 1).expect("payload stream count fits u32")
309    }
310
311    /// Take the implicit `self` loan of this call, if any.
312    pub fn take_receiver(&mut self) -> Option<Loan> {
313        self.receiver.take()
314    }
315
316    /// Issue a Rust value as a capability of its WIT resource type. Place the returned [`Slot`]
317    /// where the result's data names the resource, and serialize that result with
318    /// [`Payload::encode`]. The value is this payload's until the call returns it: then it
319    /// belongs to the issuing object, and the delivered handle names it.
320    pub fn issue<T: Issuable>(&mut self, value: T) -> Slot {
321        Slot(self.attach(Issued::new(Backend {
322            nominal: T::nominal(),
323            place: RefCell::new(Place::Pending(Rc::new(value))),
324        })))
325    }
326
327    /// Replace the data with a serialized result, whose resource positions hold the slots this
328    /// payload issued.
329    pub fn encode(self, result: impl Serialize) -> Result<Self> {
330        self.map_value(|_| {
331            serde_json::to_value(result)
332                .map_err(|error| Error::invalid(Reason::Result, error.to_string()))
333        })
334    }
335
336    /// Take the implicit `self` of this call as the value it was issued from. A call without
337    /// `self` is refused, as is a `self` of another resource type (`Forbidden/resource`), of
338    /// another object or a retired revision of the exporter, or one that has closed
339    /// (`Gone/resource`).
340    pub fn receiver<T: Issuable>(&mut self) -> Result<Receiver<T>> {
341        let loan = self.receiver.take().ok_or_else(|| {
342            Error::invalid(
343                Reason::Resource,
344                "a resource method requires its owned handle",
345            )
346        })?;
347        let owner = loan.0.upgrade().ok_or_else(resource_closed)?;
348        let Some(backend) = (&*owner as &dyn Any).downcast_ref::<Backend>() else {
349            return Err(if *owner.nominal() == T::nominal() {
350                another_issuer()
351            } else {
352                mistyped()
353            });
354        };
355        if backend.nominal != T::nominal() {
356            return Err(mistyped());
357        }
358        let (issuer, key) = match &*backend.place.borrow() {
359            Place::Issued { issuer, key } => (issuer.clone(), *key),
360            Place::Pending(_) => return Err(another_issuer()),
361        };
362        if !self
363            .issuer
364            .as_ref()
365            .is_some_and(|current| Weak::ptr_eq(current, &issuer))
366        {
367            return Err(another_issuer());
368        }
369        let receiver = Receiver {
370            issuer,
371            key,
372            marker: PhantomData,
373        };
374        receiver.with(|_| ())?;
375        Ok(receiver)
376    }
377
378    /// Receive a moved native value only in its exact issuing object and resource type.
379    /// Outstanding method guards keep their value alive and prevent exclusive extraction.
380    pub fn receive<T: Issuable>(&self, moved: Moved) -> Result<T> {
381        if moved.nominal() != &T::nominal() {
382            return Err(mistyped());
383        }
384        let backend = (&*moved.capability as &dyn Any)
385            .downcast_ref::<Backend>()
386            .ok_or_else(another_issuer)?;
387        let (issuer, key) = match &*backend.place.borrow() {
388            Place::Issued { issuer, key } => (issuer.clone(), *key),
389            Place::Pending(_) => return Err(another_issuer()),
390        };
391        if !self
392            .issuer
393            .as_ref()
394            .is_some_and(|current| Weak::ptr_eq(current, &issuer))
395        {
396            return Err(another_issuer());
397        }
398        let issuer = issuer.upgrade().ok_or_else(resource_closed)?;
399        let value = issuer
400            .values
401            .borrow_mut()
402            .remove(&key)
403            .ok_or_else(resource_closed)?;
404        let value = value.downcast::<T>().map_err(|_| mistyped())?;
405        Rc::try_unwrap(value).map_err(|_| {
406            Error::invalid(
407                Reason::Resource,
408                "a physically borrowed resource cannot move into a native value",
409            )
410        })
411    }
412
413    /// Whether the payload carries no capability at all.
414    pub fn is_data(&self) -> bool {
415        self.receiver.is_none()
416            && self.owned.is_empty()
417            && self.moved.is_empty()
418            && self.streams.is_empty()
419    }
420
421    /// Return the data of a call to an exporter's function without `self`: a `self` lent to it
422    /// is refused as a compiled exporter's function refuses it, `Invalid/resource`, and any other
423    /// capability as a data-only boundary refuses it, `Invalid/local_value`. Refused, they drop
424    /// and so close.
425    pub fn into_data(self) -> Result<Value> {
426        if self.receiver.is_some() {
427            return Err(Error::invalid(
428                Reason::Resource,
429                "this function takes no resource receiver",
430            ));
431        }
432        self.data_only()
433    }
434
435    /// Return the data of a data-only payload, as a data-only boundary or a method taking data
436    /// only reads it: every capability, a lent `self` too, is refused as `Invalid/local_value`,
437    /// which drops and so closes it.
438    pub(crate) fn data_only(self) -> Result<Value> {
439        if self.is_data() {
440            Ok(self.value)
441        } else {
442            Err(capability_refused())
443        }
444    }
445
446    /// Bind every stream end of a result to the calling root, once, before any consumer
447    /// decoder sees the payload: whatever the decoder keeps, the root's end closes it and its
448    /// cancellation cancels it. A data result does nothing here.
449    pub(crate) fn bind_streams(&self, origin: &Origin) -> Result<()> {
450        for stream in &self.streams {
451            origin.bind(stream)?;
452        }
453        Ok(())
454    }
455
456    pub(crate) fn with_receiver(mut self, loan: Loan) -> Result<Self> {
457        if self.receiver.is_some() {
458            return Err(Error::invalid(
459                Reason::Arguments,
460                "a call has at most one implicit self",
461            ));
462        }
463        self.receiver = Some(loan);
464        Ok(self)
465    }
466
467    /// Enter the call that `issuer`'s object version serves. Newly issued capabilities cannot
468    /// become arguments without a calling claim. Existing moved owners keep their exact claim.
469    /// Pin implicit self outside the provider's payload so retaining that payload cannot keep a
470    /// resource alive after the physical call settles.
471    pub(crate) fn for_call(
472        mut self,
473        issuer: &Rc<Issuer>,
474    ) -> Result<(Self, Option<Rc<dyn Capability>>)> {
475        self.issuer = Some(Rc::downgrade(issuer));
476        if !self.owned.is_empty() {
477            return Err(Error::invalid(
478                Reason::Arguments,
479                "an issued result cannot become an argument without an ownership claim",
480            ));
481        }
482        if !self.streams.is_empty() {
483            return Err(Error::invalid(
484                Reason::Arguments,
485                "stream arguments are not supported",
486            ));
487        }
488        let owner = self
489            .receiver
490            .as_ref()
491            .map(|loan| loan.0.upgrade().ok_or_else(resource_closed))
492            .transpose()?;
493        Ok((self, owner))
494    }
495
496    /// Give every value this result issued to the object version returning it: from here on
497    /// its last owner removes it from that object, and the object's end closes it.
498    pub(crate) fn issued_by(self, issuer: &Rc<Issuer>) -> Self {
499        for issued in &self.owned {
500            if let Some(backend) = (&*issued.0 as &dyn Any).downcast_ref::<Backend>() {
501                backend.adopt(issuer);
502            }
503        }
504        self
505    }
506}
507
508fn resource_closed() -> Error {
509    Error::new(core::Code::Gone, Reason::Resource, "resource has closed")
510}
511
512fn another_issuer() -> Error {
513    Error::new(
514        core::Code::Gone,
515        Reason::Resource,
516        "the resource belongs to another object or a retired revision",
517    )
518}
519
520fn mistyped() -> Error {
521    Error::new(
522        core::Code::Forbidden,
523        Reason::Resource,
524        "the resource has another type",
525    )
526}
527
528/// Refusal of capabilities by a data-only boundary (JSON, RPC or a foreign host).
529pub(crate) fn capability_refused() -> Error {
530    Error::invalid(
531        Reason::LocalValue,
532        "a data-only boundary cannot carry host capabilities",
533    )
534}
535
536/// Arguments of a portable call: ordinary Serde values, or a payload moved as is.
537pub trait IntoPayload {
538    fn into_payload(self) -> Result<Payload>;
539}
540
541impl<T: Serialize> IntoPayload for T {
542    fn into_payload(self) -> Result<Payload> {
543        serde_json::to_value(&self)
544            .map(Payload::data)
545            .map_err(|error| Error::invalid(Reason::Arguments, error.to_string()))
546    }
547}
548
549impl IntoPayload for Payload {
550    fn into_payload(self) -> Result<Payload> {
551        if self.receiver.is_some() {
552            return Err(Error::invalid(
553                Reason::Arguments,
554                "a borrowed receiver cannot be forwarded",
555            ));
556        }
557        Ok(self)
558    }
559}
560
561/// Results of a portable call. Decoding runs inside the provider's managed call, before the
562/// kernel invocation finishes, so ownership exists before delivery can fail.
563pub trait FromPayload: Sized {
564    fn from_payload(payload: Payload, origin: &Origin) -> Result<Self>;
565}
566
567impl<T: DeserializeOwned> FromPayload for T {
568    fn from_payload(payload: Payload, _: &Origin) -> Result<Self> {
569        serde_json::from_value(payload.data_only()?)
570            .map_err(|error| Error::invalid(Reason::Result, error.to_string()))
571    }
572}
573
574impl FromPayload for Owned {
575    /// A bare `own` result: the data names the only attachment.
576    fn from_payload(mut payload: Payload, origin: &Origin) -> Result<Self> {
577        let index = payload
578            .value
579            .as_u64()
580            .and_then(|index| usize::try_from(index).ok());
581        let single = payload.receiver.is_none()
582            && payload.moved.is_empty()
583            && payload.streams.is_empty()
584            && payload.owned.len() == 1;
585        let issued = index
586            .filter(|index| single && *index == 0)
587            .and_then(|_| payload.owned.pop())
588            .ok_or_else(|| {
589                Error::invalid(
590                    Reason::Result,
591                    "an owned result names exactly one capability",
592                )
593            })?;
594        Owned::anchor(issued, origin)
595    }
596}
597
598/// A payload result for executors: data, every owned capability, each anchored here, and every
599/// stream end, already bound to the calling root by the call. A data-only result allocates no
600/// claim and moves its value without conversion; a stream end takes no claim either.
601pub struct Delivered {
602    pub value: Value,
603    pub owned: Vec<Owned>,
604    pub streams: Vec<ByteStream>,
605}
606
607impl FromPayload for Delivered {
608    fn from_payload(payload: Payload, origin: &Origin) -> Result<Self> {
609        let Payload {
610            value,
611            owned,
612            moved,
613            receiver,
614            streams,
615            issuer: _,
616        } = payload;
617        if receiver.is_some() || !moved.is_empty() {
618            return Err(Error::invalid(
619                Reason::Result,
620                "a result cannot carry argument moves or lend self",
621            ));
622        }
623        let owned = owned
624            .into_iter()
625            .map(|issued| Owned::anchor(issued, origin))
626            .collect::<Result<_>>()?;
627        Ok(Self {
628            value,
629            owned,
630            streams,
631        })
632    }
633}
634
635impl FromPayload for ByteStream {
636    /// A whole `stream<u8>` result: the data names the only attachment, a stream end. The call
637    /// already bound it to the calling root before decoding.
638    fn from_payload(mut payload: Payload, _: &Origin) -> Result<Self> {
639        let whole = payload.receiver.is_none()
640            && payload.owned.is_empty()
641            && payload.moved.is_empty()
642            && payload.streams.len() == 1
643            && payload.value.as_u64() == Some(0);
644        let stream = payload.streams.pop().filter(|_| whole).ok_or_else(|| {
645            Error::invalid(Reason::Result, "a stream result names exactly one stream")
646        })?;
647        Ok(stream)
648    }
649}
650
651/// The calling claim of one portable call, as seen by its result decoding.
652pub struct Origin {
653    host: Host,
654    reference: core::Id,
655    object: core::Id,
656    foreign: bool,
657    revision: core::Id,
658    root: core::Id,
659}
660
661impl Origin {
662    pub(crate) fn new(
663        host: Host,
664        reference: core::Id,
665        object: core::Id,
666        foreign: bool,
667        revision: core::Id,
668        root: core::Id,
669    ) -> Self {
670        Self {
671            host,
672            reference,
673            object,
674            foreign,
675            revision,
676            root,
677        }
678    }
679
680    /// Bind a decoded stream end to the calling root; refused once that root has ended or was
681    /// cancelled, which drops and so closes the end.
682    fn bind(&self, stream: &ByteStream) -> Result<()> {
683        if self.foreign {
684            return Err(capability_refused());
685        }
686        self.host.bind_root_stream(self.root, stream.root_stream())
687    }
688
689    /// An exact duplicate of the calling claim; refused once that claim was released.
690    fn anchor(&self) -> Result<Reference> {
691        if self.foreign {
692            return Err(capability_refused());
693        }
694        self.host.duplicate_reference(self.reference, self.object)
695    }
696}
697
698/// An owned WIT resource handle held by native code. Dropping it is the WIT drop. It is not
699/// `Clone`. It closes its capability first and then releases its own admission claim.
700pub struct Owned {
701    capability: RefCell<Option<Rc<dyn Capability>>>,
702    anchor: RefCell<Option<Rc<Reference>>>,
703    nominal: Nominal,
704    revision: core::Id,
705}
706
707/// One linear move of an existing owner. It retains the exact original admission claim;
708/// receiving it creates a new live wrapper, while all aliases of the sender stay revoked.
709/// The capability is closed only after this move and any physical borrows have ended.
710pub struct Moved {
711    capability: Rc<dyn Capability>,
712    anchor: Rc<Reference>,
713    revision: core::Id,
714}
715
716impl Moved {
717    /// Revoke a table-owned sender before its admission can suspend. Existing physical calls
718    /// keep their own pins, but no alias can issue another method after the move.
719    pub fn from_shared(owner: Rc<Owned>) -> Result<Self> {
720        let capability = owner
721            .capability
722            .borrow_mut()
723            .take()
724            .ok_or_else(moved_owner)?;
725        let anchor = owner
726            .anchor
727            .borrow_mut()
728            .take()
729            .expect("a live owner has its claim");
730        Ok(Self {
731            capability,
732            anchor,
733            revision: owner.revision,
734        })
735    }
736
737    pub fn nominal(&self) -> &Nominal {
738        self.capability.nominal()
739    }
740
741    /// Inspect the original issuer backend without exposing or duplicating its authority.
742    pub fn with_backend<T: Capability, R>(&self, operation: impl FnOnce(&T) -> R) -> Option<R> {
743        (&*self.capability as &dyn Any)
744            .downcast_ref::<T>()
745            .map(operation)
746    }
747
748    /// Receive the moved owner under the same claim, never under the receiving Orb's claim.
749    pub fn receive(self) -> Owned {
750        let nominal = self.capability.nominal().clone();
751        Owned {
752            capability: RefCell::new(Some(self.capability)),
753            anchor: RefCell::new(Some(self.anchor)),
754            nominal,
755            revision: self.revision,
756        }
757    }
758}
759
760impl Owned {
761    /// Bind an issued capability to its own duplicate of the calling claim. If the claim is
762    /// already gone, the capability is dropped, and so closed, with the error.
763    fn anchor(issued: Issued, origin: &Origin) -> Result<Self> {
764        let anchor = origin.anchor()?;
765        let nominal = issued.0.nominal().clone();
766        Ok(Self {
767            capability: RefCell::new(Some(issued.0)),
768            anchor: RefCell::new(Some(Rc::new(anchor))),
769            nominal,
770            revision: origin.revision,
771        })
772    }
773
774    fn claim(&self) -> Result<(Rc<dyn Capability>, Rc<Reference>)> {
775        let capability = self.capability.borrow().clone().ok_or_else(moved_owner)?;
776        let anchor = self.anchor.borrow().clone().ok_or_else(moved_owner)?;
777        Ok((capability, anchor))
778    }
779
780    pub fn nominal(&self) -> &Nominal {
781        &self.nominal
782    }
783
784    /// Read the issuing provider revision retained through ownership transfers.
785    pub fn revision(&self) -> core::Id {
786        self.revision
787    }
788
789    /// Inspect the resource's own admission claim without duplicating ownership.
790    #[cfg(feature = "rpc")]
791    pub(crate) fn reference(&self) -> Result<Rc<Reference>> {
792        self.claim().map(|(_, anchor)| anchor)
793    }
794
795    /// Call a method of this resource. The call is admitted on this handle's own claim with
796    /// every ordinary kernel check. The handle travels only as the call's implicit `self` loan.
797    pub async fn call_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
798        &self,
799        context: &Context,
800        method: &str,
801        arguments: A,
802    ) -> Result<R> {
803        let (capability, anchor) = self.claim()?;
804        let payload = arguments
805            .into_payload()?
806            .with_receiver(Loan(Rc::downgrade(&capability)))?;
807        anchor.call_borrowed(context, method, payload).await
808    }
809
810    /// Like [`Owned::call_portable`], with control of the admitted invocation: see
811    /// [`crate::Reference::issue_portable`].
812    pub async fn issue_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
813        &self,
814        context: &Context,
815        method: &str,
816        arguments: A,
817    ) -> Result<(crate::IssuedCall, LocalBoxFuture<'static, Result<R>>)> {
818        let (capability, anchor) = self.claim()?;
819        let payload = arguments
820            .into_payload()?
821            .with_receiver(Loan(Rc::downgrade(&capability)))?;
822        anchor.issue_borrowed(context, method, payload).await
823    }
824}
825
826fn moved_owner() -> Error {
827    Error::new(
828        core::Code::Gone,
829        Reason::Resource,
830        "resource ownership has moved",
831    )
832}
833
834/// What a portable provider returns: its logical result and, when the call keeps working after
835/// publishing it, that physical work.
836///
837/// The caller receives only the result. The physical work stays with the call's managed task,
838/// which holds the kernel invocation until the work ends; it is never part of a [`Payload`].
839pub struct Outcome {
840    head: Result<Payload>,
841    physical: Option<LocalBoxFuture<'static, Result<()>>>,
842}
843
844impl Outcome {
845    /// A result published before the call's physical work has ended. The work is driven to
846    /// its end even if the result is refused or nobody receives it.
847    pub fn continuing(
848        head: Result<Payload>,
849        physical: impl Future<Output = Result<()>> + 'static,
850    ) -> Self {
851        Self {
852            head,
853            physical: Some(physical.boxed_local()),
854        }
855    }
856
857    pub(crate) fn into_parts(
858        self,
859    ) -> (Result<Payload>, Option<LocalBoxFuture<'static, Result<()>>>) {
860        (self.head, self.physical)
861    }
862}
863
864/// An ordinary result: the call has physically ended when it returns.
865impl From<Payload> for Outcome {
866    fn from(payload: Payload) -> Self {
867        Self {
868            head: Ok(payload),
869            physical: None,
870        }
871    }
872}