1
0
mirror of https://github.com/fafhrd91/actix-net synced 2024-11-24 00:01:11 +01:00

convert to edition 2018

This commit is contained in:
Nikolay Kim 2018-12-06 14:04:42 -08:00
parent 42a4679635
commit 8fe7ce533c
21 changed files with 103 additions and 136 deletions

View File

@ -11,6 +11,7 @@ documentation = "https://docs.rs/actix-net/"
categories = ["network-programming", "asynchronous"] categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"] features = ["ssl", "tls", "rust-tls"]

View File

@ -80,7 +80,8 @@ fn main() {
future::ok(()) future::ok(())
}) })
}, },
).unwrap() )
.unwrap()
.start(); .start();
sys.run(); sys.run();

View File

@ -61,7 +61,8 @@ fn main() {
println!("got ssl connection {:?}", num); println!("got ssl connection {:?}", num);
future::ok(()) future::ok(())
}) })
}).unwrap() })
.unwrap()
.start(); .start();
sys.run(); sys.run();

View File

@ -1,7 +1,8 @@
use std::fmt; use std::fmt;
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Async, Poll, Sink, StartSend, Stream}; use futures::{try_ready, Async, Poll, Sink, StartSend, Stream};
use log::trace;
use tokio_codec::Decoder; use tokio_codec::Decoder;
use tokio_io::AsyncRead; use tokio_io::AsyncRead;
@ -133,7 +134,7 @@ where
pub fn framed_read2<T>(inner: T) -> FramedRead2<T> { pub fn framed_read2<T>(inner: T) -> FramedRead2<T> {
FramedRead2 { FramedRead2 {
inner: inner, inner,
eof: false, eof: false,
is_readable: false, is_readable: false,
buffer: BytesMut::with_capacity(INITIAL_CAPACITY), buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
@ -146,9 +147,9 @@ pub fn framed_read2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedRead2<T
buf.reserve(bytes_to_reserve); buf.reserve(bytes_to_reserve);
} }
FramedRead2 { FramedRead2 {
inner: inner, inner,
eof: false, eof: false,
is_readable: buf.len() > 0, is_readable: !buf.is_empty(),
buffer: buf, buffer: buf,
} }
} }
@ -187,13 +188,13 @@ where
// readable again, at which point the stream is terminated. // readable again, at which point the stream is terminated.
if self.is_readable { if self.is_readable {
if self.eof { if self.eof {
let frame = try!(self.inner.decode_eof(&mut self.buffer)); let frame = self.inner.decode_eof(&mut self.buffer)?;
return Ok(Async::Ready(frame)); return Ok(Async::Ready(frame));
} }
trace!("attempting to decode a frame"); trace!("attempting to decode a frame");
if let Some(frame) = try!(self.inner.decode(&mut self.buffer)) { if let Some(frame) = self.inner.decode(&mut self.buffer)? {
trace!("frame decoded from buffer"); trace!("frame decoded from buffer");
return Ok(Async::Ready(Some(frame))); return Ok(Async::Ready(Some(frame)));
} }

View File

@ -2,7 +2,8 @@ use std::fmt;
use std::io::{self, Read}; use std::io::{self, Read};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream};
use log::trace;
use tokio_codec::{Decoder, Encoder}; use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
@ -111,7 +112,7 @@ where
} }
fn close(&mut self) -> Poll<(), Self::SinkError> { fn close(&mut self) -> Poll<(), Self::SinkError> {
Ok(try!(self.inner.close())) Ok(self.inner.close()?)
} }
} }
@ -254,7 +255,8 @@ where
io::ErrorKind::WriteZero, io::ErrorKind::WriteZero,
"failed to \ "failed to \
write frame to transport", write frame to transport",
).into()); )
.into());
} }
// TODO: Add a way to `bytes` to do this w/o returning the drained // TODO: Add a way to `bytes` to do this w/o returning the drained
@ -266,12 +268,12 @@ where
try_ready!(self.inner.poll_flush()); try_ready!(self.inner.poll_flush());
trace!("framed transport flushed"); trace!("framed transport flushed");
return Ok(Async::Ready(())); Ok(Async::Ready(()))
} }
fn close(&mut self) -> Poll<(), Self::SinkError> { fn close(&mut self) -> Poll<(), Self::SinkError> {
try_ready!(self.poll_complete()); try_ready!(self.poll_complete());
Ok(try!(self.inner.shutdown())) Ok(self.inner.shutdown()?)
} }
} }

