Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setwaker approach to passthrough correctness #15

Merged
merged 4 commits into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ weak-table = "0.2.3"
url = "2.1.0"
thiserror = "1.0.9"
anyhow = "1.0.26"
setwaker = { git = "https://github.com/noocene/setwaker" }
parking_lot = "0.10.0"

[target.wasm32-unknown-unknown.dependencies]
wasm-bindgen = { version = "0.2.54", optional = true }
Expand Down
190 changes: 119 additions & 71 deletions src/channel/id_channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ use core::{
fmt::{self, Display, Formatter},
marker::PhantomData,
pin::Pin,
task::Waker,
};
use futures::{
channel::mpsc::{unbounded, SendError, UnboundedReceiver, UnboundedSender},
future::ok,
task::{Context as FContext, Poll},
Future as IFuture, FutureExt, Sink as ISink, SinkExt, Stream, StreamExt, TryFutureExt,
};
use parking_lot::RawMutex;
use serde::{de::DeserializeOwned, Serialize};
use setwaker::SetWaker;
use std::{collections::HashMap, sync::Mutex};
use thiserror::Error;

Expand All @@ -31,20 +34,48 @@ use crate::{

use super::{ChannelError, Shim as IShim};

#[derive(Clone)]
struct SinkStages<T> {
ready: T,
flush: T,
close: T,
}

impl<T> SinkStages<T> {
fn new(cons: impl Fn() -> T) -> Self {
SinkStages {
ready: cons(),
flush: cons(),
close: cons(),
}
}
fn apply<U>(&self, f: impl Fn(&T) -> U) -> SinkStages<U> {
SinkStages {
ready: f(&self.ready),
flush: f(&self.flush),
close: f(&self.close),
}
}
}

pub struct IdChannel {
out_channel: (
Pin<Box<UnboundedReceiver<Item>>>,
Pin<Box<UnboundedSender<Item>>>,
),
set_waker: SinkStages<SetWaker<RawMutex, ForkHandle>>,
context: Context,
in_channels: Arc<Mutex<HashMap<ForkHandle, Sink<Box<dyn SerdeAny>, ChannelError>>>>,
in_channels:
Arc<Mutex<HashMap<ForkHandle, (Sink<Box<dyn SerdeAny>, ChannelError>, SinkStages<Waker>)>>>,
}

#[derive(Clone)]
struct IdChannelHandle {
out_channel: Pin<Box<UnboundedSender<Item>>>,
context: Context,
in_channels: Arc<Mutex<HashMap<ForkHandle, Sink<Box<dyn SerdeAny>, ChannelError>>>>,
set_waker: SinkStages<SetWaker<RawMutex, ForkHandle>>,
in_channels:
Arc<Mutex<HashMap<ForkHandle, (Sink<Box<dyn SerdeAny>, ChannelError>, SinkStages<Waker>)>>>,
}

impl IdChannelHandle {
Expand Down Expand Up @@ -105,67 +136,69 @@ impl ISink<Item> for IdChannel {
match self.in_channels.lock().unwrap().get_mut(&item.0) {
Some(channel) => {
let (id, data) = (item.0, item.1);
channel
let r = channel
.0
.as_mut()
.start_send(data)
.map_err(move |e| IdChannelError::Channel(SinkStage::Send, id, e))
.map_err(|e| IdChannelError::Channel(SinkStage::Send, id.clone(), e));
if r.is_ok() {
self.set_waker.flush.wake(&id);
}
r
}
None => Err(IdChannelError::InvalidId(item.0)),
}
}
fn poll_ready(self: Pin<&mut Self>, cx: &mut FContext) -> Poll<Result<(), Self::Error>> {
if let Some(result) = self
.in_channels
.lock()
.unwrap()
.iter_mut()
.map(|(k, item)| (k, item.as_mut().poll_ready(cx)))
.find(|(_, poll)| match poll {
Poll::Ready(Ok(())) => false,
_ => true,
})
{
let (id, result) = result;
result.map_err(move |e| IdChannelError::Channel(SinkStage::Ready, *id, e))
} else {
Poll::Ready(Ok(()))
self.set_waker.ready.register(cx.waker());
let mut in_channels = self.in_channels.lock().unwrap();
for key in self.set_waker.ready.keys() {
if let Some(channel) = in_channels.get_mut(&key) {
if let Poll::Pending = channel
.0
.as_mut()
.poll_ready(&mut FContext::from_waker(&channel.1.ready))
.map_err(move |e| IdChannelError::Channel(SinkStage::Ready, key, e))?
{
return Poll::Pending;
}
}
}
Poll::Ready(Ok(()))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut FContext) -> Poll<Result<(), Self::Error>> {
if let Some(result) = self
.in_channels
.lock()
.unwrap()
.iter_mut()
.map(|(k, item)| (k, item.as_mut().poll_ready(cx)))
.find(|(_, poll)| match poll {
Poll::Ready(Ok(())) => false,
_ => true,
})
{
let (id, result) = result;
result.map_err(move |e| IdChannelError::Channel(SinkStage::Flush, *id, e))
} else {
Poll::Ready(Ok(()))
self.set_waker.flush.register(cx.waker());
let mut in_channels = self.in_channels.lock().unwrap();
for key in self.set_waker.flush.keys() {
if let Some(channel) = in_channels.get_mut(&key) {
if let Poll::Pending = channel
.0
.as_mut()
.poll_ready(&mut FContext::from_waker(&channel.1.flush))
.map_err(move |e| IdChannelError::Channel(SinkStage::Flush, key, e))?
{
return Poll::Pending;
}
}
}
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, cx: &mut FContext) -> Poll<Result<(), Self::Error>> {
if let Some(result) = self
.in_channels
.lock()
.unwrap()
.iter_mut()
.map(|(k, item)| (k, item.as_mut().poll_ready(cx)))
.find(|(_, poll)| match poll {
Poll::Ready(Ok(())) => false,
_ => true,
})
{
let (id, result) = result;
result.map_err(move |e| IdChannelError::Channel(SinkStage::Close, *id, e))
} else {
Poll::Ready(Ok(()))
self.set_waker.close.register(cx.waker());
let mut in_channels = self.in_channels.lock().unwrap();
for key in self.set_waker.close.keys() {
if let Some(channel) = in_channels.get_mut(&key) {
if let Poll::Pending = channel
.0
.as_mut()
.poll_ready(&mut FContext::from_waker(&channel.1.close))
.map_err(move |e| IdChannelError::Channel(SinkStage::Close, key, e))?
{
return Poll::Pending;
}
}
}
Poll::Ready(Ok(()))
}
}

Expand Down Expand Up @@ -208,6 +241,7 @@ impl<'a, K: Kind> IShim<'a, IdChannel, K> for Shim<K> {
let channel = IdChannel {
out_channel: (Box::pin(receiver), Box::pin(sender)),
context: self.context,
set_waker: SinkStages::new(|| SetWaker::new()),
in_channels: Arc::new(Mutex::new(HashMap::new())),
};
let fork = channel.get_fork::<K>(ForkHandle(0));
Expand Down Expand Up @@ -236,6 +270,7 @@ impl IdChannelHandle {
fn fork<K: Kind>(&self, kind: K) -> Fallible<ForkHandle, K::DeconstructError> {
REGISTRY.add_deconstruct::<K>();
let id = self.context.create::<K>();
let waker = self.set_waker.apply(|waker| waker.with_key(id.clone()));
let context = self.context.clone();
let out_channel = self.out_channel.clone();
let in_channels = self.in_channels.clone();
Expand All @@ -251,15 +286,18 @@ impl IdChannelHandle {
let mut in_channels = in_channels.lock().unwrap();
in_channels.insert(
id,
Box::pin(
sender
.with(|item: Box<dyn SerdeAny>| {
ok(*(item
.downcast::<K::DeconstructItem>()
.map_err(|e| panic!(e))
.unwrap()))
})
.sink_map_err(|e: SendError| ChannelError(e.into())),
(
Box::pin(
sender
.with(|item: Box<dyn SerdeAny>| {
ok(*(item
.downcast::<K::DeconstructItem>()
.map_err(|e| panic!(e))
.unwrap()))
})
.sink_map_err(|e: SendError| ChannelError(e.into())),
),
waker,
),
);
Ok(id)
Expand All @@ -280,8 +318,12 @@ impl IdChannelHandle {
}))
});
self.in_channels.lock().unwrap().insert(
fork_ref,
Box::pin(isender.sink_map_err(|e: SendError| ChannelError(e.into()))),
fork_ref.clone(),
(
Box::pin(isender.sink_map_err(|e: SendError| ChannelError(e.into()))),
self.set_waker
.apply(|waker| waker.with_key(fork_ref.clone())),
),
);
let ct = self.context.clone();
spawn(
Expand All @@ -308,6 +350,7 @@ impl IdChannel {
out_channel: self.out_channel.1.clone(),
context: self.context.clone(),
in_channels: self.in_channels.clone(),
set_waker: self.set_waker.clone(),
}
}
fn get_fork<K: Kind>(&self, fork_ref: ForkHandle) -> Fallible<K, K::ConstructError> {
Expand Down Expand Up @@ -425,24 +468,29 @@ impl<
REGISTRY.add_deconstruct::<K>();
let context = Context::new();
let handle = context.create::<K>();
let set_waker = SinkStages::new(|| SetWaker::new());
in_channels.insert(
handle,
Box::pin(
sender
.with(|item: Box<dyn SerdeAny>| {
ok(*(item
.downcast::<K::DeconstructItem>()
.map_err(|_| panic!())
.unwrap()))
})
.sink_map_err(|e: SendError| ChannelError(e.into())),
) as Sink<Box<dyn SerdeAny>, ChannelError>,
handle.clone(),
(
Box::pin(
sender
.with(|item: Box<dyn SerdeAny>| {
ok(*(item
.downcast::<K::DeconstructItem>()
.map_err(|_| panic!())
.unwrap()))
})
.sink_map_err(|e: SendError| ChannelError(e.into())),
) as Sink<Box<dyn SerdeAny>, ChannelError>,
set_waker.apply(|waker| waker.with_key(handle.clone())),
),
);
let ct = context.clone();
let (csender, creceiver) = unbounded();
let channel = IdChannel {
out_channel: (Box::pin(creceiver), Box::pin(csender.clone())),
context,
set_waker,
in_channels: Arc::new(Mutex::new(in_channels)),
};
spawn(
Expand Down
2 changes: 1 addition & 1 deletion src/core/hal/network/native/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl RawClient for Client {
});
move |message| {
if let Message::Binary(data) = message {
data_sender.clone().start_send(data).unwrap();
data_sender.unbounded_send(data).unwrap();
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/hal/network/native/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl RawServer for Server {
});
move |message| {
if let Message::Binary(data) = message {
sender.clone().start_send(data).unwrap();
sender.unbounded_send(data).unwrap();
}
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/hal/network/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl RawClient for Client {
let (mut data_sender, data_receiver) = unbounded();
let on_data = Closure::wrap(Box::new(move |e: MessageEvent| {
data_sender
.start_send(Uint8Array::new(&e.data()).to_vec())
.unbounded_send(Uint8Array::new(&e.data()).to_vec())
.unwrap();
}) as Box<dyn FnMut(_)>);
socket.set_onmessage(Some(on_data.as_ref().unchecked_ref()));
Expand Down