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

rename Server to ServerBuilder

This commit is contained in:
Nikolay Kim 2018-12-09 20:30:04 -08:00
parent 98a151db4f
commit cdd6904aa0
7 changed files with 83 additions and 42 deletions

View File

@ -51,6 +51,7 @@ cell = []
actix = "0.7.6" actix = "0.7.6"
actix-service = "0.1.1" actix-service = "0.1.1"
actix-codec = { path = "actix-codec" } actix-codec = { path = "actix-codec" }
actix-rt = { path = "actix-rt" }
log = "0.4" log = "0.4"
num_cpus = "1.0" num_cpus = "1.0"

View File

@ -5,7 +5,7 @@
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread; use std::{fmt, thread};
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::sync::oneshot::{channel, Sender}; use futures::sync::oneshot::{channel, Sender};
@ -23,9 +23,18 @@ thread_local!(
pub(crate) const COUNT: AtomicUsize = AtomicUsize::new(0); pub(crate) const COUNT: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
pub(crate) enum ArbiterCommand { pub(crate) enum ArbiterCommand {
Stop, Stop,
Execute(Box<Future<Item = (), Error = ()> + Send>),
}
impl fmt::Debug for ArbiterCommand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"),
ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"),
}
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -49,6 +58,14 @@ impl Arbiter {
arb arb
} }
/// Returns current arbiter's address
pub fn current() -> Arbiter {
ADDR.with(|cell| match *cell.borrow() {
Some(ref addr) => addr.clone(),
None => panic!("Arbiter is not running"),
})
}
/// Stop arbiter /// Stop arbiter
pub fn stop(&self) { pub fn stop(&self) {
let _ = self.0.unbounded_send(ArbiterCommand::Stop); let _ = self.0.unbounded_send(ArbiterCommand::Stop);
@ -113,7 +130,7 @@ impl Arbiter {
RUNNING.with(|cell| cell.set(false)); RUNNING.with(|cell| cell.set(false));
} }
/// Executes a future on the current thread. /// Spawn a future on the current thread.
pub fn spawn<F>(future: F) pub fn spawn<F>(future: F)
where where
F: Future<Item = (), Error = ()> + 'static, F: Future<Item = (), Error = ()> + 'static,
@ -135,6 +152,16 @@ impl Arbiter {
{ {
Arbiter::spawn(future::lazy(f)) Arbiter::spawn(future::lazy(f))
} }
/// Send a future on the arbiter's thread and spawn.
pub fn send<F>(&self, future: F)
where
F: Future<Item = (), Error = ()> + Send + 'static,
{
let _ = self
.0
.unbounded_send(ArbiterCommand::Execute(Box::new(future)));
}
} }
struct ArbiterController { struct ArbiterController {
@ -158,17 +185,22 @@ impl Future for ArbiterController {
type Error = (); type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.rx.poll() { loop {
Ok(Async::Ready(None)) | Err(_) => Ok(Async::Ready(())), match self.rx.poll() {
Ok(Async::Ready(Some(item))) => match item { Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())),
ArbiterCommand::Stop => { Ok(Async::Ready(Some(item))) => match item {
if let Some(stop) = self.stop.take() { ArbiterCommand::Stop => {
let _ = stop.send(0); if let Some(stop) = self.stop.take() {
}; let _ = stop.send(0);
Ok(Async::Ready(())) };
} return Ok(Async::Ready(()));
}, }
Ok(Async::NotReady) => Ok(Async::NotReady), ArbiterCommand::Execute(fut) => {
spawn(fut);
}
},
Ok(Async::NotReady) => return Ok(Async::NotReady),
}
} }
} }
} }

View File

@ -5,8 +5,23 @@ mod builder;
mod runtime; mod runtime;
mod system; mod system;
pub use self::arbiter::Arbiter;
pub use self::builder::{Builder, SystemRunner}; pub use self::builder::{Builder, SystemRunner};
pub use self::runtime::{Handle, Runtime}; pub use self::runtime::{Handle, Runtime};
pub use self::system::System; pub use self::system::System;
// pub use tokio_current_thread::spawn;
// pub use tokio_current_thread::TaskExecutor; /// Spawns a future on the current arbiter.
///
/// # Panics
///
/// This function panics if actix system is not running.
pub fn spawn<F>(f: F)
where
F: futures::Future<Item = (), Error = ()> + 'static,
{
if !System::is_set() {
panic!("System is not running");
}
Arbiter::spawn(f);
}

View File

@ -58,8 +58,7 @@ impl System {
} }
/// Set current running system. /// Set current running system.
#[doc(hidden)] pub(crate) fn is_set() -> bool {
pub(crate) fn _is_set() -> bool {
CURRENT.with(|cell| cell.borrow().is_some()) CURRENT.with(|cell| cell.borrow().is_some())
} }

View File