View File

@ -5,7 +5,7 @@ use std::time::Duration;
use std::{fmt, io}; use std::{fmt, io};
use futures::future::{ok, Either, FutureResult}; use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use tokio_tcp::{ConnectFuture, TcpStream}; use tokio_tcp::{ConnectFuture, TcpStream};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts}; use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
@ -119,8 +119,8 @@ impl Connect {
impl RequestHost for Connect { impl RequestHost for Connect {
fn host(&self) -> &str { fn host(&self) -> &str {
match self.kind { match self.kind {
ConnectKind::Host { ref host, port: _ } => host, ConnectKind::Host { ref host, .. } => host,
ConnectKind::Addr { ref host, addr: _ } => host, ConnectKind::Addr { ref host, .. } => host,
} }
} }
} }
@ -128,8 +128,8 @@ impl RequestHost for Connect {
impl RequestPort for Connect { impl RequestPort for Connect {
fn port(&self) -> u16 { fn port(&self) -> u16 {
match self.kind { match self.kind {
ConnectKind::Host { host: _, port } => port, ConnectKind::Host { port, .. } => port,
ConnectKind::Addr { host: _, addr } => addr.port(), ConnectKind::Addr { addr, .. } => addr.port(),
} }
} }
} }
@ -206,11 +206,11 @@ impl Service<Connect> for Connector {
fn call(&mut self, req: Connect) -> Self::Future { fn call(&mut self, req: Connect) -> Self::Future {
match req.kind { match req.kind {
ConnectKind::Host { host: _, port: _ } => Either::A(ConnectorFuture { ConnectKind::Host { .. } => Either::A(ConnectorFuture {
fut: self.resolver.call(req), fut: self.resolver.call(req),
fut2: None, fut2: None,
}), }),
ConnectKind::Addr { host: _, addr } => { ConnectKind::Addr { addr, .. } => {
let mut addrs = VecDeque::new(); let mut addrs = VecDeque::new();
addrs.push_back(addr.ip()); addrs.push_back(addr.ip());
Either::B(ConnectorTcpFuture { Either::B(ConnectorTcpFuture {

View File

@ -1,5 +1,5 @@
//! Contains `Either` service and related types and functions. //! Contains `Either` service and related types and functions.
use futures::{future, Async, Future, Poll}; use futures::{future, try_ready, Async, Future, Poll};
use super::service::{NewService, Service}; use super::service::{NewService, Service};

View File

@ -9,8 +9,8 @@ use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use tokio_codec::{Decoder, Encoder}; use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use codec::Framed; use crate::codec::Framed;
use service::{IntoNewService, IntoService, NewService, Service}; use crate::service::{IntoNewService, IntoService, NewService, Service};
type Request<U> = <U as Decoder>::Item; type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item; type Response<U> = <U as Encoder>::Item;
@ -300,10 +300,10 @@ where
} }
} }
} }
Ok(Async::NotReady) => return false, Ok(Async::NotReady) => false,
Err(err) => { Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err)); self.state = TransportState::Error(FramedTransportError::Service(err));
return true; true
} }
} }
} }
@ -387,26 +387,22 @@ where
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match mem::replace(&mut self.state, TransportState::Processing) { match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => { TransportState::Processing => {
if self.poll_service() { if self.poll_service() || self.poll_response() {
return self.poll(); self.poll()
} else {
Ok(Async::NotReady)
} }
if self.poll_response() {
return self.poll();
}
return Ok(Async::NotReady);
} }
TransportState::Error(err) => { TransportState::Error(err) => {
if self.poll_response() { if self.poll_response() || self.flushed {
return Err(err); Err(err)
} else {
self.state = TransportState::Error(err);
Ok(Async::NotReady)
} }
if self.flushed {
return Err(err);
}
self.state = TransportState::Error(err);
return Ok(Async::NotReady);
} }
TransportState::EncoderError(err) => return Err(err), TransportState::EncoderError(err) => Err(err),
TransportState::Stopping => return Ok(Async::Ready(())), TransportState::Stopping => Ok(Async::Ready(())),
} }
} }
} }

