diff options
author | Carl Lerche <me@carllerche.com> | 2019-08-15 11:04:58 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-15 11:04:58 -0700 |
commit | 8538c25170240fa46313ffe9d4a9a2f9ba2536e5 (patch) | |
tree | 24b7d8e14a4741cd9faf116edf95d770bb937990 /tokio | |
parent | 7b6438a17247e026c996712a7c83d0c43442d73e (diff) |
reactor: rename tokio-reactor -> tokio-net (#1450)
* reactor: rename tokio-reactor -> tokio-net
This is in preparation for #1264
Diffstat (limited to 'tokio')
-rw-r--r-- | tokio/Cargo.toml | 14 | ||||
-rw-r--r-- | tokio/examples_old/README.md | 62 | ||||
-rw-r--r-- | tokio/examples_old/blocking.rs | 90 | ||||
-rw-r--r-- | tokio/examples_old/manual-runtime.rs | 85 | ||||
-rw-r--r-- | tokio/examples_old/udp-codec.rs | 61 | ||||
-rw-r--r-- | tokio/src/lib.rs | 2 | ||||
-rw-r--r-- | tokio/src/reactor.rs | 2 | ||||
-rw-r--r-- | tokio/src/runtime/current_thread/builder.rs | 2 | ||||
-rw-r--r-- | tokio/src/runtime/current_thread/runtime.rs | 8 | ||||
-rw-r--r-- | tokio/src/runtime/threadpool/background.rs | 6 | ||||
-rw-r--r-- | tokio/src/runtime/threadpool/builder.rs | 3 | ||||
-rw-r--r-- | tokio/src/runtime/threadpool/mod.rs | 2 | ||||
-rw-r--r-- | tokio/tests/reactor.rs | 4 |
13 files changed, 20 insertions, 321 deletions
diff --git a/tokio/Cargo.toml b/tokio/Cargo.toml index 27b7f7ad..efed28ed 100644 --- a/tokio/Cargo.toml +++ b/tokio/Cargo.toml @@ -29,7 +29,6 @@ default = [ "fs", "io", "net", - "reactor", "rt-full", "sync", "timer", @@ -38,11 +37,10 @@ default = [ codec = ["io", "tokio-codec", "bytes"] fs = ["tokio-fs"] io = ["tokio-io"] -reactor = ["io", "tokio-reactor"] -net = ["reactor", "tcp", "udp", "uds"] +net = ["tcp", "udp", "uds"] rt-full = [ "num_cpus", - "reactor", + "net", "sync", "timer", "tokio-executor/current-thread", @@ -51,10 +49,10 @@ rt-full = [ "tracing-core", ] sync = ["tokio-sync"] -tcp = ["tokio-tcp"] +tcp = ["io", "tokio-net", "tokio-tcp"] timer = ["tokio-timer"] -udp = ["tokio-udp"] -uds = ["tokio-uds"] +udp = ["io", "tokio-net", "tokio-udp"] +uds = ["io", "tokio-net", "tokio-uds"] [dependencies] futures-core-preview = "=0.3.0-alpha.18" @@ -69,7 +67,7 @@ tokio-fs = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-fs" } tokio-io = { version = "=0.2.0-alpha.1", optional = true, features = ["util"], path = "../tokio-io" } tokio-executor = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-executor" } tokio-macros = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-macros" } -tokio-reactor = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-reactor" } +tokio-net = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-net" } tokio-sync = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-sync", features = ["async-traits"] } tokio-threadpool = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-threadpool" } tokio-tcp = { version = "=0.2.0-alpha.1", optional = true, path = "../tokio-tcp", features = ["async-traits"] } diff --git a/tokio/examples_old/README.md b/tokio/examples_old/README.md deleted file mode 100644 index ac9e9b42..00000000 --- a/tokio/examples_old/README.md +++ /dev/null @@ -1,62 +0,0 @@ -## Examples of how to use Tokio - -This directory contains a number of examples showcasing various capabilities of -the `tokio` crate. - -All examples can be executed with: - -``` -cargo run --example $name -``` - -A high level description of each example is: - -* [`hello_world`](hello_world.rs) - a tiny server that writes "hello world" to - all connected clients and then terminates the connection, should help see how - to create and initialize `tokio`. - -* [`echo`](echo.rs) - this is your standard TCP "echo server" which accepts - connections and then echos back any contents that are read from each connected - client. - -* [`print_each_packet`](print_each_packet.rs) - this server will create a TCP - listener, accept connections in a loop, and put down in the stdout everything - that's read off of each TCP connection. - -* [`echo-udp`](echo-udp.rs) - again your standard "echo server", except for UDP - instead of TCP. This will echo back any packets received to the original - sender. - -* [`connect`](connect.rs) - this is a `nc`-like clone which can be used to - interact with most other examples. The program creates a TCP connection or UDP - socket and sends all information read on stdin to the remote peer, displaying - any data received on stdout. Often quite useful when interacting with the - various other servers here! - -* [`chat`](chat.rs) - this spins up a local TCP server which will broadcast from - any connected client to all other connected clients. You can connect to this - in multiple terminals and use it to chat between the terminals. - -* [`chat-combinator`](chat-combinator.rs) - Similar to `chat`, but this uses a - much more functional programming approach using combinators. - -* [`proxy`](proxy.rs) - an example proxy server that will forward all connected - TCP clients to the remote address specified when starting the program. - -* [`tinyhttp`](tinyhttp.rs) - a tiny HTTP/1.1 server which doesn't support HTTP - request bodies showcasing running on multiple cores, working with futures and - spawning tasks, and finally framing a TCP connection to discrete - request/response objects. - -* [`tinydb`](tinydb.rs) - an in-memory database which shows sharing state - between all connected clients, notably the key/value store of this database. - -* [`udp-client`](udp-client.rs) - a simple `send_dgram`/`recv_dgram` example. - -* [`manual-runtime`](manual-runtime.rs) - manually composing a runtime. - -* [`blocking`](blocking.rs) - perform heavy computation in blocking environment. - -If you've got an example you'd like to see here, please feel free to open an -issue. Otherwise if you've got an example you'd like to add, please feel free -to make a PR! diff --git a/tokio/examples_old/blocking.rs b/tokio/examples_old/blocking.rs deleted file mode 100644 index e8f042f4..00000000 --- a/tokio/examples_old/blocking.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! An example of using blocking funcion annotation. -//! -//! This example will create 8 "heavy computation" blocking futures and 8 -//! non-blocking futures with 4 threads core threads in runtime. -//! Each non-blocking future will print it's id and return immideatly. -//! Each blocking future will print it's id on start, sleep for 1000 ms, print -//! it's id and return. -//! -//! Note how non-blocking threads are executed before blocking threads finish -//! their task. - -#![feature(async_await)] -#![warn(rust_2018_idioms)] - -use std::pin::Pin; -use std::thread; -use std::time::Duration; -use tokio; -use tokio::prelude::*; -use tokio::runtime::Builder; -use tokio_threadpool::blocking; - -/// This future blocks it's poll method for 1000 ms. -struct BlockingFuture { - value: i32, -} - -impl Future for BlockingFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, _ctx: &mut task::Context<'_>) -> Poll<Self::Output> { - println!("Blocking begin: {}!", self.value); - // Try replacing this part with commnted code - blocking(|| { - println!("Blocking part annotated: {}!", self.value); - thread::sleep(Duration::from_millis(1000)); - println!("Blocking done annotated: {}!", self.value); - }).map(|result| match result { - Ok(result) => result, - Err(err) => panic!("Error in blocing block: {:?}", err), - }) - // println!("Blocking part annotated: {}!", self.value); - // thread::sleep(Duration::from_millis(1000)); - // println!("Blocking done annotated: {}!", self.value); - // Ok(Async::Ready(())) - } -} - -/// This future returns immideatly. -struct NonBlockingFuture { - value: i32, -} - -impl Future for NonBlockingFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, _ctx: &mut task::Context<'_>) -> Poll<Self::Output> { - println!("Non-blocking done: {}!", self.value); - Poll::Ready(()) - } -} - -/// This future spawns child futures. -struct SpawningFuture; - -impl Future for SpawningFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, _ctx: &mut task::Context<'_>) -> Poll<Self::Output> { - for i in 0..8 { - let blocking_future = BlockingFuture { value: i }; - - tokio::spawn(blocking_future); - } - for i in 0..8 { - let non_blocking_future = NonBlockingFuture { value: i }; - tokio::spawn(non_blocking_future); - } - Poll::Ready(()) - } -} - -fn main() { - let spawning_future = SpawningFuture; - - let mut runtime = Builder::new() - .core_threads(4) - .build().unwrap(); - runtime.block_on_all(spawning_future); -} diff --git a/tokio/examples_old/manual-runtime.rs b/tokio/examples_old/manual-runtime.rs deleted file mode 100644 index 6e2c9921..00000000 --- a/tokio/examples_old/manual-runtime.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! An example how to manually assemble a runtime and run some tasks on it. -//! -//! This is closer to the single-threaded runtime than the default tokio one, as it is simpler to -//! grasp. There are conceptually similar, but the multi-threaded one would be more code. If you -//! just want to *use* a single-threaded runtime, use the one provided by tokio directly -//! (`tokio::runtime::current_thread::Runtime::new()`. This is a demonstration only. -//! -//! Note that the error handling is a bit left out. Also, the `run` could be modified to return the -//! result of the provided future. - -#![warn(rust_2018_idioms)] - -use futures::{future, Future}; -use std::io::Error as IoError; -use std::time::{Duration, Instant}; -use tokio; -use tokio_current_thread; -use tokio_current_thread::CurrentThread; -use tokio_executor; -use tokio_reactor; -use tokio_reactor::Reactor; -use tokio_timer::timer::{self, Timer}; - -/// Creates a "runtime". -/// -/// This is similar to running `tokio::runtime::current_thread::Runtime::new()`. -fn run<F: Future<Item = (), Error = ()>>(f: F) -> Result<(), IoError> { - // We need a reactor to receive events about IO objects from kernel - let reactor = Reactor::new()?; - let reactor_handle = reactor.handle(); - // Place a timer wheel on top of the reactor. If there are no timeouts to fire, it'll let the - // reactor pick up some new external events. - let timer = Timer::new(reactor); - let timer_handle = timer.handle(); - // And now put a single-threaded executor on top of the timer. When there are no futures ready - // to do something, it'll let the timer or the reactor generate some new stimuli for the - // futures to continue in their life. - let mut executor = CurrentThread::new_with_park(timer); - // Binds an executor to this thread - let mut enter = tokio_executor::enter().expect("Multiple executors at once"); - // This will set the default handle and timer to use inside the closure and run the future. - tokio_reactor::with_default(&reactor_handle, &mut enter, |enter| { - timer::with_default(&timer_handle, enter, |enter| { - // The TaskExecutor is a fake executor that looks into the current single-threaded - // executor when used. This is a trick, because we need two mutable references to the - // executor (one to run the provided future, another to install as the default one). We - // use the fake one here as the default one. - let mut default_executor = tokio_current_thread::TaskExecutor::current(); - tokio_executor::with_default(&mut default_executor, enter, |enter| { - let mut executor = executor.enter(enter); - // Run the provided future - executor.block_on(f).unwrap(); - // Run all the other futures that are still left in the executor - executor.run().unwrap(); - }); - }); - }); - Ok(()) -} - -fn main() -> Result<(), Box<dyn std::error::Error>> { - run(future::lazy(|| { - // Here comes the application logic. It can spawn further tasks by tokio_current_thread::spawn(). - // It also can use the default reactor and create timeouts. - - // Connect somewhere. And then do nothing with it. Yes, useless. - // - // This will use the default reactor which runs in the current thread. - let connect = tokio::net::TcpStream::connect(&"127.0.0.1:53".parse().unwrap()) - .map(|_| println!("Connected")) - .map_err(|e| println!("Failed to connect: {}", e)); - // We can spawn it without requiring Send. This would panic if we run it outside of the - // `run` (or outside of anything else) - tokio_current_thread::spawn(connect); - - // We can also create timeouts. - let deadline = tokio::timer::Delay::new(Instant::now() + Duration::from_secs(5)) - .map(|()| println!("5 seconds are over")) - .map_err(|e| println!("Failed to wait: {}", e)); - // We can spawn on the default executor, which is also the local one. - tokio::executor::spawn(deadline); - Ok(()) - }))?; - Ok(()) -} diff --git a/tokio/examples_old/udp-codec.rs b/tokio/examples_old/udp-codec.rs deleted file mode 100644 index 650c3ffc..00000000 --- a/tokio/examples_old/udp-codec.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! This example leverages `BytesCodec` to create a UDP client and server which -//! speak a custom protocol. -//! -//! Here we're using the codec from tokio-io to convert a UDP socket to a stream of -//! client messages. These messages are then processed and returned back as a -//! new message with a new destination. Overall, we then use this to construct a -//! "ping pong" pair where two sockets are sending messages back and forth. - -#![warn(rust_2018_idioms)] - -use env_logger; -use std::net::SocketAddr; -use tokio; -use tokio::net::{UdpFramed, UdpSocket}; -use tokio::prelude::*; -use tokio_codec::BytesCodec; - -fn main() -> Result<(), Box<dyn std::error::Error>> { - let _ = env_logger::init(); - - let addr: SocketAddr = "127.0.0.1:0".parse()?; - - // Bind both our sockets and then figure out what ports we got. - let a = UdpSocket::bind(&addr)?; - let b = UdpSocket::bind(&addr)?; - let b_addr = b.local_addr()?; - - // We're parsing each socket with the `BytesCodec` included in `tokio_io`, and then we - // `split` each codec into the sink/stream halves. - let (a_sink, a_stream) = UdpFramed::new(a, BytesCodec::new()).split(); - let (b_sink, b_stream) = UdpFramed::new(b, BytesCodec::new()).split(); - - // Start off by sending a ping from a to b, afterwards we just print out - // what they send us and continually send pings - // let pings = stream::iter((0..5).map(Ok)); - let a = a_sink.send(("PING".into(), b_addr)).and_then(|a_sink| { - let mut i = 0; - let a_stream = a_stream.take(4).map(move |(msg, addr)| { - i += 1; - println!("[a] recv: {}", String::from_utf8_lossy(&msg)); - (format!("PING {}", i).into(), addr) - }); - a_sink.send_all(a_stream) - }); - - // The second client we have will receive the pings from `a` and then send - // back pongs. - let b_stream = b_stream.map(|(msg, addr)| { - println!("[b] recv: {}", String::from_utf8_lossy(&msg)); - ("PONG".into(), addr) - }); - let b = b_sink.send_all(b_stream); - - // Spawn the sender of pongs and then wait for our pinger to finish. - tokio::run({ - b.join(a) - .map(|_| ()) - .map_err(|e| println!("error = {:?}", e)) - }); - Ok(()) -} diff --git a/tokio/src/lib.rs b/tokio/src/lib.rs index a20a417c..81747bae 100644 --- a/tokio/src/lib.rs +++ b/tokio/src/lib.rs @@ -88,7 +88,7 @@ pub mod io; #[cfg(any(feature = "tcp", feature = "udp", feature = "uds"))] pub mod net; pub mod prelude; -#[cfg(feature = "reactor")] +#[cfg(feature = "tokio-net")] pub mod reactor; pub mod stream; #[cfg(feature = "sync")] diff --git a/tokio/src/reactor.rs b/tokio/src/reactor.rs index 40c055ee..53351e3e 100644 --- a/tokio/src/reactor.rs +++ b/tokio/src/reactor.rs @@ -131,4 +131,4 @@ //! [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html //! [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html -pub use tokio_reactor::{Handle, PollEvented, Reactor, Registration, Turn}; +pub use tokio_net::{Handle, PollEvented, Reactor, Registration, Turn}; diff --git a/tokio/src/runtime/current_thread/builder.rs b/tokio/src/runtime/current_thread/builder.rs index a07df287..7c9cd797 100644 --- a/tokio/src/runtime/current_thread/builder.rs +++ b/tokio/src/runtime/current_thread/builder.rs @@ -1,7 +1,7 @@ use crate::runtime::current_thread::Runtime; use tokio_executor::current_thread::CurrentThread; -use tokio_reactor::Reactor; +use tokio_net::Reactor; use tokio_timer::clock::Clock; use tokio_timer::timer::Timer; diff --git a/tokio/src/runtime/current_thread/runtime.rs b/tokio/src/runtime/current_thread/runtime.rs index a411a034..d730937e 100644 --- a/tokio/src/runtime/current_thread/runtime.rs +++ b/tokio/src/runtime/current_thread/runtime.rs @@ -2,7 +2,7 @@ use crate::runtime::current_thread::Builder; use tokio_executor::current_thread::Handle as ExecutorHandle; use tokio_executor::current_thread::{self, CurrentThread}; -use tokio_reactor::{self, Reactor}; +use tokio_net::{self, Reactor}; use tokio_timer::clock::{self, Clock}; use tokio_timer::timer::{self, Timer}; @@ -19,7 +19,7 @@ use std::io; /// [mod]: index.html #[derive(Debug)] pub struct Runtime { - reactor_handle: tokio_reactor::Handle, + reactor_handle: tokio_net::Handle, timer_handle: timer::Handle, clock: Clock, executor: CurrentThread<Parker>, @@ -93,7 +93,7 @@ impl Runtime { } pub(super) fn new2( - reactor_handle: tokio_reactor::Handle, + reactor_handle: tokio_net::Handle, timer_handle: timer::Handle, clock: Clock, executor: CurrentThread<Parker>, @@ -197,7 +197,7 @@ impl Runtime { // This will set the default handle and timer to use inside the closure // and run the future. - tokio_reactor::with_default(&reactor_handle, || { + tokio_net::with_default(&reactor_handle, || { clock::with_default(clock, || { timer::with_default(&timer_handle, || { // The TaskExecutor is a fake executor that looks into the diff --git a/tokio/src/runtime/threadpool/background.rs b/tokio/src/runtime/threadpool/background.rs index 800c732e..a65e0250 100644 --- a/tokio/src/runtime/threadpool/background.rs +++ b/tokio/src/runtime/threadpool/background.rs @@ -2,7 +2,7 @@ //! `block_on` work. use tokio_executor::current_thread::CurrentThread; -use tokio_reactor::Reactor; +use tokio_net::Reactor; use tokio_sync::oneshot; use tokio_timer::clock::Clock; use tokio_timer::timer::{self, Timer}; @@ -11,7 +11,7 @@ use std::{io, thread}; #[derive(Debug)] pub(crate) struct Background { - reactor_handle: tokio_reactor::Handle, + reactor_handle: tokio_net::Handle, timer_handle: timer::Handle, shutdown_tx: Option<oneshot::Sender<()>>, thread: Option<thread::JoinHandle<()>>, @@ -44,7 +44,7 @@ pub(crate) fn spawn(clock: &Clock) -> io::Result<Background> { } impl Background { - pub(super) fn reactor(&self) -> &tokio_reactor::Handle { + pub(super) fn reactor(&self) -> &tokio_net::Handle { &self.reactor_handle } diff --git a/tokio/src/runtime/threadpool/builder.rs b/tokio/src/runtime/threadpool/builder.rs index f6b06b7d..6f187395 100644 --- a/tokio/src/runtime/threadpool/builder.rs +++ b/tokio/src/runtime/threadpool/builder.rs @@ -1,7 +1,6 @@ use super::{background, Inner, Runtime}; use crate::reactor::Reactor; -use tokio_reactor; use tokio_threadpool::Builder as ThreadPoolBuilder; use tokio_timer::clock::{self, Clock}; use tokio_timer::timer::{self, Timer}; @@ -344,7 +343,7 @@ impl Builder { .around_worker(move |w| { let index = w.id().to_usize(); - tokio_reactor::with_default(&reactor_handles[index], || { + tokio_net::with_default(&reactor_handles[index], || { clock::with_default(&clock, || { timer::with_default(&timer_handles[index], || { trace::dispatcher::with_default(&dispatch, || { diff --git a/tokio/src/runtime/threadpool/mod.rs b/tokio/src/runtime/threadpool/mod.rs index f9341f09..891b9231 100644 --- a/tokio/src/runtime/threadpool/mod.rs +++ b/tokio/src/runtime/threadpool/mod.rs @@ -173,7 +173,7 @@ impl Runtime { let trace = &self.inner().trace; tokio_executor::with_default(&mut self.inner().pool.sender(), || { - tokio_reactor::with_default(bg.reactor(), || { + tokio_net::with_default(bg.reactor(), || { timer::with_default(bg.timer(), || { trace::dispatcher::with_default(trace, || { entered.block_on(future) diff --git a/tokio/tests/reactor.rs b/tokio/tests/reactor.rs index 95159fc1..f72381ed 100644 --- a/tokio/tests/reactor.rs +++ b/tokio/tests/reactor.rs @@ -2,7 +2,7 @@ #![warn(rust_2018_idioms)] #![cfg(feature = "default")] -use tokio_reactor::Reactor; +use tokio_net::Reactor; use tokio_tcp::TcpListener; use tokio_test::{assert_ok, assert_pending}; @@ -66,7 +66,7 @@ fn test_drop_on_notify() { let _enter = tokio_executor::enter().unwrap(); - tokio_reactor::with_default(&reactor.handle(), || { + tokio_net::with_default(&reactor.handle(), || { let waker = waker_ref(&task); let mut cx = Context::from_waker(&waker); assert_pending!(task.future.lock().unwrap().as_mut().poll(&mut cx)); |