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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use std::fmt;
use std::io;
use std::net::{SocketAddr, TcpListener as StdTcpListener};
use futures::{Future, Map};
use futures::stream::{Stream};
use futures::sync::oneshot;
use tokio::io::Io;
use tokio::net::TcpListener;
use tokio::reactor::{Core, Handle};
use tokio_proto::BindServer;
use tokio_proto::streaming::Message;
use tokio_proto::streaming::pipeline::ServerProto;
pub use tokio_service::{NewService, Service};
pub use self::accept::Accept;
pub use self::request::Request;
pub use self::response::Response;
use http;
mod request;
mod response;
type HttpIncoming = ::tokio::net::Incoming;
#[derive(Debug)]
pub struct Server<A> {
accepter: A,
addr: SocketAddr,
keep_alive: bool,
}
impl<A: Accept> Server<A> {
pub fn new(accepter: A, addr: SocketAddr) -> Server<A> {
Server {
accepter: accepter,
addr: addr,
keep_alive: true,
}
}
pub fn keep_alive(mut self, val: bool) -> Server<A> {
self.keep_alive = val;
self
}
}
impl Server<HttpIncoming> {
pub fn http(addr: &SocketAddr, handle: &Handle) -> ::Result<Server<HttpIncoming>> {
let listener = try!(StdTcpListener::bind(addr));
let addr = try!(listener.local_addr());
let listener = try!(TcpListener::from_listener(listener, &addr, handle));
Ok(Server::new(listener.incoming(), addr))
}
}
impl<A: Accept> Server<A> {
pub fn handle<H>(self, factory: H, handle: &Handle) -> ::Result<SocketAddr>
where H: NewService<Request=Request, Response=Response, Error=::Error> + Send + 'static {
let binder = HttpServer {
keep_alive: self.keep_alive,
};
let inner_handle = handle.clone();
handle.spawn(self.accepter.accept().for_each(move |(socket, remote_addr)| {
let service = HttpService {
inner: try!(factory.new_service()),
remote_addr: remote_addr,
};
binder.bind_server(&inner_handle, socket, service);
Ok(())
}).map_err(|e| {
error!("listener io error: {:?}", e);
()
}));
Ok(self.addr)
}
}
impl Server<()> {
pub fn standalone<F>(closure: F) -> ::Result<(Listening, ServerLoop)>
where F: FnOnce(&Handle) -> ::Result<SocketAddr> {
let core = try!(Core::new());
let handle = core.handle();
let addr = try!(closure(&handle));
let (shutdown_tx, shutdown_rx) = oneshot::channel();
Ok((
Listening {
addr: addr,
shutdown: shutdown_tx,
},
ServerLoop {
inner: Some((core, shutdown_rx)),
}
))
}
}
pub struct ServerLoop {
inner: Option<(Core, oneshot::Receiver<()>)>,
}
impl fmt::Debug for ServerLoop {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("ServerLoop")
}
}
impl ServerLoop {
pub fn run(self) {
trace!("ServerLoop::run()");
}
}
impl Drop for ServerLoop {
fn drop(&mut self) {
self.inner.take().map(|(mut loop_, shutdown)| {
debug!("ServerLoop::drop running");
let _ = loop_.run(shutdown.or_else(|_dropped| ::futures::future::empty::<(), oneshot::Canceled>()));
debug!("Server closed");
});
}
}
pub struct Listening {
addr: SocketAddr,
shutdown: ::futures::sync::oneshot::Sender<()>,
}
impl fmt::Debug for Listening {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Listening")
.field("addr", &self.addr)
.finish()
}
}
impl fmt::Display for Listening {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.addr, f)
}
}
impl Listening {
pub fn addr(&self) -> &SocketAddr {
&self.addr
}
pub fn close(self) {
debug!("closing server {}", self);
self.shutdown.complete(());
}
}
struct HttpServer {
keep_alive: bool,
}
impl<T: Io + 'static> ServerProto<T> for HttpServer {
type Request = http::RequestHead;
type RequestBody = http::Chunk;
type Response = ResponseHead;
type ResponseBody = http::Chunk;
type Error = ::Error;
type Transport = http::Conn<T, http::ServerTransaction>;
type BindTransport = io::Result<http::Conn<T, http::ServerTransaction>>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
let ka = if self.keep_alive {
http::KA::Busy
} else {
http::KA::Disabled
};
Ok(http::Conn::new(io, ka))
}
}
struct HttpService<T> {
inner: T,
remote_addr: SocketAddr,
}
fn map_response_to_message(res: Response) -> Message<ResponseHead, http::TokioBody> {
let (head, body) = response::split(res);
if let Some(body) = body {
Message::WithBody(head, body.into())
} else {
Message::WithoutBody(head)
}
}
type ResponseHead = http::MessageHead<::StatusCode>;
impl<T> Service for HttpService<T>
where T: Service<Request=Request, Response=Response, Error=::Error>,
{
type Request = Message<http::RequestHead, http::TokioBody>;
type Response = Message<ResponseHead, http::TokioBody>;
type Error = ::Error;
type Future = Map<T::Future, fn(Response) -> Message<ResponseHead, http::TokioBody>>;
fn call(&mut self, message: Self::Request) -> Self::Future {
let (head, body) = match message {
Message::WithoutBody(head) => (head, http::Body::empty()),
Message::WithBody(head, body) => (head, body.into()),
};
let req = request::new(self.remote_addr, head, body);
self.inner.call(req).map(map_response_to_message)
}
}
mod accept {
use std::io;
use std::net::SocketAddr;
use futures::{Stream, Poll};
use tokio::io::Io;
pub trait Accept: Stream<Error=io::Error> {
#[doc(hidden)]
type Output: Io + 'static;
#[doc(hidden)]
type Stream: Stream<Item=(Self::Output, SocketAddr), Error=io::Error> + 'static;
#[doc(hidden)]
fn accept(self) -> Accepter<Self::Stream, Self::Output>
where Self: Sized;
}
#[allow(missing_debug_implementations)]
pub struct Accepter<T: Stream<Item=(I, SocketAddr), Error=io::Error> + 'static, I: Io + 'static>(T, ::std::marker::PhantomData<I>);
impl<T, I> Stream for Accepter<T, I>
where T: Stream<Item=(I, SocketAddr), Error=io::Error>,
I: Io + 'static,
{
type Item = T::Item;
type Error = io::Error;
#[inline]
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.0.poll()
}
}
impl<T, I> Accept for T
where T: Stream<Item=(I, SocketAddr), Error=io::Error> + 'static,
I: Io + 'static,
{
type Output = I;
type Stream = T;
fn accept(self) -> Accepter<Self, I> {
Accepter(self, ::std::marker::PhantomData)
}
}
}