View File

@ -1,4 +1,4 @@
use futures::{Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use super::counter::{Counter, CounterGuard}; use super::counter::{Counter, CounterGuard};
use super::service::{IntoNewService, IntoService, NewService, Service}; use super::service::{IntoNewService, IntoService, NewService, Service};

View File

@ -7,54 +7,11 @@
//! * `rust-tls` - enables ssl support via `rustls` crate //! * `rust-tls` - enables ssl support via `rustls` crate
// #![warn(missing_docs)] // #![warn(missing_docs)]
#![cfg_attr( #![allow(
feature = "cargo-clippy", clippy::declare_interior_mutable_const,
allow( clippy::borrow_interior_mutable_const
declare_interior_mutable_const,
borrow_interior_mutable_const
)
)] )]
#[macro_use]
extern crate log;
extern crate bytes;
#[macro_use]
extern crate futures;
extern crate mio;
extern crate net2;
extern crate num_cpus;
extern crate slab;
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate tokio_reactor;
extern crate tokio_tcp;
extern crate tokio_timer;
extern crate tower_service;
extern crate trust_dns_resolver;
#[allow(unused_imports)]
#[macro_use]
extern crate actix;
#[cfg(feature = "tls")]
extern crate native_tls;
#[cfg(feature = "ssl")]
extern crate openssl;
#[cfg(feature = "ssl")]
extern crate tokio_openssl;
#[cfg(feature = "rust-tls")]
extern crate rustls;
#[cfg(feature = "rust-tls")]
extern crate tokio_rustls;
#[cfg(feature = "rust-tls")]
extern crate webpki;
#[cfg(feature = "rust-tls")]
extern crate webpki_roots;
mod cell; mod cell;
pub mod cloneable; pub mod cloneable;
pub mod codec; pub mod codec;

View File

