tokio_util.rs 4.0 KB
Newer Older
R
Ryan Dahl 已提交
1
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
A
Andy Hayden 已提交
2
use crate::resources::Resource;
R
Ryan Dahl 已提交
3 4
use futures;
use futures::Future;
5 6 7 8
use futures::Poll;
use std::io;
use std::mem;
use std::net::SocketAddr;
R
Ryan Dahl 已提交
9
use tokio;
10
use tokio::net::TcpStream;
11 12 13 14 15 16 17 18 19 20 21 22 23 24
use tokio::runtime;

pub fn create_threadpool_runtime() -> tokio::runtime::Runtime {
  // This code can be simplified once the following PR is landed and
  // released: https://github.com/tokio-rs/tokio/pull/1055
  use tokio_threadpool::Builder as ThreadPoolBuilder;
  let mut threadpool_builder = ThreadPoolBuilder::new();
  threadpool_builder.panic_handler(|err| std::panic::resume_unwind(err));
  #[allow(deprecated)]
  runtime::Builder::new()
    .threadpool_builder(threadpool_builder)
    .build()
    .unwrap()
}
25 26 27 28 29 30

pub fn run<F>(future: F)
where
  F: Future<Item = (), Error = ()> + Send + 'static,
{
  // tokio::runtime::current_thread::run(future)
31 32
  let rt = create_threadpool_runtime();
  rt.block_on_all(future).unwrap();
33 34
}

R
Ryan Dahl 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48
pub fn block_on<F, R, E>(future: F) -> Result<R, E>
where
  F: Send + 'static + Future<Item = R, Error = E>,
  R: Send + 'static,
  E: Send + 'static,
{
  let (tx, rx) = futures::sync::oneshot::channel();
  tokio::spawn(future.then(move |r| tx.send(r).map_err(|_| unreachable!())));
  rx.wait().unwrap()
}

// Set the default executor so we can use tokio::spawn(). It's difficult to
// pass around mut references to the runtime, so using with_default is
// preferable. Ideally Tokio would provide this function.
49
#[cfg(test)]
R
Ryan Dahl 已提交
50 51 52 53
pub fn init<F>(f: F)
where
  F: FnOnce(),
{
54
  let rt = create_threadpool_runtime();
R
Ryan Dahl 已提交
55 56
  let mut executor = rt.executor();
  let mut enter = tokio_executor::enter().expect("Multiple executors at once");
57
  tokio_executor::with_default(&mut executor, &mut enter, move |_enter| f());
R
Ryan Dahl 已提交
58
}
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

#[derive(Debug)]
enum AcceptState {
  Pending(Resource),
  Empty,
}

/// Simply accepts a connection.
pub fn accept(r: Resource) -> Accept {
  Accept {
    state: AcceptState::Pending(r),
  }
}

/// A future which can be used to easily read available number of bytes to fill
/// a buffer.
///
/// Created by the [`read`] function.
#[derive(Debug)]
pub struct Accept {
  state: AcceptState,
}
impl Future for Accept {
  type Item = (TcpStream, SocketAddr);
  type Error = io::Error;

  fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
    let (stream, addr) = match self.state {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
      // Similar to try_ready!, but also track/untrack accept task
      // in TcpListener resource.
      // In this way, when the listener is closed, the task can be
      // notified to error out (instead of stuck forever).
      AcceptState::Pending(ref mut r) => match r.poll_accept() {
        Ok(futures::prelude::Async::Ready(t)) => {
          r.untrack_task();
          t
        }
        Ok(futures::prelude::Async::NotReady) => {
          // Would error out if another accept task is being tracked.
          r.track_task()?;
          return Ok(futures::prelude::Async::NotReady);
        }
        Err(e) => {
          r.untrack_task();
          return Err(From::from(e));
        }
      },
106 107 108 109 110 111 112 113 114
      AcceptState::Empty => panic!("poll Accept after it's done"),
    };

    match mem::replace(&mut self.state, AcceptState::Empty) {
      AcceptState::Pending(_) => Ok((stream, addr).into()),
      AcceptState::Empty => panic!("invalid internal state"),
    }
  }
}
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

/// `futures::future::poll_fn` only support `F: FnMut()->Poll<T, E>`
/// However, we require that `F: FnOnce()->Poll<T, E>`.
/// Therefore, we created our version of `poll_fn`.
pub fn poll_fn<T, E, F>(f: F) -> PollFn<F>
where
  F: FnOnce() -> Poll<T, E>,
{
  PollFn { inner: Some(f) }
}

pub struct PollFn<F> {
  inner: Option<F>,
}

impl<T, E, F> Future for PollFn<F>
where
  F: FnOnce() -> Poll<T, E>,
{
  type Item = T;
  type Error = E;

  fn poll(&mut self) -> Poll<T, E> {
    let f = self.inner.take().expect("Inner fn has been taken.");
    f()
  }
}
R
Ryan Dahl 已提交
142 143 144 145 146 147 148 149

pub fn panic_on_error<I, E, F>(f: F) -> impl Future<Item = I, Error = ()>
where
  F: Future<Item = I, Error = E>,
  E: std::fmt::Debug,
{
  f.map_err(|err| panic!("Future got unexpected error: {:?}", err))
}