@ -1,15 +1,16 @@
use std::time::Duration; use std::time::Duration;
use std::{io, mem, net}; use std::{io, mem, net};
use actix_rt::Arbiter;
use futures::sync::{mpsc, mpsc::unbounded}; use futures::sync::{mpsc, mpsc::unbounded};
use futures::{Future, Sink, Stream}; use futures::{future::lazy, Future, Sink, Stream};
use log::{error, info}; use log::{error, info};
use net2::TcpBuilder; use net2::TcpBuilder;
use num_cpus; use num_cpus;
use actix::{ use actix::{
actors::signal, fut, msgs::Execute, Actor, ActorFuture, Addr, Arbiter, AsyncContext, actors::signal, fut, Actor, ActorFuture, Addr, AsyncContext, Context, Handler, Response,
Context, Handler, Response, StreamHandler, System, WrapFuture, StreamHandler, System, WrapFuture,
}; };
use super::accept::{AcceptLoop, AcceptNotify, Command}; use super::accept::{AcceptLoop, AcceptNotify, Command};
@ -24,7 +25,9 @@ pub(crate) enum ServerCommand {
} }
/// Server /// Server
pub struct Server { pub struct Server {}
pub struct ServerBuilder {
threads: usize, threads: usize,
token: Token, token: Token,
workers: Vec<(usize, WorkerClient)>, workers: Vec<(usize, WorkerClient)>,
@ -37,16 +40,10 @@ pub struct Server {
no_signals: bool, no_signals: bool,
} }
impl Default for Server { impl ServerBuilder {
fn default() -> Self {
Self::new()
}
}
impl Server {
/// Create new Server instance /// Create new Server instance
pub fn new() -> Server { pub fn new() -> Server {
Server { ServerBuilder {
threads: num_cpus::get(), threads: num_cpus::get(),
token: Token(0), token: Token(0),
workers: Vec::new(), workers: Vec::new(),
@ -227,7 +224,7 @@ impl Server {
} }
/// Starts Server Actor and returns its address /// Starts Server Actor and returns its address
pub fn start(mut self) -> Addr<Server> { pub fn start(mut self) -> Server {
if self.sockets.is_empty() { if self.sockets.is_empty() {
panic!("Service should have at least one bound socket"); panic!("Service should have at least one bound socket");
} else { } else {
@ -284,7 +281,7 @@ impl Server {
let services: Vec<Box<InternalServiceFactory>> = let services: Vec<Box<InternalServiceFactory>> =
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().send(lazy(move || {
Worker::start(rx1, rx2, services, avail, timeout); Worker::start(rx1, rx2, services, avail, timeout);
Ok::<_, ()>(()) Ok::<_, ()>(())
})); }));

View File

@ -3,13 +3,13 @@
use actix::Message; use actix::Message;
mod accept; mod accept;
mod builder;
mod config; mod config;
mod server;
mod services; mod services;
mod worker; mod worker;
pub use self::builder::ServerBuilder;
pub use self::config::{ServiceConfig, ServiceRuntime}; pub use self::config::{ServiceConfig, ServiceRuntime};
pub use self::server::Server;
pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory}; pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory};
/// Pause accepting incoming connections /// Pause accepting incoming connections

View File

@ -2,16 +2,13 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::{mem, net, time}; use std::{mem, net, time};
use actix_rt::{spawn, Arbiter};
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 log::{error, info, trace};
use tokio_current_thread::spawn;
use tokio_timer::{sleep, Delay}; use tokio_timer::{sleep, Delay};
use actix::msgs::StopArbiter;
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;
@ -26,7 +23,7 @@ pub(crate) struct StopCommand {
result: oneshot::Sender<bool>, result: oneshot::Sender<bool>,
} }
#[derive(Debug, Message)] #[derive(Debug)]
pub(crate) struct Conn { pub(crate) struct Conn {
pub io: net::TcpStream, pub io: net::TcpStream,
pub token: Token, pub token: Token,
@ -167,7 +164,7 @@ impl Worker {
future::join_all(fut) future::join_all(fut)
.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().stop();
}) })
.and_then(move |services| { .and_then(move |services| {
for item in services { for item in services {
@ -365,7 +362,7 @@ impl Future for Worker {
let num = num_connections(); let num = num_connections();
if num == 0 { if num == 0 {
let _ = tx.send(true); let _ = tx.send(true);
Arbiter::current().do_send(StopArbiter(0)); Arbiter::current().stop();
return Ok(Async::Ready(())); return Ok(Async::Ready(()));
} }
@ -375,7 +372,7 @@ impl Future for Worker {
Async::Ready(_) => { Async::Ready(_) => {
self.shutdown(true); self.shutdown(true);
let _ = tx.send(false); let _ = tx.send(false);
Arbiter::current().do_send(StopArbiter(0)); Arbiter::current().stop();
return Ok(Async::Ready(())); return Ok(Async::Ready(()));
} }
} }