use crate::encoding::{
decode_transaction_header, Decode, Decoder, DefaultFuchsiaResourceDialect, DynamicFlags,
Encode, Encoder, EpitaphBody, MessageBufFor, ProxyChannelBox, ProxyChannelFor, ResourceDialect,
TransactionHeader, TransactionMessage, TransactionMessageType, TypeMarker,
};
use crate::Error;
use fuchsia_sync::Mutex;
use futures::future::{self, FusedFuture, Future, FutureExt, Map, MaybeDone};
use futures::ready;
use futures::stream::{FusedStream, Stream};
use futures::task::{Context, Poll, Waker};
use slab::Slab;
use std::collections::VecDeque;
use std::mem;
use std::ops::ControlFlow;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{RawWaker, RawWakerVTable};
use zx_status;
#[doc(hidden)] pub fn decode_transaction_body<T: TypeMarker, D: ResourceDialect, const EXPECTED_ORDINAL: u64>(
mut buf: D::MessageBufEtc,
) -> Result<T::Owned, Error>
where
T::Owned: Decode<T, D>,
{
let (bytes, handles) = buf.split_mut();
let (header, body_bytes) = decode_transaction_header(bytes)?;
if header.ordinal != EXPECTED_ORDINAL {
return Err(Error::InvalidResponseOrdinal);
}
let mut output = Decode::<T, D>::new_empty();
Decoder::<D>::decode_into::<T>(&header, body_bytes, handles, &mut output)?;
Ok(output)
}
#[derive(Debug, Clone)]
pub struct Client<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
inner: Arc<ClientInner<D>>,
}
pub type DecodedQueryResponseFut<T, D = DefaultFuchsiaResourceDialect> = Map<
MessageResponse<D>,
fn(Result<<D as ResourceDialect>::MessageBufEtc, Error>) -> Result<T, Error>,
>;
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct QueryResponseFut<T, D: ResourceDialect = DefaultFuchsiaResourceDialect>(
pub MaybeDone<DecodedQueryResponseFut<T, D>>,
);
impl<T: Unpin, D: ResourceDialect> FusedFuture for QueryResponseFut<T, D> {
fn is_terminated(&self) -> bool {
matches!(self.0, MaybeDone::Gone)
}
}
impl<T: Unpin, D: ResourceDialect> Future for QueryResponseFut<T, D> {
type Output = Result<T, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
ready!(self.0.poll_unpin(cx));
let maybe_done = Pin::new(&mut self.0);
Poll::Ready(maybe_done.take_output().unwrap_or(Err(Error::PollAfterCompletion)))
}
}
impl<T> QueryResponseFut<T> {
pub fn check(self) -> Result<Self, Error> {
match self.0 {
MaybeDone::Done(Err(e)) => Err(e),
x => Ok(QueryResponseFut(x)),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Txid(u32);
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct InterestId(usize);
impl InterestId {
fn from_txid(txid: Txid) -> Self {
InterestId(txid.0 as usize - 1)
}
}
impl Txid {
fn from_interest_id(int_id: InterestId) -> Self {
Txid((int_id.0 + 1) as u32)
}
pub fn as_raw_id(&self) -> u32 {
self.0
}
}
impl From<u32> for Txid {
fn from(txid: u32) -> Self {
Self(txid)
}
}
impl<D: ResourceDialect> Client<D> {
pub fn new(channel: D::ProxyChannel, protocol_name: &'static str) -> Client<D> {
Client {
inner: Arc::new(ClientInner {
channel: channel.boxed(),
interests: Mutex::default(),
terminal_error: Mutex::default(),
protocol_name,
}),
}
}
pub fn as_channel(&self) -> &D::ProxyChannel {
self.inner.channel.as_channel()
}
pub fn into_channel(self) -> Result<D::ProxyChannel, Self> {
match Arc::try_unwrap(self.inner) {
Ok(inner) => {
if inner.interests.lock().messages.is_empty() || inner.channel.is_closed() {
Ok(inner.channel.unbox())
} else {
Err(Self { inner: Arc::new(inner) })
}
}
Err(inner) => Err(Self { inner }),
}
}
pub fn take_event_receiver(&self) -> EventReceiver<D> {
{
let mut lock = self.inner.interests.lock();
if let EventListener::None = lock.event_listener {
lock.event_listener = EventListener::WillPoll;
} else {
panic!("Event stream was already taken");
}
}
EventReceiver { inner: self.inner.clone(), state: EventReceiverState::Active }
}
pub fn send<T: TypeMarker>(
&self,
body: impl Encode<T, D>,
ordinal: u64,
dynamic_flags: DynamicFlags,
) -> Result<(), Error> {
let msg =
TransactionMessage { header: TransactionHeader::new(0, ordinal, dynamic_flags), body };
crate::encoding::with_tls_encoded::<TransactionMessageType<T>, D, ()>(
msg,
|bytes, handles| self.send_raw(bytes, handles),
)
}
pub fn send_query<Request: TypeMarker, Response: TypeMarker, const ORDINAL: u64>(
&self,
body: impl Encode<Request, D>,
dynamic_flags: DynamicFlags,
) -> QueryResponseFut<Response::Owned, D>
where
Response::Owned: Decode<Response, D>,
{
self.send_query_and_decode::<Request, Response::Owned>(
body,
ORDINAL,
dynamic_flags,
|buf| buf.and_then(decode_transaction_body::<Response, D, ORDINAL>),
)
}
pub fn send_query_and_decode<Request: TypeMarker, Output>(
&self,
body: impl Encode<Request, D>,
ordinal: u64,
dynamic_flags: DynamicFlags,
decode: fn(Result<D::MessageBufEtc, Error>) -> Result<Output, Error>,
) -> QueryResponseFut<Output, D> {
let send_result = self.send_raw_query(|tx_id, bytes, handles| {
let msg = TransactionMessage {
header: TransactionHeader::new(tx_id.as_raw_id(), ordinal, dynamic_flags),
body,
};
Encoder::encode::<TransactionMessageType<Request>>(bytes, handles, msg)?;
Ok(())
});
QueryResponseFut(match send_result {
Ok(res_fut) => future::maybe_done(res_fut.map(decode)),
Err(e) => MaybeDone::Done(Err(e)),
})
}
pub fn send_raw(
&self,
bytes: &[u8],
handles: &mut [<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition],
) -> Result<(), Error> {
match self.inner.channel.write_etc(bytes, handles) {
Ok(()) | Err(None) => Ok(()),
Err(Some(e)) => Err(Error::ClientWrite(e.into())),
}
}
pub fn send_raw_query<F>(&self, encode_msg: F) -> Result<MessageResponse<D>, Error>
where
F: for<'a, 'b> FnOnce(
Txid,
&'a mut Vec<u8>,
&'b mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
) -> Result<(), Error>,
{
let id = self.inner.interests.lock().register_msg_interest();
crate::encoding::with_tls_encode_buf::<_, D>(|bytes, handles| {
encode_msg(id, bytes, handles)?;
self.send_raw(bytes, handles)
})?;
Ok(MessageResponse { id, client: Some(self.inner.clone()) })
}
}
#[must_use]
#[derive(Debug)]
pub struct MessageResponse<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
id: Txid,
client: Option<Arc<ClientInner<D>>>,
}
impl<D: ResourceDialect> Unpin for MessageResponse<D> {}
impl<D: ResourceDialect> Future for MessageResponse<D> {
type Output = Result<D::MessageBufEtc, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let res;
{
let client = this.client.as_ref().ok_or(Error::PollAfterCompletion)?;
res = client.poll_recv_msg_response(this.id, cx);
}
if let Poll::Ready(Ok(_)) = res {
this.client.take().expect("MessageResponse polled after completion");
}
res
}
}
impl<D: ResourceDialect> Drop for MessageResponse<D> {
fn drop(&mut self) {
if let Some(client) = &self.client {
client.interests.lock().deregister(self.id);
}
}
}
#[derive(Debug)]
enum MessageInterest<D: ResourceDialect> {
WillPoll,
Waiting(Waker),
Received(D::MessageBufEtc),
Discard,
}
impl<D: ResourceDialect> MessageInterest<D> {
fn is_received(&self) -> bool {
matches!(*self, MessageInterest::Received(_))
}
fn unwrap_received(self) -> D::MessageBufEtc {
if let MessageInterest::Received(buf) = self {
buf
} else {
panic!("EXPECTED received message")
}
}
}
#[derive(Debug)]
enum EventReceiverState {
Active,
Terminal,
Terminated,
}
#[derive(Debug)]
pub struct EventReceiver<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
inner: Arc<ClientInner<D>>,
state: EventReceiverState,
}
impl<D: ResourceDialect> Unpin for EventReceiver<D> {}
impl<D: ResourceDialect> FusedStream for EventReceiver<D> {
fn is_terminated(&self) -> bool {
matches!(self.state, EventReceiverState::Terminated)
}
}
impl<D: ResourceDialect> Stream for EventReceiver<D> {
type Item = Result<D::MessageBufEtc, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.state {
EventReceiverState::Active => {}
EventReceiverState::Terminated => {
panic!("polled EventReceiver after `None`");
}
EventReceiverState::Terminal => {
self.state = EventReceiverState::Terminated;
return Poll::Ready(None);
}
}
Poll::Ready(match ready!(self.inner.poll_recv_event(cx)) {
Ok(x) => Some(Ok(x)),
Err(Error::ClientChannelClosed { status: zx_status::Status::PEER_CLOSED, .. }) => {
self.state = EventReceiverState::Terminated;
None
}
err @ Err(_) => {
self.state = EventReceiverState::Terminal;
Some(err)
}
})
}
}
impl<D: ResourceDialect> Drop for EventReceiver<D> {
fn drop(&mut self) {
self.inner.interests.lock().dropped_event_listener();
}
}
#[derive(Debug, Default)]
enum EventListener {
#[default]
None,
WillPoll,
Some(Waker),
}
impl EventListener {
fn is_some(&self) -> bool {
matches!(self, EventListener::Some(_))
}
}
#[derive(Debug)]
struct ClientInner<D: ResourceDialect> {
channel: <D::ProxyChannel as ProxyChannelFor<D>>::Boxed,
interests: Mutex<Interests<D>>,
terminal_error: Mutex<Option<Error>>,
protocol_name: &'static str,
}
#[derive(Debug)]
struct Interests<D: ResourceDialect> {
messages: Slab<MessageInterest<D>>,
events: VecDeque<D::MessageBufEtc>,
event_listener: EventListener,
waker_count: usize,
}
impl<D: ResourceDialect> Default for Interests<D> {
fn default() -> Self {
Interests {
messages: Slab::new(),
events: Default::default(),
event_listener: Default::default(),
waker_count: 0,
}
}
}
impl<D: ResourceDialect> Interests<D> {
fn push_event(&mut self, buf: D::MessageBufEtc) -> Option<Waker> {
self.events.push_back(buf);
self.take_event_waker()
}
fn take_event_waker(&mut self) -> Option<Waker> {
if self.event_listener.is_some() {
let EventListener::Some(waker) =
mem::replace(&mut self.event_listener, EventListener::WillPoll)
else {
unreachable!()
};
self.waker_count -= 1;
Some(waker)
} else {
None
}
}
fn event_waker(&self) -> Option<&Waker> {
match &self.event_listener {
EventListener::Some(waker) => Some(waker),
_ => None,
}
}
fn push_message(&mut self, txid: Txid, buf: D::MessageBufEtc) -> Result<Option<Waker>, Error> {
let InterestId(raw_id) = InterestId::from_txid(txid);
let Some(interest) = self.messages.get_mut(raw_id) else {
return Err(Error::InvalidResponseTxid);
};
let mut waker = None;
if let MessageInterest::Discard = interest {
self.messages.remove(raw_id);
} else if let MessageInterest::Waiting(w) =
mem::replace(interest, MessageInterest::Received(buf))
{
waker = Some(w);
self.waker_count -= 1;
}
Ok(waker)
}
fn register(&mut self, txid: Txid, cx: &Context<'_>) -> Option<D::MessageBufEtc> {
let InterestId(raw_id) = InterestId::from_txid(txid);
let interest = self.messages.get_mut(raw_id).expect("Polled unregistered interest");
match interest {
MessageInterest::Received(_) => {
return Some(self.messages.remove(raw_id).unwrap_received())
}
MessageInterest::Discard => panic!("Polled a discarded MessageReceiver?!"),
MessageInterest::WillPoll => self.waker_count += 1,
MessageInterest::Waiting(_) => {}
}
*interest = MessageInterest::Waiting(cx.waker().clone());
None
}
fn deregister(&mut self, txid: Txid) {
let InterestId(raw_id) = InterestId::from_txid(txid);
match self.messages[raw_id] {
MessageInterest::Received(_) => {
self.messages.remove(raw_id);
return;
}
MessageInterest::WillPoll => {}
MessageInterest::Waiting(_) => self.waker_count -= 1,
MessageInterest::Discard => unreachable!(),
}
self.messages[raw_id] = MessageInterest::Discard;
}
fn register_event_listener(&mut self, cx: &Context<'_>) -> Option<D::MessageBufEtc> {
self.events.pop_front().or_else(|| {
if !mem::replace(&mut self.event_listener, EventListener::Some(cx.waker().clone()))
.is_some()
{
self.waker_count += 1;
}
None
})
}
fn dropped_event_listener(&mut self) {
if self.event_listener.is_some() {
self.waker_count -= 1;
}
self.event_listener = EventListener::None;
}
fn register_msg_interest(&mut self) -> Txid {
Txid::from_interest_id(InterestId(self.messages.insert(MessageInterest::WillPoll)))
}
}
impl<D: ResourceDialect> ClientInner<D> {
fn poll_recv_event(
self: &Arc<Self>,
cx: &Context<'_>,
) -> Poll<Result<D::MessageBufEtc, Error>> {
if let Some(msg_buf) = self.interests.lock().register_event_listener(cx) {
return Poll::Ready(Ok(msg_buf));
}
let maybe_terminal_error = self.recv_all(Some(Txid(0)));
let mut lock = self.interests.lock();
if let Some(msg_buf) = lock.events.pop_front() {
Poll::Ready(Ok(msg_buf))
} else {
maybe_terminal_error?;
Poll::Pending
}
}
fn poll_recv_msg_response(
self: &Arc<Self>,
txid: Txid,
cx: &Context<'_>,
) -> Poll<Result<D::MessageBufEtc, Error>> {
if let Some(buf) = self.interests.lock().register(txid, cx) {
return Poll::Ready(Ok(buf));
}
let maybe_terminal_error = self.recv_all(Some(txid));
let InterestId(raw_id) = InterestId::from_txid(txid);
let mut interests = self.interests.lock();
if interests.messages.get(raw_id).expect("Polled unregistered interest").is_received() {
let buf = interests.messages.remove(raw_id).unwrap_received();
Poll::Ready(Ok(buf))
} else {
maybe_terminal_error?;
Poll::Pending
}
}
fn recv_all(self: &Arc<Self>, want_txid: Option<Txid>) -> Result<(), Error> {
let mut terminal_error = self.terminal_error.lock();
if let Some(error) = terminal_error.as_ref() {
return Err(error.clone());
}
let recv_once = |waker| {
let cx = &mut Context::from_waker(&waker);
let mut buf = D::MessageBufEtc::new();
let result = self.channel.recv_etc_from(cx, &mut buf);
match result {
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(None)) => {
return Err(Error::ClientChannelClosed {
status: zx_status::Status::PEER_CLOSED,
protocol_name: self.protocol_name,
#[cfg(not(target_os = "fuchsia"))]
reason: self.channel.closed_reason(),
});
}
Poll::Ready(Err(Some(e))) => return Err(Error::ClientRead(e.into())),
Poll::Pending => return Ok(ControlFlow::Break(())),
};
let (bytes, _) = buf.split_mut();
let (header, body_bytes) = decode_transaction_header(bytes)?;
if header.is_epitaph() {
let handles = &mut [];
let mut epitaph_body = Decode::<EpitaphBody, D>::new_empty();
Decoder::<D>::decode_into::<EpitaphBody>(
&header,
body_bytes,
handles,
&mut epitaph_body,
)?;
return Err(Error::ClientChannelClosed {
status: epitaph_body.error,
protocol_name: self.protocol_name,
#[cfg(not(target_os = "fuchsia"))]
reason: self.channel.closed_reason(),
});
}
let txid = Txid(header.tx_id);
let waker = {
buf.shrink_bytes_to_fit();
let mut interests = self.interests.lock();
if txid == Txid(0) {
interests.push_event(buf)
} else {
interests.push_message(txid, buf)?
}
};
if want_txid != Some(txid) {
if let Some(waker) = waker {
waker.wake();
}
}
Ok(ControlFlow::Continue(()))
};
loop {
let waker = {
let interests = self.interests.lock();
if interests.waker_count == 0 {
return Ok(());
} else if interests.waker_count == 1 {
if let Some(waker) = interests.event_waker() {
waker.clone()
} else {
interests
.messages
.iter()
.find_map(|(_, interest)| {
if let MessageInterest::Waiting(waker) = interest {
Some(waker.clone())
} else {
None
}
})
.unwrap()
}
} else {
let weak = Arc::downgrade(self);
let waker = ClientWaker(Arc::new(move || {
if let Some(strong) = weak.upgrade() {
#[cfg(target_os = "fuchsia")]
if strong.recv_all(None).is_ok() {
return;
}
strong.wake_all();
}
}));
unsafe {
Waker::from_raw(RawWaker::new(
Arc::into_raw(Arc::new(waker)) as *const (),
&WAKER_VTABLE,
))
}
}
};
match recv_once(waker) {
Ok(ControlFlow::Continue(())) => {}
Ok(ControlFlow::Break(())) => return Ok(()),
Err(error) => {
self.wake_all();
return Err(terminal_error.insert(error).clone());
}
}
}
}
fn wake_all(&self) {
let mut lock = self.interests.lock();
for (_, interest) in &mut lock.messages {
if let MessageInterest::Waiting(_) = interest {
let MessageInterest::Waiting(waker) =
mem::replace(interest, MessageInterest::WillPoll)
else {
unreachable!()
};
waker.wake();
}
}
if let Some(waker) = lock.take_event_waker() {
waker.wake();
}
lock.waker_count = 0;
}
}
#[derive(Clone)]
struct ClientWaker(Arc<dyn Fn() + Send + Sync + 'static>);
static WAKER_VTABLE: RawWakerVTable =
RawWakerVTable::new(clone_waker, wake, wake_by_ref, drop_waker);
unsafe fn clone_waker(data: *const ()) -> RawWaker {
Arc::increment_strong_count(data as *const ClientWaker);
RawWaker::new(data, &WAKER_VTABLE)
}
unsafe fn wake(data: *const ()) {
Arc::from_raw(data as *const ClientWaker).0();
}
unsafe fn wake_by_ref(data: *const ()) {
mem::ManuallyDrop::new(Arc::from_raw(data as *const ClientWaker)).0();
}
unsafe fn drop_waker(data: *const ()) {
Arc::from_raw(data as *const ClientWaker);
}
#[cfg(target_os = "fuchsia")]
pub mod sync {
use super::*;
use std::mem::MaybeUninit;
use zx::{self as zx, AsHandleRef, MessageBufEtc};
#[derive(Debug)]
pub struct Client {
channel: zx::Channel,
protocol_name: &'static str,
}
impl Client {
pub fn new(channel: zx::Channel, protocol_name: &'static str) -> Self {
Client { channel, protocol_name }
}
pub fn as_channel(&self) -> &zx::Channel {
&self.channel
}
pub fn into_channel(self) -> zx::Channel {
self.channel
}
pub fn send<T: TypeMarker>(
&self,
body: impl Encode<T, DefaultFuchsiaResourceDialect>,
ordinal: u64,
dynamic_flags: DynamicFlags,
) -> Result<(), Error> {
let mut write_bytes = Vec::new();
let mut write_handles = Vec::new();
let msg = TransactionMessage {
header: TransactionHeader::new(0, ordinal, dynamic_flags),
body,
};
Encoder::encode::<TransactionMessageType<T>>(
&mut write_bytes,
&mut write_handles,
msg,
)?;
match self.channel.write_etc(&write_bytes, &mut write_handles) {
Ok(()) | Err(zx_status::Status::PEER_CLOSED) => Ok(()),
Err(e) => Err(Error::ClientWrite(e.into())),
}
}
pub fn send_query<Request: TypeMarker, Response: TypeMarker>(
&self,
body: impl Encode<Request, DefaultFuchsiaResourceDialect>,
ordinal: u64,
dynamic_flags: DynamicFlags,
deadline: zx::MonotonicInstant,
) -> Result<Response::Owned, Error>
where
Response::Owned: Decode<Response, DefaultFuchsiaResourceDialect>,
{
let mut write_bytes = Vec::new();
let mut write_handles = Vec::new();
let msg = TransactionMessage {
header: TransactionHeader::new(0, ordinal, dynamic_flags),
body,
};
Encoder::encode::<TransactionMessageType<Request>>(
&mut write_bytes,
&mut write_handles,
msg,
)?;
let bytes_out =
&mut [MaybeUninit::<u8>::uninit(); zx::sys::ZX_CHANNEL_MAX_MSG_BYTES as usize];
let handles_out = &mut [const { MaybeUninit::<zx::HandleInfo>::uninit() };
zx::sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize];
let (bytes_out, handles_out) = self
.channel
.call_etc_uninit(deadline, &write_bytes, &mut write_handles, bytes_out, handles_out)
.map_err(|e| self.wrap_error(Error::ClientCall, e))?;
let (header, body_bytes) = decode_transaction_header(bytes_out)?;
if header.ordinal != ordinal {
return Err(Error::InvalidResponseOrdinal);
}
let mut output = Decode::<Response, DefaultFuchsiaResourceDialect>::new_empty();
Decoder::<DefaultFuchsiaResourceDialect>::decode_into::<Response>(
&header,
body_bytes,
handles_out,
&mut output,
)?;
Ok(output)
}
pub fn wait_for_event(
&self,
deadline: zx::MonotonicInstant,
) -> Result<MessageBufEtc, Error> {
let mut buf = zx::MessageBufEtc::new();
buf.ensure_capacity_bytes(zx::sys::ZX_CHANNEL_MAX_MSG_BYTES as usize);
buf.ensure_capacity_handle_infos(zx::sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize);
loop {
self.channel
.wait_handle(
zx::Signals::CHANNEL_READABLE | zx::Signals::CHANNEL_PEER_CLOSED,
deadline,
)
.map_err(|e| self.wrap_error(Error::ClientEvent, e))?;
match self.channel.read_etc(&mut buf) {
Ok(()) => {
let (header, _) = decode_transaction_header(buf.bytes())
.map_err(|_| Error::InvalidHeader)?;
if header.tx_id != 0 {
return Err(Error::UnexpectedSyncResponse);
}
return Ok(buf);
}
Err(zx::Status::SHOULD_WAIT) => {
continue;
}
Err(e) => {
return Err(self.wrap_error(|x| Error::ClientRead(x.into()), e));
}
}
}
}
fn wrap_error<T: Fn(zx_status::Status) -> Error>(
&self,
variant: T,
err: zx_status::Status,
) -> Error {
if err == zx_status::Status::PEER_CLOSED {
Error::ClientChannelClosed {
status: zx_status::Status::PEER_CLOSED,
protocol_name: self.protocol_name,
}
} else {
variant(err)
}
}
}
}
#[cfg(all(test, target_os = "fuchsia"))]
mod tests {
use super::*;
use crate::encoding::MAGIC_NUMBER_INITIAL;
use crate::epitaph::{self, ChannelEpitaphExt};
use anyhow::{Context as _, Error};
use assert_matches::assert_matches;
use fuchsia_async as fasync;
use fuchsia_async::{Channel as AsyncChannel, DurationExt, TimeoutExt};
use futures::channel::oneshot;
use futures::stream::FuturesUnordered;
use futures::task::{noop_waker, waker, ArcWake};
use futures::{join, StreamExt, TryFutureExt};
use futures_test::task::new_count_waker;
use std::future::pending;
use std::thread;
use zx::{AsHandleRef, MessageBufEtc};
const SEND_ORDINAL_HIGH_BYTE: u8 = 42;
const SEND_ORDINAL: u64 = 42 << 32;
const SEND_DATA: u8 = 55;
const EVENT_ORDINAL: u64 = 854 << 23;
#[rustfmt::skip]
fn expected_sent_bytes(tx_id_low_byte: u8) -> [u8; 24] {
[
tx_id_low_byte, 0, 0, 0, 2, 0, 0, MAGIC_NUMBER_INITIAL,
0, 0, 0, 0, SEND_ORDINAL_HIGH_BYTE, 0, 0, 0, SEND_DATA, 0, 0, 0, 0, 0, 0, 0, ]
}
fn send_transaction(header: TransactionHeader, channel: &zx::Channel) {
let (bytes, handles) = (&mut vec![], &mut vec![]);
encode_transaction(header, bytes, handles);
channel.write_etc(bytes, handles).expect("Server channel write failed");
}
fn encode_transaction(
header: TransactionHeader,
bytes: &mut Vec<u8>,
handles: &mut Vec<zx::HandleDisposition<'static>>,
) {
let event = TransactionMessage { header, body: SEND_DATA };
Encoder::<DefaultFuchsiaResourceDialect>::encode::<TransactionMessageType<u8>>(
bytes, handles, event,
)
.expect("Encoding failure");
}
#[test]
fn sync_client() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()).context("sending")?;
let mut received = MessageBufEtc::new();
server_end.read_etc(&mut received).context("reading")?;
let one_way_tx_id = 0;
assert_eq!(received.bytes(), expected_sent_bytes(one_way_tx_id));
Ok(())
}
#[test]
fn sync_client_with_response() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
thread::spawn(move || {
let mut received = MessageBufEtc::new();
server_end
.wait_handle(
zx::Signals::CHANNEL_READABLE,
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
)
.expect("failed to wait for channel readable");
server_end.read_etc(&mut received).expect("failed to read on server end");
let (buf, _handles) = received.split_mut();
let (header, _body_bytes) = decode_transaction_header(buf).expect("server decode");
assert_eq!(header.ordinal, SEND_ORDINAL);
send_transaction(
TransactionHeader::new(header.tx_id, header.ordinal, DynamicFlags::empty()),
&server_end,
);
});
let response_data = client
.send_query::<u8, u8>(
SEND_DATA,
SEND_ORDINAL,
DynamicFlags::empty(),
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
)
.context("sending query")?;
assert_eq!(SEND_DATA, response_data);
Ok(())
}
#[test]
fn sync_client_with_event_and_response() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
thread::spawn(move || {
let mut received = MessageBufEtc::new();
server_end
.wait_handle(
zx::Signals::CHANNEL_READABLE,
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
)
.expect("failed to wait for channel readable");
server_end.read_etc(&mut received).expect("failed to read on server end");
let (buf, _handles) = received.split_mut();
let (header, _body_bytes) = decode_transaction_header(buf).expect("server decode");
assert_ne!(header.tx_id, 0);
assert_eq!(header.ordinal, SEND_ORDINAL);
send_transaction(
TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
&server_end,
);
send_transaction(
TransactionHeader::new(header.tx_id, header.ordinal, DynamicFlags::empty()),
&server_end,
);
});
let response_data = client
.send_query::<u8, u8>(
SEND_DATA,
SEND_ORDINAL,
DynamicFlags::empty(),
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
)
.context("sending query")?;
assert_eq!(SEND_DATA, response_data);
let event_buf = client
.wait_for_event(zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)))
.context("waiting for event")?;
let (bytes, _handles) = event_buf.split();
let (header, _body) = decode_transaction_header(&bytes).expect("event decode");
assert_eq!(header.ordinal, EVENT_ORDINAL);
Ok(())
}
#[test]
fn sync_client_with_racing_events() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client1 = Arc::new(sync::Client::new(client_end, "test_protocol"));
let client2 = client1.clone();
let thread1 = thread::spawn(move || {
let result = client1.wait_for_event(zx::MonotonicInstant::after(
zx::MonotonicDuration::from_seconds(5),
));
assert!(result.is_ok());
});
let thread2 = thread::spawn(move || {
let result = client2.wait_for_event(zx::MonotonicInstant::after(
zx::MonotonicDuration::from_seconds(5),
));
assert!(result.is_ok());
});
send_transaction(
TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
&server_end,
);
send_transaction(
TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
&server_end,
);
assert!(thread1.join().is_ok());
assert!(thread2.join().is_ok());
Ok(())
}
#[test]
fn sync_client_wait_for_event_gets_method_response() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
send_transaction(
TransactionHeader::new(3902304923, SEND_ORDINAL, DynamicFlags::empty()),
&server_end,
);
assert_matches!(
client.wait_for_event(zx::MonotonicInstant::after(
zx::MonotonicDuration::from_seconds(5)
)),
Err(crate::Error::UnexpectedSyncResponse)
);
Ok(())
}
#[test]
fn sync_client_one_way_call_suceeds_after_peer_closed() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
drop(server_end);
assert_matches!(client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()), Ok(()));
Ok(())
}
#[test]
fn sync_client_two_way_call_fails_after_peer_closed() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
drop(server_end);
assert_matches!(
client.send_query::<u8, u8>(
SEND_DATA,
SEND_ORDINAL,
DynamicFlags::empty(),
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5))
),
Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::PEER_CLOSED,
protocol_name: "test_protocol",
})
);
Ok(())
}
#[test]
fn sync_client_does_not_receive_epitaphs() -> Result<(), Error> {
let (client_end, server_end) = zx::Channel::create();
let client = sync::Client::new(client_end, "test_protocol");
server_end
.close_with_epitaph(zx_status::Status::UNAVAILABLE)
.expect("failed to write epitaph");
assert_matches!(
client.send_query::<u8, u8>(
SEND_DATA,
SEND_ORDINAL,
DynamicFlags::empty(),
zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5))
),
Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::PEER_CLOSED,
protocol_name: "test_protocol",
})
);
Ok(())
}
#[test]
fn sync_client_into_channel() -> Result<(), Error> {
let (client_end, _server_end) = zx::Channel::create();
let client_end_raw = client_end.raw_handle();
let client = sync::Client::new(client_end, "test_protocol");
assert_eq!(client.into_channel().raw_handle(), client_end_raw);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn client() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let receiver = async move {
let mut buffer = MessageBufEtc::new();
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
let one_way_tx_id = 0;
assert_eq!(buffer.bytes(), expected_sent_bytes(one_way_tx_id));
};
let receiver = receiver
.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive message in time!")
});
client
.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty())
.expect("failed to send msg");
receiver.await;
}
#[fasync::run_singlethreaded(test)]
async fn client_with_response() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let mut buffer = MessageBufEtc::new();
let receiver = async move {
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
let two_way_tx_id = 1u8;
assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header =
TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
};
let receiver = receiver
.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receiver message in time!")
});
let sender = client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.map_ok(|x| assert_eq!(x, SEND_DATA))
.unwrap_or_else(|e| panic!("fidl error: {:?}", e));
let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive response in time!")
});
let ((), ()) = join!(receiver, sender);
}
#[fasync::run_singlethreaded(test)]
async fn client_with_response_receives_epitaph() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let mut buffer = zx::MessageBufEtc::new();
let receiver = async move {
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
server
.close_with_epitaph(zx_status::Status::UNAVAILABLE)
.expect("failed to write epitaph");
};
let receiver = receiver
.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive message in time!")
});
let sender = async move {
const ORDINAL: u64 = 42 << 32;
let result = client.send_query::<u8, u8, ORDINAL>(55, DynamicFlags::empty()).await;
assert_matches!(
result,
Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::UNAVAILABLE,
protocol_name: "test_protocol"
})
);
};
let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive response in time!")
});
let ((), ()) = join!(receiver, sender);
}
#[fasync::run_singlethreaded(test)]
#[should_panic]
async fn event_cant_be_taken_twice() {
let (client_end, _) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let _foo = client.take_event_receiver();
client.take_event_receiver();
}
#[fasync::run_singlethreaded(test)]
async fn event_can_be_taken_after_drop() {
let (client_end, _) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let foo = client.take_event_receiver();
drop(foo);
client.take_event_receiver();
}
#[fasync::run_singlethreaded(test)]
async fn receiver_termination_test() {
let (client_end, _) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let mut foo = client.take_event_receiver();
assert!(!foo.is_terminated(), "receiver should not report terminated before being polled");
let _ = foo.next().await;
assert!(
foo.is_terminated(),
"receiver should report terminated after seeing channel is closed"
);
}
#[fasync::run_singlethreaded(test)]
#[should_panic(expected = "polled EventReceiver after `None`")]
async fn receiver_cant_be_polled_more_than_once_on_closed_stream() {
let (client_end, _) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let foo = client.take_event_receiver();
drop(foo);
let mut bar = client.take_event_receiver();
assert!(bar.next().await.is_none(), "read on closed channel should return none");
let _ = bar.next().await;
}
#[fasync::run_singlethreaded(test)]
#[should_panic(expected = "polled EventReceiver after `None`")]
async fn receiver_panics_when_polled_after_receiving_epitaph_then_none() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let server_end = AsyncChannel::from_channel(server_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let mut stream = client.take_event_receiver();
epitaph::write_epitaph_impl(&server_end, zx_status::Status::UNAVAILABLE)
.expect("wrote epitaph");
drop(server_end);
assert_matches!(
stream.next().await,
Some(Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::UNAVAILABLE,
protocol_name: "test_protocol"
}))
);
assert_matches!(stream.next().await, None);
let _ = stream.next().await;
}
#[fasync::run_singlethreaded(test)]
async fn event_can_be_taken() {
let (client_end, _) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
client.take_event_receiver();
}
#[fasync::run_singlethreaded(test)]
async fn event_received() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let (bytes, handles) = (&mut vec![], &mut vec![]);
const ORDINAL: u64 = 5;
let header = TransactionHeader::new(0, ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
drop(server);
let recv = client
.take_event_receiver()
.into_future()
.then(|(x, stream)| {
let x = x.expect("should contain one element");
let x = x.expect("fidl error");
let x: i32 =
decode_transaction_body::<i32, DefaultFuchsiaResourceDialect, ORDINAL>(x)
.expect("failed to decode event");
assert_eq!(x, 55);
stream.into_future()
})
.map(|(x, _stream)| assert!(x.is_none(), "should have emptied"));
let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive event in time!")
});
recv.await;
}
#[fasync::run_singlethreaded(test)]
async fn receiver_can_be_taken_after_end_of_stream() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let (bytes, handles) = (&mut vec![], &mut vec![]);
const ORDINAL: u64 = 5;
let header = TransactionHeader::new(0, ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
drop(server);
{
let recv = client
.take_event_receiver()
.into_future()
.then(|(x, stream)| {
let x = x.expect("should contain one element");
let x = x.expect("fidl error");
let x: i32 =
decode_transaction_body::<i32, DefaultFuchsiaResourceDialect, ORDINAL>(x)
.expect("failed to decode event");
assert_eq!(x, 55);
stream.into_future()
})
.map(|(x, _stream)| assert!(x.is_none(), "should have emptied"));
let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive event in time!")
});
recv.await;
}
let mut c = client.take_event_receiver();
assert!(
c.next().await.is_none(),
"receiver on closed channel should return none on first call"
);
}
#[fasync::run_singlethreaded(test)]
async fn event_incompatible_format() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header = TransactionHeader::new_full(
0,
5,
crate::encoding::Context {
wire_format_version: crate::encoding::WireFormatVersion::V2,
},
DynamicFlags::empty(),
0,
);
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
drop(server);
let mut event_receiver = client.take_event_receiver();
let recv = event_receiver.next().map(|event| {
assert_matches!(event, Some(Err(crate::Error::IncompatibleMagicNumber(0))))
});
let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive event in time!")
});
recv.await;
}
#[test]
fn client_always_wakes_pending_futures() {
let mut executor = fasync::TestExecutor::new();
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let mut event_receiver = client.take_event_receiver();
let (response_waker, response_waker_count) = new_count_waker();
let response_cx = &mut Context::from_waker(&response_waker);
let mut response_txid = Txid(0);
let mut response_future = client
.send_raw_query(|tx_id, bytes, handles| {
response_txid = tx_id;
let header = TransactionHeader::new(
response_txid.as_raw_id(),
SEND_ORDINAL,
DynamicFlags::empty(),
);
encode_transaction(header, bytes, handles);
Ok(())
})
.expect("Couldn't send query");
assert!(response_future.poll_unpin(response_cx).is_pending());
let (event_waker, event_waker_count) = new_count_waker();
let event_cx = &mut Context::from_waker(&event_waker);
assert!(event_receiver.poll_next_unpin(event_cx).is_pending());
assert_eq!(response_waker_count.get(), 0);
assert_eq!(event_waker_count.get(), 0);
send_transaction(TransactionHeader::new(0, 5, DynamicFlags::empty()), &server_end);
let _ = executor.run_until_stalled(&mut future::pending::<()>());
assert_eq!(response_waker_count.get(), 0);
assert_eq!(event_waker_count.get(), 1);
assert!(event_receiver.poll_next_unpin(event_cx).is_ready());
send_transaction(
TransactionHeader::new(response_txid.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty()),
&server_end,
);
let _ = executor.run_until_stalled(&mut future::pending::<()>());
assert_eq!(response_waker_count.get(), 1);
}
#[test]
fn client_always_wakes_pending_futures_on_epitaph() {
let mut executor = fasync::TestExecutor::new();
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let server_end = AsyncChannel::from_channel(server_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let mut event_receiver = client.take_event_receiver();
let (response1_waker, response1_waker_count) = new_count_waker();
let response1_cx = &mut Context::from_waker(&response1_waker);
let mut response1_future = client
.send_raw_query(|tx_id, bytes, handles| {
let header =
TransactionHeader::new(tx_id.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
Ok(())
})
.expect("Couldn't send query");
assert!(response1_future.poll_unpin(response1_cx).is_pending());
let (event_waker, event_waker_count) = new_count_waker();
let event_cx = &mut Context::from_waker(&event_waker);
assert!(event_receiver.poll_next_unpin(event_cx).is_pending());
let (response2_waker, response2_waker_count) = new_count_waker();
let response2_cx = &mut Context::from_waker(&response2_waker);
let mut response2_future = client
.send_raw_query(|tx_id, bytes, handles| {
let header =
TransactionHeader::new(tx_id.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
Ok(())
})
.expect("Couldn't send query");
assert!(response2_future.poll_unpin(response2_cx).is_pending());
let wakers = vec![response1_waker_count, response2_waker_count, event_waker_count];
let _ = executor.run_until_stalled(&mut future::pending::<()>());
assert_eq!(0, wakers.iter().fold(0, |acc, x| acc + x.get()));
epitaph::write_epitaph_impl(&server_end, zx_status::Status::UNAVAILABLE)
.expect("wrote epitaph");
let _ = executor.run_until_stalled(&mut future::pending::<()>());
for wake_count in &wakers {
assert_eq!(wake_count.get(), 1);
}
assert_matches!(
response1_future.poll_unpin(response1_cx),
Poll::Ready(Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::UNAVAILABLE,
protocol_name: "test_protocol"
}))
);
let _ = executor.run_until_stalled(&mut future::pending::<()>());
assert_matches!(
response2_future.poll_unpin(response2_cx),
Poll::Ready(Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::UNAVAILABLE,
protocol_name: "test_protocol"
}))
);
assert!(event_receiver.poll_next_unpin(event_cx).is_ready());
}
#[fasync::run_singlethreaded(test)]
async fn client_allows_take_event_stream_even_if_event_delivered() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
send_transaction(TransactionHeader::new(0, 5, DynamicFlags::empty()), &server_end);
let (response_waker, _response_waker_count) = new_count_waker();
let response_cx = &mut Context::from_waker(&response_waker);
let mut response_future =
client.send_query::<u8, u8, SEND_ORDINAL>(55, DynamicFlags::empty());
assert!(response_future.poll_unpin(response_cx).is_pending());
let mut _event_receiver = client.take_event_receiver();
}
#[fasync::run_singlethreaded(test)]
async fn client_reports_epitaph_from_all_read_actions() {
#[derive(Debug, PartialEq)]
enum Action {
SendMsg, SendQuery, WaitQuery, RecvEvent, }
impl Action {
fn should_report_epitaph(&self) -> bool {
match self {
Action::SendMsg | Action::SendQuery => false,
Action::WaitQuery | Action::RecvEvent => true,
}
}
}
use Action::*;
for two_actions in &[
[SendMsg, SendMsg],
[SendMsg, SendQuery],
[SendMsg, WaitQuery],
[SendMsg, RecvEvent],
[SendQuery, SendMsg],
[SendQuery, SendQuery],
[SendQuery, WaitQuery],
[SendQuery, RecvEvent],
[WaitQuery, SendMsg],
[WaitQuery, SendQuery],
[WaitQuery, WaitQuery],
[WaitQuery, RecvEvent],
[RecvEvent, SendMsg],
[RecvEvent, SendQuery],
[RecvEvent, WaitQuery],
] {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::new(client_end, "test_protocol");
let server_end = AsyncChannel::from_channel(server_end);
server_end
.close_with_epitaph(zx_status::Status::UNAVAILABLE)
.expect("failed to write epitaph");
let mut event_receiver = client.take_event_receiver();
for (index, action) in two_actions.iter().enumerate() {
let err = match action {
SendMsg => {
client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()).err()
}
WaitQuery => client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.await
.err(),
SendQuery => client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.check()
.err(),
RecvEvent => event_receiver.next().await.unwrap().err(),
};
let details = format!("index: {index:?}, two_actions: {two_actions:?}");
match err {
None => assert!(
!action.should_report_epitaph(),
"expected epitaph, but succeeded.\n{details}"
),
Some(crate::Error::ClientChannelClosed {
status: zx_status::Status::UNAVAILABLE,
protocol_name: "test_protocol",
}) => assert!(
action.should_report_epitaph(),
"got epitaph unexpectedly.\n{details}",
),
Some(err) => panic!("unexpected error: {err:#?}.\n{details}"),
}
}
if two_actions.contains(&RecvEvent) {
assert_matches!(event_receiver.next().await, None);
}
}
}
#[test]
fn client_query_result_check() {
let mut executor = fasync::TestExecutor::new();
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let active_fut =
client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());
let mut checked_fut = active_fut.check().expect("failed to check future");
let mut buffer = MessageBufEtc::new();
executor.run_singlethreaded(server.recv_etc_msg(&mut buffer)).expect("failed to recv msg");
let two_way_tx_id = 1u8;
assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header =
TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
executor
.run_singlethreaded(&mut checked_fut)
.map(|x| assert_eq!(x, SEND_DATA))
.unwrap_or_else(|e| panic!("fidl error: {:?}", e));
drop(server);
let query_fut = client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());
let mut checked_fut = query_fut.check().expect("failed to check future");
assert_matches!(
executor.run_singlethreaded(&mut checked_fut),
Err(crate::Error::ClientChannelClosed {
status: zx_status::Status::PEER_CLOSED,
protocol_name: "test_protocol"
})
);
}
#[fasync::run_singlethreaded(test)]
async fn client_into_channel() {
let (client_end, _server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
assert!(client.into_channel().is_ok());
}
#[fasync::run_singlethreaded(test)]
async fn client_into_channel_outstanding_messages() {
let (client_end, _server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
{
let _sender =
client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());
}
assert!(client.into_channel().is_err());
}
#[fasync::run_singlethreaded(test)]
async fn client_into_channel_active_clone() {
let (client_end, _server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let _cloned_client = client.clone();
assert!(client.into_channel().is_err());
}
#[fasync::run_singlethreaded(test)]
async fn client_into_channel_outstanding_messages_get_received() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let mut buffer = MessageBufEtc::new();
let receiver = async move {
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
let two_way_tx_id = 1u8;
assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header =
TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
};
let receiver = receiver
.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receiver message in time!")
});
let sender = client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.map_ok(|x| assert_eq!(x, SEND_DATA))
.unwrap_or_else(|e| panic!("fidl error: {:?}", e));
let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
panic!("did not receive response in time!")
});
let ((), ()) = join!(receiver, sender);
assert!(client.into_channel().is_ok());
}
#[fasync::run_singlethreaded(test)]
async fn client_decode_errors_are_broadcast() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let _server = fasync::Task::spawn(async move {
let mut buffer = MessageBufEtc::new();
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
let two_way_tx_id = 1u8;
assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header =
TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
bytes[4] = 0;
server.write_etc(bytes, handles).expect("Server channel write failed");
pending::<()>().await;
});
let futures = FuturesUnordered::new();
for _ in 0..4 {
futures.push(async {
assert_matches!(
client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.map_ok(|x| assert_eq!(x, SEND_DATA))
.await,
Err(crate::Error::UnsupportedWireFormatVersion)
);
});
}
futures
.collect::<Vec<_>>()
.on_timeout(zx::MonotonicDuration::from_seconds(1).after_now(), || panic!("timed out!"))
.await;
}
#[fasync::run_singlethreaded(test)]
async fn into_channel_from_waker_succeeds() {
let (client_end, server_end) = zx::Channel::create();
let client_end = AsyncChannel::from_channel(client_end);
let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
let server = AsyncChannel::from_channel(server_end);
let mut buffer = MessageBufEtc::new();
let receiver = async move {
server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
let two_way_tx_id = 1u8;
assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));
let (bytes, handles) = (&mut vec![], &mut vec![]);
let header =
TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
encode_transaction(header, bytes, handles);
server.write_etc(bytes, handles).expect("Server channel write failed");
};
struct Sender {
future: Mutex<Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>>,
}
let (done_tx, done_rx) = oneshot::channel();
let sender = Arc::new(Sender {
future: Mutex::new(Box::pin(async move {
client
.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
.map_ok(|x| assert_eq!(x, SEND_DATA))
.unwrap_or_else(|e| panic!("fidl error: {:?}", e))
.await;
assert!(client.into_channel().is_ok());
let _ = done_tx.send(());
})),
});
impl ArcWake for Sender {
fn wake_by_ref(arc_self: &Arc<Self>) {
assert!(arc_self
.future
.lock()
.poll_unpin(&mut Context::from_waker(&noop_waker()))
.is_ready());
}
}
let waker = waker(sender.clone());
assert!(sender.future.lock().poll_unpin(&mut Context::from_waker(&waker)).is_pending());
receiver.await;
done_rx.await.unwrap();
}
}