1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-20 08:31:09 +00:00

upgrade to actix 0.4

This commit is contained in:
Nikolay Kim 2018-01-05 13:30:21 -08:00
parent dea354d6d8
commit 5ff35f5b99
19 changed files with 75 additions and 90 deletions

View file

@ -32,9 +32,6 @@ tls = ["native-tls", "tokio-tls"]
# openssl # openssl
alpn = ["openssl", "openssl/v102", "openssl/v110", "tokio-openssl"] alpn = ["openssl", "openssl/v102", "openssl/v110", "tokio-openssl"]
# signals
signal = ["actix/signal"]
[dependencies] [dependencies]
log = "0.3" log = "0.3"
failure = "0.1" failure = "0.1"
@ -77,9 +74,7 @@ tokio-tls = { version="0.1", optional = true }
tokio-openssl = { version="0.1", optional = true } tokio-openssl = { version="0.1", optional = true }
[dependencies.actix] [dependencies.actix]
version = "^0.3.5" version = "0.4"
default-features = false
features = []
[dependencies.openssl] [dependencies.openssl]
version = "0.9" version = "0.9"

View file

@ -7,5 +7,5 @@ workspace = "../.."
[dependencies] [dependencies]
futures = "*" futures = "*"
env_logger = "0.4" env_logger = "0.4"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }

View file

@ -11,7 +11,6 @@ use actix::*;
use actix_web::*; use actix_web::*;
use actix_web::middleware::RequestSession; use actix_web::middleware::RequestSession;
use futures::future::{FutureResult, result}; use futures::future::{FutureResult, result};
#[cfg(unix)]
use actix::actors::signal::{ProcessSignals, Subscribe}; use actix::actors::signal::{ProcessSignals, Subscribe};
/// simple handler /// simple handler
@ -97,11 +96,8 @@ fn main() {
.start(); .start();
// Subscribe to unix signals // Subscribe to unix signals
#[cfg(unix)] let signals = actix::Arbiter::system_registry().get::<ProcessSignals>();
{ signals.send(Subscribe(addr.subscriber()));
let signals = actix::Arbiter::system_registry().get::<ProcessSignals>();
signals.send(Subscribe(addr.subscriber()));
}
println!("Starting http server: 127.0.0.1:8080"); println!("Starting http server: 127.0.0.1:8080");
let _ = sys.run(); let _ = sys.run();

View file

@ -6,8 +6,8 @@ workspace = "../.."
[dependencies] [dependencies]
env_logger = "0.4" env_logger = "0.4"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }
futures = "0.1" futures = "0.1"
uuid = { version = "0.5", features = ["serde", "v4"] } uuid = { version = "0.5", features = ["serde", "v4"] }

View file

@ -6,5 +6,5 @@ workspace = "../.."
[dependencies] [dependencies]
env_logger = "0.4" env_logger = "0.4"
actix = "^0.3.5" actix = "0.4"
actix-web = { path = "../../" } actix-web = { path = "../../" }

View file

@ -14,5 +14,5 @@ serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
json = "*" json = "*"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }

View file

@ -11,5 +11,5 @@ path = "src/main.rs"
[dependencies] [dependencies]
env_logger = "*" env_logger = "*"
futures = "0.1" futures = "0.1"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }

View file

@ -11,5 +11,5 @@ path = "src/main.rs"
[dependencies] [dependencies]
env_logger = "*" env_logger = "*"
futures = "0.1" futures = "0.1"
actix = "^0.3.5" actix = "0.4"
actix-web = { path = "../../", features=["signal"] } actix-web = { path = "../../" }

View file

@ -7,5 +7,5 @@ workspace = "../.."
[dependencies] [dependencies]
futures = "*" futures = "*"
env_logger = "0.4" env_logger = "0.4"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }

View file

@ -6,6 +6,6 @@ workspace = "../.."
[dependencies] [dependencies]
env_logger = "0.4" env_logger = "0.4"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }
tera = "*" tera = "*"

