1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-31 22:00:07 +01:00

77 lines
2.0 KiB
Rust
Raw Normal View History

2019-11-29 10:41:09 +06:00
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_service::{IntoService, Service};
2019-12-11 12:42:07 +06:00
use futures::{FutureExt, Stream};
2019-11-29 10:41:09 +06:00
use crate::mpsc;
#[pin_project::pin_project]
2019-12-11 12:42:07 +06:00
pub struct Dispatcher<S, T>
2019-11-29 10:41:09 +06:00
where
S: Stream,
T: Service<Request = S::Item, Response = ()> + 'static,
{
#[pin]
stream: S,
service: T,
err_rx: mpsc::Receiver<T::Error>,
err_tx: mpsc::Sender<T::Error>,
}
2019-12-11 12:42:07 +06:00
impl<S, T> Dispatcher<S, T>
2019-11-29 10:41:09 +06:00
where
S: Stream,
2019-11-29 13:51:00 +06:00
T: Service<Request = S::Item, Response = ()> + 'static,
2019-11-29 10:41:09 +06:00
{
pub fn new<F>(stream: S, service: F) -> Self
where
F: IntoService<T>,
{
let (err_tx, err_rx) = mpsc::channel();
2019-12-11 12:42:07 +06:00
Dispatcher {
2019-11-29 10:41:09 +06:00
err_rx,
err_tx,
stream,
service: service.into_service(),
}
}
}
2019-12-11 12:42:07 +06:00
impl<S, T> Future for Dispatcher<S, T>
2019-11-29 10:41:09 +06:00
where
S: Stream,
T: Service<Request = S::Item, Response = ()> + 'static,
{
type Output = Result<(), T::Error>;
2019-12-02 22:30:09 +06:00
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2019-11-29 10:41:09 +06:00
let mut this = self.as_mut().project();
if let Poll::Ready(Some(e)) = Pin::new(&mut this.err_rx).poll_next(cx) {
return Poll::Ready(Err(e));
}
loop {
2019-12-11 12:42:07 +06:00
return match this.service.poll_ready(cx)? {
2019-11-29 10:41:09 +06:00
Poll::Ready(_) => match this.stream.poll_next(cx) {
Poll::Ready(Some(item)) => {
2019-12-11 12:42:07 +06:00
let stop = this.err_tx.clone();
actix_rt::spawn(this.service.call(item).map(move |res| {
if let Err(e) = res {
let _ = stop.send(e);
}
}));
2019-11-29 10:41:09 +06:00
this = self.as_mut().project();
2019-12-11 12:42:07 +06:00
continue;
2019-11-29 10:41:09 +06:00
}
2019-12-11 12:42:07 +06:00
Poll::Pending => Poll::Pending,
Poll::Ready(None) => Poll::Ready(Ok(())),
2019-11-29 10:41:09 +06:00
},
2019-12-11 12:42:07 +06:00
Poll::Pending => Poll::Pending,
};
2019-11-29 10:41:09 +06:00
}
}
}