use crate::{Context, Error, Host, Reference, Result, core, core::Reason};
use futures::{FutureExt, future::LocalBoxFuture};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
use std::{
any::Any,
cell::{Cell, RefCell},
collections::BTreeMap,
future::Future,
marker::PhantomData,
rc::{Rc, Weak},
};
mod stream;
pub(crate) use stream::RootStream;
pub use stream::{ByteSource, ByteStream};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Nominal {
pub interface: String,
pub name: String,
}
pub trait Capability: Any {
fn nominal(&self) -> &Nominal;
}
pub struct Issued(Rc<dyn Capability>);
impl Issued {
pub fn new(capability: impl Capability) -> Self {
Self(Rc::new(capability))
}
pub fn nominal(&self) -> &Nominal {
self.0.nominal()
}
}
pub trait Issuable: 'static {
fn nominal() -> Nominal;
}
#[derive(Default)]
pub(crate) struct Issuer {
values: RefCell<BTreeMap<u64, Rc<dyn Any>>>,
next: Cell<u64>,
}
impl Issuer {
fn adopt(&self, value: Rc<dyn Any>) -> u64 {
let key = self.next.get();
self.next.set(key + 1);
self.values.borrow_mut().insert(key, value);
key
}
fn value(&self, key: u64) -> Option<Rc<dyn Any>> {
self.values.borrow().get(&key).cloned()
}
fn close(&self, key: u64) {
let value = self.values.borrow_mut().remove(&key);
drop(value);
}
}
struct Backend {
nominal: Nominal,
place: RefCell<Place>,
}
enum Place {
Pending(Rc<dyn Any>),
Issued { issuer: Weak<Issuer>, key: u64 },
}
impl Backend {
fn adopt(&self, issuer: &Rc<Issuer>) {
let mut place = self.place.borrow_mut();
if let Place::Pending(value) = &*place {
let key = issuer.adopt(value.clone());
*place = Place::Issued {
issuer: Rc::downgrade(issuer),
key,
};
}
}
}
impl Capability for Backend {
fn nominal(&self) -> &Nominal {
&self.nominal
}
}
impl Drop for Backend {
fn drop(&mut self) {
if let Place::Issued { issuer, key } = self.place.get_mut()
&& let Some(issuer) = issuer.upgrade()
{
issuer.close(*key);
}
}
}
pub struct Receiver<T> {
issuer: Weak<Issuer>,
key: u64,
marker: PhantomData<T>,
}
impl<T: Issuable> Receiver<T> {
pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> Result<R> {
let value = self
.issuer
.upgrade()
.and_then(|issuer| issuer.value(self.key))
.ok_or_else(resource_closed)?;
let value = (*value).downcast_ref::<T>().ok_or_else(mistyped)?;
Ok(read(value))
}
pub fn guard(&self) -> Result<Guard<'_, T>> {
let value = self
.issuer
.upgrade()
.and_then(|issuer| issuer.value(self.key))
.ok_or_else(resource_closed)?;
if !(*value).is::<T>() {
return Err(mistyped());
}
Ok(Guard {
value,
receiver: PhantomData,
})
}
}
pub struct Guard<'a, T> {
value: Rc<dyn Any>,
receiver: PhantomData<&'a Receiver<T>>,
}
impl<T: Issuable> std::ops::Deref for Guard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
(*self.value)
.downcast_ref::<T>()
.expect("a guard holds a value of its receiver's type")
}
}
#[must_use = "a slot names its capability in the result's data"]
pub struct Slot(u32);
impl Serialize for Slot {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_u32(self.0)
}
}
impl From<Slot> for u32 {
fn from(slot: Slot) -> Self {
slot.0
}
}
pub struct Loan(Weak<dyn Capability>);
impl Loan {
pub fn with_backend<T: Capability, R>(&self, operation: impl FnOnce(&T) -> R) -> Option<R> {
let owner = self.0.upgrade()?;
(&*owner as &dyn Any).downcast_ref::<T>().map(operation)
}
}
pub struct Payload {
value: Value,
owned: Vec<Issued>,
moved: Vec<Moved>,
receiver: Option<Loan>,
streams: Vec<ByteStream>,
issuer: Option<Weak<Issuer>>,
}
impl Payload {
pub fn data(value: Value) -> Self {
Self {
value,
owned: Vec::new(),
moved: Vec::new(),
receiver: None,
streams: Vec::new(),
issuer: None,
}
}
pub fn value(&self) -> &Value {
&self.value
}
pub fn map_value(mut self, map: impl FnOnce(Value) -> Result<Value>) -> Result<Self> {
self.value = map(std::mem::take(&mut self.value))?;
Ok(self)
}
pub fn attach(&mut self, issued: Issued) -> u32 {
self.owned.push(issued);
u32::try_from(self.owned.len() - 1).expect("payload attachment count fits u32")
}
pub fn attach_argument(&mut self, owner: Owned) -> Result<u32> {
Ok(self.attach_moved(Moved::from_shared(Rc::new(owner))?))
}
pub fn attach_moved(&mut self, moved: Moved) -> u32 {
self.moved.push(moved);
u32::try_from(self.moved.len() - 1).expect("payload attachment count fits u32")
}
pub fn take_arguments(&mut self) -> Vec<Moved> {
std::mem::take(&mut self.moved)
}
pub fn attach_stream(&mut self, stream: ByteStream) -> u32 {
self.streams.push(stream);
u32::try_from(self.streams.len() - 1).expect("payload stream count fits u32")
}
pub fn take_receiver(&mut self) -> Option<Loan> {
self.receiver.take()
}
pub fn issue<T: Issuable>(&mut self, value: T) -> Slot {
Slot(self.attach(Issued::new(Backend {
nominal: T::nominal(),
place: RefCell::new(Place::Pending(Rc::new(value))),
})))
}
pub fn encode(self, result: impl Serialize) -> Result<Self> {
self.map_value(|_| {
serde_json::to_value(result)
.map_err(|error| Error::invalid(Reason::Result, error.to_string()))
})
}
pub fn receiver<T: Issuable>(&mut self) -> Result<Receiver<T>> {
let loan = self.receiver.take().ok_or_else(|| {
Error::invalid(
Reason::Resource,
"a resource method requires its owned handle",
)
})?;
let owner = loan.0.upgrade().ok_or_else(resource_closed)?;
let Some(backend) = (&*owner as &dyn Any).downcast_ref::<Backend>() else {
return Err(if *owner.nominal() == T::nominal() {
another_issuer()
} else {
mistyped()
});
};
if backend.nominal != T::nominal() {
return Err(mistyped());
}
let (issuer, key) = match &*backend.place.borrow() {
Place::Issued { issuer, key } => (issuer.clone(), *key),
Place::Pending(_) => return Err(another_issuer()),
};
if !self
.issuer
.as_ref()
.is_some_and(|current| Weak::ptr_eq(current, &issuer))
{
return Err(another_issuer());
}
let receiver = Receiver {
issuer,
key,
marker: PhantomData,
};
receiver.with(|_| ())?;
Ok(receiver)
}
pub fn receive<T: Issuable>(&self, moved: Moved) -> Result<T> {
if moved.nominal() != &T::nominal() {
return Err(mistyped());
}
let backend = (&*moved.capability as &dyn Any)
.downcast_ref::<Backend>()
.ok_or_else(another_issuer)?;
let (issuer, key) = match &*backend.place.borrow() {
Place::Issued { issuer, key } => (issuer.clone(), *key),
Place::Pending(_) => return Err(another_issuer()),
};
if !self
.issuer
.as_ref()
.is_some_and(|current| Weak::ptr_eq(current, &issuer))
{
return Err(another_issuer());
}
let issuer = issuer.upgrade().ok_or_else(resource_closed)?;
let value = issuer
.values
.borrow_mut()
.remove(&key)
.ok_or_else(resource_closed)?;
let value = value.downcast::<T>().map_err(|_| mistyped())?;
Rc::try_unwrap(value).map_err(|_| {
Error::invalid(
Reason::Resource,
"a physically borrowed resource cannot move into a native value",
)
})
}
pub fn is_data(&self) -> bool {
self.receiver.is_none()
&& self.owned.is_empty()
&& self.moved.is_empty()
&& self.streams.is_empty()
}
pub fn into_data(self) -> Result<Value> {
if self.receiver.is_some() {
return Err(Error::invalid(
Reason::Resource,
"this function takes no resource receiver",
));
}
self.data_only()
}
pub(crate) fn data_only(self) -> Result<Value> {
if self.is_data() {
Ok(self.value)
} else {
Err(capability_refused())
}
}
pub(crate) fn bind_streams(&self, origin: &Origin) -> Result<()> {
for stream in &self.streams {
origin.bind(stream)?;
}
Ok(())
}
pub(crate) fn with_receiver(mut self, loan: Loan) -> Result<Self> {
if self.receiver.is_some() {
return Err(Error::invalid(
Reason::Arguments,
"a call has at most one implicit self",
));
}
self.receiver = Some(loan);
Ok(self)
}
pub(crate) fn for_call(
mut self,
issuer: &Rc<Issuer>,
) -> Result<(Self, Option<Rc<dyn Capability>>)> {
self.issuer = Some(Rc::downgrade(issuer));
if !self.owned.is_empty() {
return Err(Error::invalid(
Reason::Arguments,
"an issued result cannot become an argument without an ownership claim",
));
}
if !self.streams.is_empty() {
return Err(Error::invalid(
Reason::Arguments,
"stream arguments are not supported",
));
}
let owner = self
.receiver
.as_ref()
.map(|loan| loan.0.upgrade().ok_or_else(resource_closed))
.transpose()?;
Ok((self, owner))
}
pub(crate) fn issued_by(self, issuer: &Rc<Issuer>) -> Self {
for issued in &self.owned {
if let Some(backend) = (&*issued.0 as &dyn Any).downcast_ref::<Backend>() {
backend.adopt(issuer);
}
}
self
}
}
fn resource_closed() -> Error {
Error::new(core::Code::Gone, Reason::Resource, "resource has closed")
}
fn another_issuer() -> Error {
Error::new(
core::Code::Gone,
Reason::Resource,
"the resource belongs to another object or a retired revision",
)
}
fn mistyped() -> Error {
Error::new(
core::Code::Forbidden,
Reason::Resource,
"the resource has another type",
)
}
pub(crate) fn capability_refused() -> Error {
Error::invalid(
Reason::LocalValue,
"a data-only boundary cannot carry host capabilities",
)
}
pub trait IntoPayload {
fn into_payload(self) -> Result<Payload>;
}
impl<T: Serialize> IntoPayload for T {
fn into_payload(self) -> Result<Payload> {
serde_json::to_value(&self)
.map(Payload::data)
.map_err(|error| Error::invalid(Reason::Arguments, error.to_string()))
}
}
impl IntoPayload for Payload {
fn into_payload(self) -> Result<Payload> {
if self.receiver.is_some() {
return Err(Error::invalid(
Reason::Arguments,
"a borrowed receiver cannot be forwarded",
));
}
Ok(self)
}
}
pub trait FromPayload: Sized {
fn from_payload(payload: Payload, origin: &Origin) -> Result<Self>;
}
impl<T: DeserializeOwned> FromPayload for T {
fn from_payload(payload: Payload, _: &Origin) -> Result<Self> {
serde_json::from_value(payload.data_only()?)
.map_err(|error| Error::invalid(Reason::Result, error.to_string()))
}
}
impl FromPayload for Owned {
fn from_payload(mut payload: Payload, origin: &Origin) -> Result<Self> {
let index = payload
.value
.as_u64()
.and_then(|index| usize::try_from(index).ok());
let single = payload.receiver.is_none()
&& payload.moved.is_empty()
&& payload.streams.is_empty()
&& payload.owned.len() == 1;
let issued = index
.filter(|index| single && *index == 0)
.and_then(|_| payload.owned.pop())
.ok_or_else(|| {
Error::invalid(
Reason::Result,
"an owned result names exactly one capability",
)
})?;
Owned::anchor(issued, origin)
}
}
pub struct Delivered {
pub value: Value,
pub owned: Vec<Owned>,
pub streams: Vec<ByteStream>,
}
impl FromPayload for Delivered {
fn from_payload(payload: Payload, origin: &Origin) -> Result<Self> {
let Payload {
value,
owned,
moved,
receiver,
streams,
issuer: _,
} = payload;
if receiver.is_some() || !moved.is_empty() {
return Err(Error::invalid(
Reason::Result,
"a result cannot carry argument moves or lend self",
));
}
let owned = owned
.into_iter()
.map(|issued| Owned::anchor(issued, origin))
.collect::<Result<_>>()?;
Ok(Self {
value,
owned,
streams,
})
}
}
impl FromPayload for ByteStream {
fn from_payload(mut payload: Payload, _: &Origin) -> Result<Self> {
let whole = payload.receiver.is_none()
&& payload.owned.is_empty()
&& payload.moved.is_empty()
&& payload.streams.len() == 1
&& payload.value.as_u64() == Some(0);
let stream = payload.streams.pop().filter(|_| whole).ok_or_else(|| {
Error::invalid(Reason::Result, "a stream result names exactly one stream")
})?;
Ok(stream)
}
}
pub struct Origin {
host: Host,
reference: core::Id,
object: core::Id,
foreign: bool,
revision: core::Id,
root: core::Id,
}
impl Origin {
pub(crate) fn new(
host: Host,
reference: core::Id,
object: core::Id,
foreign: bool,
revision: core::Id,
root: core::Id,
) -> Self {
Self {
host,
reference,
object,
foreign,
revision,
root,
}
}
fn bind(&self, stream: &ByteStream) -> Result<()> {
if self.foreign {
return Err(capability_refused());
}
self.host.bind_root_stream(self.root, stream.root_stream())
}
fn anchor(&self) -> Result<Reference> {
if self.foreign {
return Err(capability_refused());
}
self.host.duplicate_reference(self.reference, self.object)
}
}
pub struct Owned {
capability: RefCell<Option<Rc<dyn Capability>>>,
anchor: RefCell<Option<Rc<Reference>>>,
nominal: Nominal,
revision: core::Id,
}
pub struct Moved {
capability: Rc<dyn Capability>,
anchor: Rc<Reference>,
revision: core::Id,
}
impl Moved {
pub fn from_shared(owner: Rc<Owned>) -> Result<Self> {
let capability = owner
.capability
.borrow_mut()
.take()
.ok_or_else(moved_owner)?;
let anchor = owner
.anchor
.borrow_mut()
.take()
.expect("a live owner has its claim");
Ok(Self {
capability,
anchor,
revision: owner.revision,
})
}
pub fn nominal(&self) -> &Nominal {
self.capability.nominal()
}
pub fn with_backend<T: Capability, R>(&self, operation: impl FnOnce(&T) -> R) -> Option<R> {
(&*self.capability as &dyn Any)
.downcast_ref::<T>()
.map(operation)
}
pub fn receive(self) -> Owned {
let nominal = self.capability.nominal().clone();
Owned {
capability: RefCell::new(Some(self.capability)),
anchor: RefCell::new(Some(self.anchor)),
nominal,
revision: self.revision,
}
}
}
impl Owned {
fn anchor(issued: Issued, origin: &Origin) -> Result<Self> {
let anchor = origin.anchor()?;
let nominal = issued.0.nominal().clone();
Ok(Self {
capability: RefCell::new(Some(issued.0)),
anchor: RefCell::new(Some(Rc::new(anchor))),
nominal,
revision: origin.revision,
})
}
fn claim(&self) -> Result<(Rc<dyn Capability>, Rc<Reference>)> {
let capability = self.capability.borrow().clone().ok_or_else(moved_owner)?;
let anchor = self.anchor.borrow().clone().ok_or_else(moved_owner)?;
Ok((capability, anchor))
}
pub fn nominal(&self) -> &Nominal {
&self.nominal
}
pub fn revision(&self) -> core::Id {
self.revision
}
#[cfg(feature = "rpc")]
pub(crate) fn reference(&self) -> Result<Rc<Reference>> {
self.claim().map(|(_, anchor)| anchor)
}
pub async fn call_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
&self,
context: &Context,
method: &str,
arguments: A,
) -> Result<R> {
let (capability, anchor) = self.claim()?;
let payload = arguments
.into_payload()?
.with_receiver(Loan(Rc::downgrade(&capability)))?;
anchor.call_borrowed(context, method, payload).await
}
pub async fn issue_portable<A: IntoPayload + 'static, R: FromPayload + 'static>(
&self,
context: &Context,
method: &str,
arguments: A,
) -> Result<(crate::IssuedCall, LocalBoxFuture<'static, Result<R>>)> {
let (capability, anchor) = self.claim()?;
let payload = arguments
.into_payload()?
.with_receiver(Loan(Rc::downgrade(&capability)))?;
anchor.issue_borrowed(context, method, payload).await
}
}
fn moved_owner() -> Error {
Error::new(
core::Code::Gone,
Reason::Resource,
"resource ownership has moved",
)
}
pub struct Outcome {
head: Result<Payload>,
physical: Option<LocalBoxFuture<'static, Result<()>>>,
}
impl Outcome {
pub fn continuing(
head: Result<Payload>,
physical: impl Future<Output = Result<()>> + 'static,
) -> Self {
Self {
head,
physical: Some(physical.boxed_local()),
}
}
pub(crate) fn into_parts(
self,
) -> (Result<Payload>, Option<LocalBoxFuture<'static, Result<()>>>) {
(self.head, self.physical)
}
}
impl From<Payload> for Outcome {
fn from(payload: Payload) -> Self {
Self {
head: Ok(payload),
physical: None,
}
}
}