tokio_util.rs 5.1 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;
3
use deno::ErrBox;
R
Ryan Dahl 已提交
4 5
use futures;
use futures::Future;
6 7 8 9
use futures::Poll;
use std::io;
use std::mem;
use std::net::SocketAddr;
10
use std::ops::FnOnce;
R
Ryan Dahl 已提交
11
use tokio;
12
use tokio::net::TcpStream;
13 14
use tokio::runtime;

15 16
pub fn create_threadpool_runtime(
) -> Result<tokio::runtime::Runtime, tokio::io::Error> {
17
  runtime::Builder::new()
18
    .panic_handler(|err| std::panic::resume_unwind(err))
19 20
    .build()
}
21 22 23 24 25 26

pub fn run<F>(future: F)
where
  F: Future<Item = (), Error = ()> + Send + 'static,
{
  // tokio::runtime::current_thread::run(future)
27
  let rt = create_threadpool_runtime().expect("Unable to create Tokio runtime");
28
  rt.block_on_all(future).unwrap();
29 30
}

31 32 33 34 35 36 37
pub fn run_on_current_thread<F>(future: F)
where
  F: Future<Item = (), Error = ()> + Send + 'static,
{
  tokio::runtime::current_thread::run(future);
}

38 39
/// THIS IS A HACK AND SHOULD BE AVOIDED.
///
40 41 42 43
/// This spawns a new thread and creates a single-threaded tokio runtime on that thread,
/// to execute the given future.
///
/// This is useful when we want to block the main runtime to
G
Gurwinder S 已提交
44
/// resolve a future without worrying that we'll use up all the threads in the
45
/// main runtime.
46
pub fn block_on<F, R>(future: F) -> Result<R, ErrBox>
R
Ryan Dahl 已提交
47
where
48
  F: Send + 'static + Future<Item = R, Error = ErrBox>,
R
Ryan Dahl 已提交
49 50
  R: Send + 'static,
{
51 52 53 54 55
  use std::sync::mpsc::channel;
  use std::thread;
  let (sender, receiver) = channel();
  // Create a new runtime to evaluate the future asynchronously.
  thread::spawn(move || {
56
    let r = tokio::runtime::current_thread::block_on_all(future);
57 58 59
    sender
      .send(r)
      .expect("Unable to send blocking future result")
60
  });
61 62 63
  receiver
    .recv()
    .expect("Unable to receive blocking future result")
R
Ryan Dahl 已提交
64 65 66 67 68
}

// 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.
69
#[cfg(test)]
R
Ryan Dahl 已提交
70 71 72 73
pub fn init<F>(f: F)
where
  F: FnOnce(),
{
74
  let rt = create_threadpool_runtime().expect("Unable to create Tokio runtime");
R
Ryan Dahl 已提交
75 76
  let mut executor = rt.executor();
  let mut enter = tokio_executor::enter().expect("Multiple executors at once");
77
  tokio_executor::with_default(&mut executor, &mut enter, move |_enter| f());
R
Ryan Dahl 已提交
78
}
79 80 81

#[derive(Debug)]
enum AcceptState {
82
  Eager(Resource),
83 84 85 86 87 88 89
  Pending(Resource),
  Empty,
}

/// Simply accepts a connection.
pub fn accept(r: Resource) -> Accept {
  Accept {
90
    state: AcceptState::Eager(r),
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  }
}

/// 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 {
R
Ryan Dahl 已提交
108 109 110 111
      // 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).
112 113 114 115 116 117 118 119 120 121
      AcceptState::Eager(ref mut r) => match r.poll_accept() {
        Ok(futures::prelude::Async::Ready(t)) => t,
        Ok(futures::prelude::Async::NotReady) => {
          self.state = AcceptState::Pending(r.to_owned());
          return Ok(futures::prelude::Async::NotReady);
        }
        Err(e) => {
          return Err(e);
        }
      },
R
Ryan Dahl 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      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(e);
        }
      },
137 138 139 140 141
      AcceptState::Empty => panic!("poll Accept after it's done"),
    };

    match mem::replace(&mut self.state, AcceptState::Empty) {
      AcceptState::Empty => panic!("invalid internal state"),
142
      _ => Ok((stream, addr).into()),
143 144 145
    }
  }
}
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

/// `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 已提交
173 174 175 176 177 178 179 180

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))
}
181 182 183 184 185 186 187 188 189 190 191 192 193

#[cfg(test)]
pub fn run_in_task<F>(f: F)
where
  F: FnOnce() + Send + 'static,
{
  let fut = futures::future::lazy(move || {
    f();
    futures::future::ok(())
  });

  run(fut)
}