View file

@ -10,5 +10,5 @@ path = "src/main.rs"
[dependencies] [dependencies]
env_logger = "0.4" env_logger = "0.4"
actix = { version = "^0.3.5" } actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal", "alpn"] } actix-web = { git = "https://github.com/actix/actix-web", features=["alpn"] }

View file

@ -25,5 +25,5 @@ serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
actix = { version = "^0.3.5" } actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web" }

View file

@ -10,5 +10,5 @@ path = "src/main.rs"
[dependencies] [dependencies]
env_logger = "*" env_logger = "*"
futures = "0.1" futures = "0.1"
actix = "^0.3.5" actix = "0.4"
actix-web = { git = "https://github.com/actix/actix-web.git", features=["signal"] } actix-web = { git = "https://github.com/actix/actix-web.git" }

View file

@ -195,13 +195,8 @@ fn main() {
} }
``` ```
It is possible to use unix signals on compatible OSs. "signal" feature needs to be enabled It is possible to use signals. *CTRL-C* is available on all OSs, other signals are
in *Cargo.toml* for *actix-web* dependency. available on unix systems.
```toml
[dependencies]
actix-web = { git = "https://github.com/actix/actix-web", features=["signal"] }
```
Then you can subscribe your server to unix signals. Http server handles three signals: Then you can subscribe your server to unix signals. Http server handles three signals:

View file

@ -23,15 +23,15 @@ impl Actor for Ws {
/// Define Handler for ws::Message message /// Define Handler for ws::Message message
# impl StreamHandler<ws::Message> for Ws {} # impl StreamHandler<ws::Message> for Ws {}
impl Handler<ws::Message> for Ws { impl Handler<ws::Message> for Ws {
fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>) -> Response<Self, ws::Message> type Result=();
{
fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>) {
match msg { match msg {
ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg), ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg),
ws::Message::Text(text) => ws::WsWriter::text(ctx, &text), ws::Message::Text(text) => ws::WsWriter::text(ctx, &text),
ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin), ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin),
_ => (), _ => (),
} }
Self::empty()
} }
} }

View file

@ -6,9 +6,9 @@ use futures::sync::oneshot::Sender;
use futures::unsync::oneshot; use futures::unsync::oneshot;
use actix::{Actor, ActorState, ActorContext, AsyncContext, use actix::{Actor, ActorState, ActorContext, AsyncContext,
Handler, Subscriber, ResponseType}; Handler, Subscriber, ResponseType, SpawnHandle};
use actix::fut::ActorFuture; use actix::fut::ActorFuture;
use actix::dev::{AsyncContextApi, ActorAddressCell, ActorItemsCell, ActorWaitCell, SpawnHandle, use actix::dev::{AsyncContextApi, ActorAddressCell, ActorItemsCell, ActorWaitCell,
Envelope, ToEnvelope, RemoteEnvelope}; Envelope, ToEnvelope, RemoteEnvelope};
use body::{Body, Binary}; use body::{Body, Binary};
@ -290,13 +290,14 @@ impl<A, S> ActorHttpContext for HttpContext<A, S> where A: Actor<Context=Self>,
impl<A, S> ToEnvelope<A> for HttpContext<A, S> impl<A, S> ToEnvelope<A> for HttpContext<A, S>
where A: Actor<Context=HttpContext<A, S>>, where A: Actor<Context=HttpContext<A, S>>,
{ {
fn pack<M>(msg: M, tx: Option<Sender<Result<M::Item, M::Error>>>) -> Envelope<A> fn pack<M>(msg: M, tx: Option<Sender<Result<M::Item, M::Error>>>,
channel_on_drop: bool) -> Envelope<A>
where A: Handler<M>, where A: Handler<M>,
M: ResponseType + Send + 'static, M: ResponseType + Send + 'static,
M::Item: Send, M::Item: Send,
M::Error: Send M::Error: Send
{ {
RemoteEnvelope::new(msg, tx).into() RemoteEnvelope::new(msg, tx, channel_on_drop).into()
} }
} }

