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
use std;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio_service::Service as TokioService;
use crate::jsonrpc::futures::sync::{mpsc, oneshot};
use crate::jsonrpc::futures::{future, Future, Sink, Stream};
use crate::jsonrpc::{middleware, MetaIoHandler, Metadata, Middleware};
use crate::server_utils::{codecs, reactor, tokio, tokio_codec::Framed, SuspendableStream};
use crate::dispatch::{Dispatcher, PeerMessageQueue, SenderChannels};
use crate::meta::{MetaExtractor, NoopExtractor, RequestContext};
use crate::service::Service;
pub struct ServerBuilder<M: Metadata = (), S: Middleware<M> = middleware::Noop> {
executor: reactor::UninitializedExecutor,
handler: Arc<MetaIoHandler<M, S>>,
meta_extractor: Arc<dyn MetaExtractor<M>>,
channels: Arc<SenderChannels>,
incoming_separator: codecs::Separator,
outgoing_separator: codecs::Separator,
}
impl<M: Metadata + Default, S: Middleware<M> + 'static> ServerBuilder<M, S> {
pub fn new<T>(handler: T) -> Self
where
T: Into<MetaIoHandler<M, S>>,
{
Self::with_meta_extractor(handler, NoopExtractor)
}
}
impl<M: Metadata, S: Middleware<M> + 'static> ServerBuilder<M, S> {
pub fn with_meta_extractor<T, E>(handler: T, extractor: E) -> Self
where
T: Into<MetaIoHandler<M, S>>,
E: MetaExtractor<M> + 'static,
{
ServerBuilder {
executor: reactor::UninitializedExecutor::Unspawned,
handler: Arc::new(handler.into()),
meta_extractor: Arc::new(extractor),
channels: Default::default(),
incoming_separator: Default::default(),
outgoing_separator: Default::default(),
}
}
pub fn event_loop_executor(mut self, handle: tokio::runtime::TaskExecutor) -> Self {
self.executor = reactor::UninitializedExecutor::Shared(handle);
self
}
pub fn session_meta_extractor<T: MetaExtractor<M> + 'static>(mut self, meta_extractor: T) -> Self {
self.meta_extractor = Arc::new(meta_extractor);
self
}
pub fn request_separators(mut self, incoming: codecs::Separator, outgoing: codecs::Separator) -> Self {
self.incoming_separator = incoming;
self.outgoing_separator = outgoing;
self
}
pub fn start(self, addr: &SocketAddr) -> std::io::Result<Server> {
let meta_extractor = self.meta_extractor.clone();
let rpc_handler = self.handler.clone();
let channels = self.channels.clone();
let incoming_separator = self.incoming_separator;
let outgoing_separator = self.outgoing_separator;
let address = addr.to_owned();
let (tx, rx) = std::sync::mpsc::channel();
let (stop_tx, stop_rx) = oneshot::channel();
let executor = self.executor.initialize()?;
executor.spawn(future::lazy(move || {
let start = move || {
let listener = tokio::net::TcpListener::bind(&address)?;
let connections = SuspendableStream::new(listener.incoming());
let server = connections.map(move |socket| {
let peer_addr = match socket.peer_addr() {
Ok(addr) => addr,
Err(e) => {
warn!(target: "tcp", "Unable to determine socket peer address, ignoring connection {}", e);
return future::Either::A(future::ok(()));
}
};
trace!(target: "tcp", "Accepted incoming connection from {}", &peer_addr);
let (sender, receiver) = mpsc::channel(65536);
let context = RequestContext {
peer_addr,
sender: sender.clone(),
};
let meta = meta_extractor.extract(&context);
let service = Service::new(peer_addr, rpc_handler.clone(), meta);
let (writer, reader) = Framed::new(
socket,
codecs::StreamCodec::new(incoming_separator.clone(), outgoing_separator.clone()),
)
.split();
let responses = reader.and_then(move |req| {
service.call(req).then(|response| match response {
Err(e) => {
warn!(target: "tcp", "Error while processing request: {:?}", e);
future::ok(String::new())
}
Ok(None) => {
trace!(target: "tcp", "JSON RPC request produced no response");
future::ok(String::new())
}
Ok(Some(response_data)) => {
trace!(target: "tcp", "Sent response: {}", &response_data);
future::ok(response_data)
}
})
});
let peer_message_queue = {
let mut channels = channels.lock();
channels.insert(peer_addr, sender.clone());
PeerMessageQueue::new(responses, receiver, peer_addr)
};
let shared_channels = channels.clone();
let writer = writer.send_all(peer_message_queue).then(move |_| {
trace!(target: "tcp", "Peer {}: service finished", peer_addr);
let mut channels = shared_channels.lock();
channels.remove(&peer_addr);
Ok(())
});
future::Either::B(writer)
});
Ok(server)
};
let stop = stop_rx.map_err(|_| ());
match start() {
Ok(server) => {
tx.send(Ok(())).expect("Rx is blocking parent thread.");
future::Either::A(
server
.buffer_unordered(1024)
.for_each(|_| Ok(()))
.select(stop)
.map(|_| ())
.map_err(|(e, _)| {
error!("Error while executing the server: {:?}", e);
}),
)
}
Err(e) => {
tx.send(Err(e)).expect("Rx is blocking parent thread.");
future::Either::B(stop.map_err(|e| {
error!("Error while executing the server: {:?}", e);
}))
}
}
}));
let res = rx.recv().expect("Response is always sent before tx is dropped.");
res.map(|_| Server {
executor: Some(executor),
stop: Some(stop_tx),
})
}
pub fn dispatcher(&self) -> Dispatcher {
Dispatcher::new(self.channels.clone())
}
}
pub struct Server {
executor: Option<reactor::Executor>,
stop: Option<oneshot::Sender<()>>,
}
impl Server {
pub fn close(mut self) {
let _ = self.stop.take().map(|sg| sg.send(()));
self.executor.take().unwrap().close();
}
pub fn wait(mut self) {
self.executor.take().unwrap().wait();
}
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.stop.take().map(|sg| sg.send(()));
if let Some(executor) = self.executor.take() {
executor.close()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_is_send_and_sync() {
fn is_send_and_sync<T: Send + Sync>() {}
is_send_and_sync::<Server>();
}
}