Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for graceful exit from loop using shutdown flag #118

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ use std::fs::File;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use std::borrow::Borrow;
Expand All @@ -69,6 +71,7 @@ pub struct Server {
handler: Handler,
timeout: Option<Duration>,
static_directory: Option<PathBuf>,
pub shutdown: Arc<AtomicBool>,
}

impl fmt::Debug for Server {
Expand Down Expand Up @@ -117,6 +120,7 @@ impl Server {
handler: Box::new(handler),
timeout: None,
static_directory: Some(PathBuf::from("public")),
shutdown: Arc::new(AtomicBool::new(false)),
}
}

Expand Down Expand Up @@ -157,6 +161,7 @@ impl Server {
handler: Box::new(handler),
timeout: Some(timeout),
static_directory: Some(PathBuf::from("public")),
shutdown: Arc::new(AtomicBool::new(false)),
}
}

Expand Down Expand Up @@ -207,7 +212,7 @@ impl Server {
/// server.listen("127.0.0.1", "7979");
/// }
/// ```
pub fn listen(&self, host: &str, port: &str) -> ! {
pub fn listen(&self, host: &str, port: &str) {
let listener =
TcpListener::bind(format!("{}:{}", host, port)).expect("Error starting the server.");

Expand Down Expand Up @@ -246,13 +251,17 @@ impl Server {
/// server.listen_on_socket(listener);
/// }
/// ```
pub fn listen_on_socket(&self, listener: TcpListener) -> ! {
pub fn listen_on_socket(&self, listener: TcpListener) {
const READ_TIMEOUT_MS: u64 = 20;
let num_threads = self.pool_size();
let mut pool = Pool::new(num_threads);
let mut incoming = listener.incoming();

loop {
// check if shutdown received
if self.shutdown.load(Ordering::SeqCst) {
return;
}
// Incoming is an endless iterator, so it's okay to unwrap on it.
let stream = incoming.next().unwrap();
let stream = stream.expect("Error handling TCP stream.");
Expand Down Expand Up @@ -341,7 +350,7 @@ impl Server {
fn handle_connection(&self, mut stream: TcpStream) -> Result<(), Error> {
let request = match request::read(&mut stream, self.timeout) {
Err(Error::ConnectionClosed) | Err(Error::Timeout) | Err(Error::HttpParse(_)) => {
return Ok(())
return Ok(());
}

Err(Error::RequestTooLarge) => {
Expand Down
6 changes: 4 additions & 2 deletions src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ pub fn try_parse_request(buffer: Vec<u8>) -> Result<ParseResult, httparse::Error
let method = RequestMethodIndices(method.0, method.1);

(r, method, proto, n)
}).map(|(r, method, proto, n)| {
})
.map(|(r, method, proto, n)| {
let headers = r
.headers
.iter()
Expand All @@ -109,7 +110,8 @@ pub fn try_parse_request(buffer: Vec<u8>) -> Result<ParseResult, httparse::Error
value: slice_indices(&*buffer, value),
}
},
).collect::<Vec<_>>();
)
.collect::<Vec<_>>();
(method, proto, headers, n)
})
};
Expand Down