View file

@ -5,12 +5,12 @@ use std::time::Duration;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::collections::HashMap; use std::collections::HashMap;
use actix::dev::*; use actix::prelude::*;
use actix::System;
use futures::{Future, Sink, Stream}; use futures::{Future, Sink, Stream};
use futures::sync::mpsc; use futures::sync::mpsc;
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use tokio_core::net::TcpStream; use tokio_core::net::TcpStream;
use actix::actors::signal;
use mio; use mio;
use num_cpus; use num_cpus;
use net2::TcpBuilder; use net2::TcpBuilder;
@ -27,9 +27,6 @@ use openssl::pkcs12::ParsedPkcs12;
#[cfg(feature="alpn")] #[cfg(feature="alpn")]
use tokio_openssl::SslStream; use tokio_openssl::SslStream;
#[cfg(feature="signal")]
use actix::actors::signal;
use helpers; use helpers;
use channel::{HttpChannel, HttpHandler, IntoHttpHandler, IoStream, WrapperStream}; use channel::{HttpChannel, HttpHandler, IntoHttpHandler, IoStream, WrapperStream};
use worker::{Conn, Worker, WorkerSettings, StreamHandlerType, StopWorker}; use worker::{Conn, Worker, WorkerSettings, StreamHandlerType, StopWorker};
@ -202,7 +199,6 @@ impl<T, A, H, U, V> HttpServer<T, A, H, U>
self self
} }
#[cfg(feature="signal")]
/// Send `SystemExit` message to actix system /// Send `SystemExit` message to actix system
/// ///
/// `SystemExit` message stops currently running system arbiter and all /// `SystemExit` message stops currently running system arbiter and all
@ -271,7 +267,7 @@ impl<T, A, H, U, V> HttpServer<T, A, H, U>
let apps: Vec<_> = (*factory)() let apps: Vec<_> = (*factory)()
.into_iter() .into_iter()
.map(|h| h.into_handler(s.clone())).collect(); .map(|h| h.into_handler(s.clone())).collect();
ctx.add_stream(rx); ctx.add_message_stream(rx);
Worker::new(apps, h, ka) Worker::new(apps, h, ka)
}); });
workers.push(tx); workers.push(tx);
@ -494,8 +490,7 @@ impl<T, A, H, U, V> HttpServer<WrapperStream<T>, A, H, U>
} }
} }
#[cfg(feature="signal")] /// Signals support
/// Unix Signals support
/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and send `SystemExit(0)` /// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and send `SystemExit(0)`
/// message to `System` actor. /// message to `System` actor.
impl<T, A, H, U> Handler<signal::Signal> for HttpServer<T, A, H, U> impl<T, A, H, U> Handler<signal::Signal> for HttpServer<T, A, H, U>
@ -504,9 +499,9 @@ impl<T, A, H, U> Handler<signal::Signal> for HttpServer<T, A, H, U>
U: 'static, U: 'static,
A: 'static, A: 'static,
{ {
fn handle(&mut self, msg: signal::Signal, ctx: &mut Context<Self>) type Result = ();
-> Response<Self, signal::Signal>
{ fn handle(&mut self, msg: signal::Signal, ctx: &mut Context<Self>) {
match msg.0 { match msg.0 {
signal::SignalType::Int => { signal::SignalType::Int => {
info!("SIGINT received, exiting"); info!("SIGINT received, exiting");
@ -524,32 +519,33 @@ impl<T, A, H, U> Handler<signal::Signal> for HttpServer<T, A, H, U>
Handler::<StopServer>::handle(self, StopServer{graceful: false}, ctx); Handler::<StopServer>::handle(self, StopServer{graceful: false}, ctx);
} }
_ => (), _ => (),
}; }
Self::empty()
} }
} }
impl<T, A, H, U> StreamHandler<Conn<T>, io::Error> for HttpServer<T, A, H, U> impl<T, A, H, U> StreamHandler<io::Result<Conn<T>>> for HttpServer<T, A, H, U>
where T: IoStream, where T: IoStream,
H: HttpHandler + 'static, H: HttpHandler + 'static,
U: 'static, U: 'static,
A: 'static {} A: 'static {}
impl<T, A, H, U> Handler<Conn<T>, io::Error> for HttpServer<T, A, H, U> impl<T, A, H, U> Handler<io::Result<Conn<T>>> for HttpServer<T, A, H, U>
where T: IoStream, where T: IoStream,
H: HttpHandler + 'static, H: HttpHandler + 'static,
U: 'static, U: 'static,
A: 'static, A: 'static,
{ {
fn error(&mut self, err: io::Error, _: &mut Context<Self>) { type Result = ();
debug!("Error handling request: {}", err)
}
fn handle(&mut self, msg: Conn<T>, _: &mut Context<Self>) -> Response<Self, Conn<T>> fn handle(&mut self, msg: io::Result<Conn<T>>, _: &mut Context<Self>) -> Self::Result {
{ match msg {
Arbiter::handle().spawn( Ok(msg) =>
HttpChannel::new(Rc::clone(self.h.as_ref().unwrap()), msg.io, msg.peer, msg.http2)); Arbiter::handle().spawn(
Self::empty() HttpChannel::new(
Rc::clone(self.h.as_ref().unwrap()), msg.io, msg.peer, msg.http2)),
Err(err) =>
debug!("Error handling request: {}", err),
}
} }
} }
@ -578,13 +574,14 @@ impl<T, A, H, U> Handler<PauseServer> for HttpServer<T, A, H, U>
U: 'static, U: 'static,
A: 'static, A: 'static,
{ {
fn handle(&mut self, _: PauseServer, _: &mut Context<Self>) -> Response<Self, PauseServer> type Result = ();
fn handle(&mut self, _: PauseServer, _: &mut Context<Self>)
{ {
for item in &self.accept { for item in &self.accept {
let _ = item.1.send(Command::Pause); let _ = item.1.send(Command::Pause);
let _ = item.0.set_readiness(mio::Ready::readable()); let _ = item.0.set_readiness(mio::Ready::readable());
} }
Self::empty()
} }
} }
@ -594,13 +591,13 @@ impl<T, A, H, U> Handler<ResumeServer> for HttpServer<T, A, H, U>
U: 'static, U: 'static,
A: 'static, A: 'static,
{ {
fn handle(&mut self, _: ResumeServer, _: &mut Context<Self>) -> Response<Self, ResumeServer> type Result = ();
{
fn handle(&mut self, _: ResumeServer, _: &mut Context<Self>) {
for item in &self.accept { for item in &self.accept {
let _ = item.1.send(Command::Resume); let _ = item.1.send(Command::Resume);
let _ = item.0.set_readiness(mio::Ready::readable()); let _ = item.0.set_readiness(mio::Ready::readable());
} }
Self::empty()
} }
} }
@ -610,8 +607,9 @@ impl<T, A, H, U> Handler<StopServer> for HttpServer<T, A, H, U>
U: 'static, U: 'static,
A: 'static, A: 'static,
{ {
fn handle(&mut self, msg: StopServer, ctx: &mut Context<Self>) -> Response<Self, StopServer> type Result = actix::Response<Self, StopServer>;
{
fn handle(&mut self, msg: StopServer, ctx: &mut Context<Self>) -> Self::Result {
// stop accept threads // stop accept threads
for item in &self.accept { for item in &self.accept {
let _ = item.1.send(Command::Stop); let _ = item.1.send(Command::Stop);
@ -636,10 +634,10 @@ impl<T, A, H, U> Handler<StopServer> for HttpServer<T, A, H, U>
// we need to stop system if server was spawned // we need to stop system if server was spawned
if slf.exit { if slf.exit {
Arbiter::system().send(msgs::SystemExit(0)) Arbiter::system().send(actix::msgs::SystemExit(0))
} }
} }
fut::ok(()) actix::fut::ok(())
}).spawn(ctx); }).spawn(ctx);
} }
@ -649,7 +647,7 @@ impl<T, A, H, U> Handler<StopServer> for HttpServer<T, A, H, U>
} 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 {
Arbiter::system().send(msgs::SystemExit(0)) Arbiter::system().send(actix::msgs::SystemExit(0))
} }
Self::empty() Self::empty()
} }