@ -3,6 +3,7 @@ use std::time::{Duration, Instant};
use std::{io, net, thread}; use std::{io, net, thread};
use futures::{sync::mpsc, Future}; use futures::{sync::mpsc, Future};
use log::{error, info};
use mio; use mio;
use slab::Slab; use slab::Slab;
use tokio_timer::Delay; use tokio_timer::Delay;
@ -134,7 +135,7 @@ fn connection_error(e: &io::Error) -> bool {
} }
impl Accept { impl Accept {
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] #![allow(clippy::too_many_arguments)]
pub(crate) fn start( pub(crate) fn start(
rx: sync_mpsc::Receiver<Command>, rx: sync_mpsc::Receiver<Command>,
cmd_reg: mio::Registration, cmd_reg: mio::Registration,

View File

@ -2,10 +2,11 @@ use std::collections::HashMap;
use std::{fmt, io, net}; use std::{fmt, io, net};
use futures::future::{join_all, Future}; use futures::future::{join_all, Future};
use log::error;
use tokio_tcp::TcpStream; use tokio_tcp::TcpStream;
use counter::CounterGuard; use crate::counter::CounterGuard;
use service::{IntoNewService, NewService}; use crate::service::{IntoNewService, NewService};
use super::server::bind_addr; use super::server::bind_addr;
use super::services::{ use super::services::{
@ -111,7 +112,7 @@ impl InternalServiceFactory for ConfiguredService {
pub(super) trait ServiceRuntimeConfiguration: Send { pub(super) trait ServiceRuntimeConfiguration: Send {
fn clone(&self) -> Box<ServiceRuntimeConfiguration>; fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
fn configure(&self, &mut ServiceRuntime); fn configure(&self, rt: &mut ServiceRuntime);
} }
impl<F> ServiceRuntimeConfiguration for F impl<F> ServiceRuntimeConfiguration for F

View File

@ -3,6 +3,7 @@ use std::{io, mem, net};
use futures::sync::{mpsc, mpsc::unbounded}; use futures::sync::{mpsc, mpsc::unbounded};
use futures::{Future, Sink, Stream}; use futures::{Future, Sink, Stream};
use log::{error, info};
use net2::TcpBuilder; use net2::TcpBuilder;
use num_cpus; use num_cpus;
@ -284,7 +285,7 @@ impl Server {
self.services.iter().map(|v| v.clone_factory()).collect(); self.services.iter().map(|v| v.clone_factory()).collect();
Arbiter::new(format!("actix-net-worker-{}", idx)).do_send(Execute::new(move || { Arbiter::new(format!("actix-net-worker-{}", idx)).do_send(Execute::new(move || {
Worker::start(rx1, rx2, services, avail, timeout.clone()); Worker::start(rx1, rx2, services, avail, timeout);
Ok::<_, ()>(()) Ok::<_, ()>(())
})); }));
@ -376,7 +377,7 @@ impl Handler<StopServer> for Server {
} }
if !self.workers.is_empty() { if !self.workers.is_empty() {
Response::async(rx.into_future().map(|_| ()).map_err(|_| ())) Response::r#async(rx.into_future().map(|_| ()).map_err(|_| ()))
} else { } else {
// we need to stop system if server was spawned // we need to stop system if server was spawned
if self.exit { if self.exit {

View File

@ -3,13 +3,14 @@ use std::time::Duration;
use futures::future::{err, ok, FutureResult}; use futures::future::{err, ok, FutureResult};
use futures::{Future, Poll}; use futures::{Future, Poll};
use log::error;
use tokio_current_thread::spawn; use tokio_current_thread::spawn;
use tokio_reactor::Handle; use tokio_reactor::Handle;
use tokio_tcp::TcpStream; use tokio_tcp::TcpStream;
use super::Token; use super::Token;
use counter::CounterGuard; use crate::counter::CounterGuard;
use service::{NewService, Service}; use crate::service::{NewService, Service};
/// Server message /// Server message
pub enum ServerMessage { pub enum ServerMessage {

View File

@ -5,6 +5,7 @@ use std::{mem, net, time};
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::sync::oneshot; use futures::sync::oneshot;
use futures::{future, Async, Future, Poll, Stream}; use futures::{future, Async, Future, Poll, Stream};
use log::{error, info, trace};
use tokio_current_thread::spawn; use tokio_current_thread::spawn;
use tokio_timer::{sleep, Delay}; use tokio_timer::{sleep, Delay};
@ -14,7 +15,7 @@ use actix::{Arbiter, Message};
use super::accept::AcceptNotify; use super::accept::AcceptNotify;
use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage}; use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
use super::Token; use super::Token;
use counter::Counter; use crate::counter::Counter;
pub(crate) struct WorkerCommand(Conn); pub(crate) struct WorkerCommand(Conn);
@ -167,7 +168,8 @@ impl Worker {
.map_err(|e| { .map_err(|e| {
error!("Can not start worker: {:?}", e); error!("Can not start worker: {:?}", e);
Arbiter::current().do_send(StopArbiter(0)); Arbiter::current().do_send(StopArbiter(0));
}).and_then(move |services| { })
.and_then(move |services| {
for item in services { for item in services {
for (idx, token, service) in item { for (idx, token, service) in item {
while token.0 >= wrk.services.len() { while token.0 >= wrk.services.len() {
@ -192,7 +194,7 @@ impl Worker {
let timeout = self.shutdown_timeout; let timeout = self.shutdown_timeout;
self.services.iter_mut().for_each(move |h| { self.services.iter_mut().for_each(move |h| {
if let Some(h) = h { if let Some(h) = h {
let _ = h.1.call((None, ServerMessage::Shutdown(timeout.clone()))); let _ = h.1.call((None, ServerMessage::Shutdown(timeout)));
} }
}); });
} }
@ -249,36 +251,33 @@ impl Future for Worker {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// `StopWorker` message handler // `StopWorker` message handler
match self.rx2.poll() { if let Ok(Async::Ready(Some(StopCommand { graceful, result }))) = self.rx2.poll() {
Ok(Async::Ready(Some(StopCommand { graceful, result }))) => { self.availability.set(false);
self.availability.set(false); let num = num_connections();
if num == 0 {
info!("Shutting down worker, 0 connections");
let _ = result.send(true);
return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
let num = num_connections(); let num = num_connections();
if num == 0 { if num != 0 {
info!("Shutting down worker, 0 connections"); info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
let _ = result.send(true); let _ = result.send(true);
return Ok(Async::Ready(())); return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
let num = num_connections();
if num != 0 {
info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
let _ = result.send(true);
return Ok(Async::Ready(()));
}
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
} }
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
} }
_ => (),
} }
let state = mem::replace(&mut self.state, WorkerState::None); let state = mem::replace(&mut self.state, WorkerState::None);

View File

@ -1,7 +1,7 @@
use futures::{Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use super::{IntoNewService, NewService, Service}; use super::{IntoNewService, NewService, Service};
use cell::Cell; use crate::cell::Cell;
/// Service for the `and_then` combinator, chaining a computation onto the end /// Service for the `and_then` combinator, chaining a computation onto the end
/// of another service which completes successfully. /// of another service which completes successfully.
@ -45,7 +45,7 @@ where
type Future = AndThenFuture<A, B, Request>; type Future = AndThenFuture<A, B, Request>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let _ = try_ready!(self.a.poll_ready()); try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready() self.b.borrow_mut().poll_ready()
} }

View File

@ -55,7 +55,7 @@ where
type Future = Out::Future; type Future = Out::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(|e| e.into()) self.service.poll_ready()
} }
fn call(&mut self, req: In) -> Self::Future { fn call(&mut self, req: In) -> Self::Future {

View File

@ -1,7 +1,7 @@
use futures::{Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use super::{IntoNewService, NewService, Service}; use super::{IntoNewService, NewService, Service};
use cell::Cell; use crate::cell::Cell;
/// Service for the `then` combinator, chaining a computation onto the end of /// Service for the `then` combinator, chaining a computation onto the end of
/// another service. /// another service.
@ -45,7 +45,7 @@ where
type Future = ThenFuture<A, B, Request>; type Future = ThenFuture<A, B, Request>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let _ = try_ready!(self.a.poll_ready()); try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready() self.b.borrow_mut().poll_ready()
} }

View File

@ -106,6 +106,12 @@ impl<T> TakeItem<T> {
} }
} }
impl<T> Default for TakeItem<T> {
fn default() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Clone for TakeItem<T> { impl<T> Clone for TakeItem<T> {
fn clone(&self) -> TakeItem<T> { fn clone(&self) -> TakeItem<T> {
TakeItem { _t: PhantomData } TakeItem { _t: PhantomData }

View File

@ -66,7 +66,7 @@ impl LowResTimeService {
/// Get current time. This function has to be called from /// Get current time. This function has to be called from
/// future's poll method, otherwise it panics. /// future's poll method, otherwise it panics.
pub fn now(&self) -> Instant { pub fn now(&self) -> Instant {
let cur = self.0.borrow().current.clone(); let cur = self.0.borrow().current;
if let Some(cur) = cur { if let Some(cur) = cur {
cur cur
} else { } else {

View File

@ -5,10 +5,11 @@
use std::fmt; use std::fmt;
use std::time::Duration; use std::time::Duration;
use futures::try_ready;
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay}; use tokio_timer::{clock, Delay};
use service::{NewService, Service}; use crate::service::{NewService, Service};
/// Applies a timeout to requests. /// Applies a timeout to requests.
#[derive(Debug)] #[derive(Debug)]
@ -56,7 +57,7 @@ where
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
TimeoutFut { TimeoutFut {
fut: self.inner.new_service(), fut: self.inner.new_service(),
timeout: self.timeout.clone(), timeout: self.timeout,
} }
} }
} }
@ -115,9 +116,7 @@ where
type Future = TimeoutServiceResponse<T, Request>; type Future = TimeoutServiceResponse<T, Request>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner self.inner.poll_ready().map_err(TimeoutError::Service)
.poll_ready()
.map_err(|e| TimeoutError::Service(e))
} }
fn call(&mut self, request: Request) -> Self::Future { fn call(&mut self, request: Request) -> Self::Future {