This repository has been archived by the owner on Sep 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
tcp_server.rs
181 lines (159 loc) · 5.47 KB
/
tcp_server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use std::io;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread;
use BindServer;
use futures::stream::Stream;
use net2;
use tokio_core::net::{TcpStream, TcpListener};
use tokio_core::reactor::{Core, Handle};
use tokio_service::NewService;
// TODO: Add more options, e.g.:
// - max concurrent requests
// - request timeout
// - read timeout
// - write timeout
// - max idle time
// - max lifetime
/// A builder for TCP servers.
///
/// Setting up a server needs, at minimum:
///
/// - A server protocol implementation
/// - An address
/// - A service to provide
///
/// In addition to those basics, the builder provides some additional
/// configuration, which is expected to grow over time.
///
/// See the crate docs for an example.
pub struct TcpServer<Kind, P> {
_kind: PhantomData<Kind>,
proto: Arc<P>,
threads: usize,
addr: SocketAddr,
}
impl<Kind, P> TcpServer<Kind, P> where
P: BindServer<Kind, TcpStream> + Send + Sync + 'static
{
/// Starts building a server for the given protocol and address, with
/// default configuration.
///
/// Generally, a protocol is implemented *not* by implementing the
/// `BindServer` trait directly, but instead by implementing one of the
/// protocol traits:
///
/// - `pipeline::ServerProto`
/// - `multiplex::ServerProto`
/// - `streaming::pipeline::ServerProto`
/// - `streaming::multiplex::ServerProto`
///
/// See the crate documentation for more details on those traits.
pub fn new(protocol: P, addr: SocketAddr) -> TcpServer<Kind, P> {
TcpServer {
_kind: PhantomData,
proto: Arc::new(protocol),
threads: 1,
addr: addr,
}
}
/// Set the address for the server.
pub fn addr(&mut self, addr: SocketAddr) {
self.addr = addr;
}
/// Set the number of threads running simultaneous event loops (Unix only).
pub fn threads(&mut self, threads: usize) {
assert!(threads > 0);
if cfg!(unix) {
self.threads = threads;
}
}
/// Start up the server, providing the given service on it.
///
/// This method will block the current thread until the server is shut down.
pub fn serve<S>(&self, new_service: S) where
S: NewService<Request = P::ServiceRequest,
Response = P::ServiceResponse,
Error = P::ServiceError> + Send + Sync + 'static,
{
let new_service = Arc::new(new_service);
self.with_handle(move |_| new_service.clone())
}
/// Start up the server, providing the given service on it, and providing
/// access to the event loop handle.
///
/// The `new_service` argument is a closure that is given an event loop
/// handle, and produces a value implementing `NewService`. That value is in
/// turned used to make a new service instance for each incoming connection.
///
/// This method will block the current thread until the server is shut down.
pub fn with_handle<F, S>(&self, new_service: F) where
F: Fn(&Handle) -> S + Send + Sync + 'static,
S: NewService<Request = P::ServiceRequest,
Response = P::ServiceResponse,
Error = P::ServiceError> + Send + Sync + 'static,
{
let proto = self.proto.clone();
let new_service = Arc::new(new_service);
let addr = self.addr;
let workers = self.threads;
let threads = (0..self.threads - 1).map(|i| {
let proto = proto.clone();
let new_service = new_service.clone();
thread::Builder::new().name(format!("worker{}", i)).spawn(move || {
serve(proto, addr, workers, &*new_service)
}).unwrap()
}).collect::<Vec<_>>();
serve(proto, addr, workers, &*new_service);
for thread in threads {
thread.join().unwrap();
}
}
}
fn serve<P, Kind, F, S>(binder: Arc<P>, addr: SocketAddr, workers: usize, new_service: &F)
where P: BindServer<Kind, TcpStream>,
F: Fn(&Handle) -> S,
S: NewService<Request = P::ServiceRequest,
Response = P::ServiceResponse,
Error = P::ServiceError> + 'static,
{
let mut core = Core::new().unwrap();
let handle = core.handle();
let new_service = new_service(&handle);
let listener = listener(&addr, workers, &handle).unwrap();
let server = listener.incoming().for_each(move |(socket, _)| {
// Create the service
let service = try!(new_service.new_service());
// Bind it!
binder.bind_server(&handle, socket, service);
Ok(())
});
core.run(server).unwrap();
}
fn listener(addr: &SocketAddr,
workers: usize,
handle: &Handle) -> io::Result<TcpListener> {
let listener = match *addr {
SocketAddr::V4(_) => try!(net2::TcpBuilder::new_v4()),
SocketAddr::V6(_) => try!(net2::TcpBuilder::new_v6()),
};
try!(configure_tcp(workers, &listener));
try!(listener.reuse_address(true));
try!(listener.bind(addr));
listener.listen(1024).and_then(|l| {
TcpListener::from_listener(l, addr, handle)
})
}
#[cfg(unix)]
fn configure_tcp(workers: usize, tcp: &net2::TcpBuilder) -> io::Result<()> {
use net2::unix::*;
if workers > 1 {
try!(tcp.reuse_port(true));
}
Ok(())
}
#[cfg(windows)]
fn configure_tcp(workers: usize, _tcp: &net2::TcpBuilder) -> io::Result<()> {
Ok(())
}