View file

@ -157,8 +157,9 @@ impl<H> StreamHandler<Conn<net::TcpStream>> for Worker<H>
impl<H> Handler<Conn<net::TcpStream>> for Worker<H> impl<H> Handler<Conn<net::TcpStream>> for Worker<H>
where H: HttpHandler + 'static, where H: HttpHandler + 'static,
{ {
type Result = ();
fn handle(&mut self, msg: Conn<net::TcpStream>, _: &mut Context<Self>) fn handle(&mut self, msg: Conn<net::TcpStream>, _: &mut Context<Self>)
-> Response<Self, Conn<net::TcpStream>>
{ {
if !self.settings.keep_alive_enabled() && if !self.settings.keep_alive_enabled() &&
msg.io.set_keepalive(Some(time::Duration::new(75, 0))).is_err() msg.io.set_keepalive(Some(time::Duration::new(75, 0))).is_err()
@ -166,7 +167,6 @@ impl<H> Handler<Conn<net::TcpStream>> for Worker<H>
error!("Can not set socket keep-alive option"); error!("Can not set socket keep-alive option");
} }
self.handler.handle(Rc::clone(&self.settings), &self.hnd, msg); self.handler.handle(Rc::clone(&self.settings), &self.hnd, msg);
Self::empty()
} }
} }
@ -174,8 +174,9 @@ impl<H> Handler<Conn<net::TcpStream>> for Worker<H>
impl<H> Handler<StopWorker> for Worker<H> impl<H> Handler<StopWorker> for Worker<H>
where H: HttpHandler + 'static, where H: HttpHandler + 'static,
{ {
fn handle(&mut self, msg: StopWorker, ctx: &mut Context<Self>) -> Response<Self, StopWorker> type Result = Response<Self, StopWorker>;
{
fn handle(&mut self, msg: StopWorker, ctx: &mut Context<Self>) -> Self::Result {
let num = self.settings.channels.get(); let num = self.settings.channels.get();
if num == 0 { if num == 0 {
info!("Shutting down http worker, 0 connections"); info!("Shutting down http worker, 0 connections");

View file

@ -26,16 +26,15 @@
//! # impl StreamHandler<ws::Message> for Ws {} //! # impl StreamHandler<ws::Message> for Ws {}
//! # //! #
//! impl Handler<ws::Message> for Ws { //! impl Handler<ws::Message> for Ws {
//! fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>) //! type Result = ();
//! -> Response<Self, ws::Message> //!
//! { //! fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext<Self>) {
//! match msg { //! match msg {
//! ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg), //! ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, &msg),
//! ws::Message::Text(text) => ws::WsWriter::text(ctx, &text), //! ws::Message::Text(text) => ws::WsWriter::text(ctx, &text),
//! ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin), //! ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin),
//! _ => (), //! _ => (),
//! } //! }
//! Self::empty()
//! } //! }
//! } //! }
//! # //! #
@ -94,7 +93,7 @@ pub fn start<A, S>(mut req: HttpRequest<S>, actor: A) -> Result<HttpResponse, Er
let stream = WsStream::new(req.payload_mut().readany()); let stream = WsStream::new(req.payload_mut().readany());
let mut ctx = HttpContext::new(req, actor); let mut ctx = HttpContext::new(req, actor);
ctx.add_stream(stream); ctx.add_message_stream(stream);
Ok(resp.body(ctx)?) Ok(resp.body(ctx)?)
} }