1use 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#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
46pub struct Nominal {
47 pub interface: String,
48 pub name: String,
49}
50
51pub trait Capability: Any {
54 fn nominal(&self) -> &Nominal;
56}
57
58pub struct Issued(Rc<dyn Capability>);
61
62impl Issued {
63 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
73pub trait Issuable: 'static {
75 fn nominal() -> Nominal;
77}
78
79#[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 fn close(&self, key: u64) {
103 let value = self.values.borrow_mut().remove(&key);
104 drop(value);
105 }
106}
107
108struct 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 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
152pub struct Receiver<T> {
157 issuer: Weak<Issuer>,
158 key: u64,
159 marker: PhantomData<T>,
160}
161
162impl<T: Issuable> Receiver<T> {
163 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 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
195pub 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#[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
227impl From<Slot> for u32 {
229 fn from(slot: Slot) -> Self {
230 slot.0
231 }
232}
233
234pub struct Loan(Weak<dyn Capability>);
237
238impl Loan {
239 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
247pub struct Payload {
250 value: Value,
251 owned: Vec<Issued>,
252 moved: Vec<Moved>,
253 receiver: Option<Loan>,
254 streams: Vec<ByteStream>,
255 issuer: Option<Weak<Issuer>>,
257}
258
259impl Payload {
260 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 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 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 pub fn attach_argument(&mut self, owner: Owned) -> Result<u32> {
291 Ok(self.attach_moved(Moved::from_shared(Rc::new(owner))?))
292 }
293
294 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 pub fn take_arguments(&mut self) -> Vec<Moved> {
302 std::mem::take(&mut self.moved)
303 }
304
305 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 pub fn take_receiver(&mut self) -> Option<Loan> {
313 self.receiver.take()
314 }
315
316 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 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 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 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 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 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 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 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 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 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
528pub(crate) fn capability_refused() -> Error {
530 Error::invalid(
531 Reason::LocalValue,
532 "a data-only boundary cannot carry host capabilities",
533 )
534}
535
536pub 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
561pub 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 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
598pub 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 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
651pub 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 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 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
698pub struct Owned {
701 capability: RefCell<Option<Rc<dyn Capability>>>,
702 anchor: RefCell<Option<Rc<Reference>>>,
703 nominal: Nominal,
704 revision: core::Id,
705}
706
707pub struct Moved {
711 capability: Rc<dyn Capability>,
712 anchor: Rc<Reference>,
713 revision: core::Id,
714}
715
716impl Moved {
717 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 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 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 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 pub fn revision(&self) -> core::Id {
786 self.revision
787 }
788
789 #[cfg(feature = "rpc")]
791 pub(crate) fn reference(&self) -> Result<Rc<Reference>> {
792 self.claim().map(|(_, anchor)| anchor)
793 }
794
795 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 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
834pub struct Outcome {
840 head: Result<Payload>,
841 physical: Option<LocalBoxFuture<'static, Result<()>>>,
842}
843
844impl Outcome {
845 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
864impl From<Payload> for Outcome {
866 fn from(payload: Payload) -> Self {
867 Self {
868 head: Ok(payload),
869 physical: None,
870 }
871 }
872}