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
use futures::{Async, Future, Poll, Stream};
use futures::task::{self, Task};
use std::io;
use std::net::SocketAddr;
use hyper::Chunk;
use hyper::server::Http;
use tokio_core::reactor::Core;
use tokio_core::net::{TcpListener, TcpStream};
use routing::Router;
use std::sync::{Arc, Mutex};
use futures::prelude::{async, await};
use std::thread;
use num_cpus;
use proto::{ArcHandler, ArcService};
use super::rootservice::RootService;

// A wrapper around a closure i can run forever on an event loop.
struct ReactorFuture<F>
where
	F: Fn(),
{
	pub handler: F,
}

// The future never completes.
// This is because it takes care of dispatching connected clients on the event
// loop.
impl<F> Future for ReactorFuture<F>
where
	F: Fn(),
{
	type Item = ();
	type Error = ();

	fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
		(self.handler)();

		Ok(Async::NotReady)
	}
}

type ReactorAlias = Arc<Mutex<Reactor>>;

// Shared Mutable object to connected clients
// This struct is only shared by the main thread, and the another worker thread
// at any point in time. As new clients are connected, The main thread will
// lock the reactor and push the clients to `peers`. then the future running in
// the thread is notified that there are new clients that need to be handled.
struct Reactor {
	pub(crate) peers: Vec<(TcpStream, SocketAddr)>,
	pub(crate) taskHandle: Option<Task>,
}

// Creates a thread safe Mutable reactor.
impl Reactor {
	pub fn new() -> ReactorAlias {
		Arc::new(Mutex::new(Reactor {
			peers: Vec::new(),
			taskHandle: None,
		}))
	}
}

/// The main server, the ArcReactor is where you mount your routes, middlewares and initiate the
/// server.
///
/// #Examples
///
/// ```rust,ignore
/// extern crate arc_reactor;
/// use arc_reactor::ArcReactor;
///
/// fn main() {
///   ArcReactor::new().routes(..).port(1234).initiate().unwrap()
/// }
/// ```
pub struct ArcReactor {
	port: i16,
	handler: Option<ArcHandler>,
}

impl ArcReactor {
	/// Creates an instance of the server.
	/// with a default port of `8080`
	/// and *No* routes. Note that calling `initiate` on an `ArcReactor` without routes
	/// will cause your program to panic.
	pub fn new() -> ArcReactor {
		ArcReactor {
			port: 8080,
			handler: None,
		}
	}

	/// sets the port for the server to listen on and returns the instance.
	pub fn port(mut self, port: i16) -> Self {
		self.port = port;

		self
	}

//	/// Mount a global MiddleWare on the server, Note that it takes a type
//	/// [`MiddleWare<Request>`](trait.MiddleWare.html#impl-MiddleWare<Request>) this is because, the
//	/// middleware(s) supplied here are run before any other middleware or route handlers.
//	///
//	/// read the [`MiddleWare<T>`](trait.MiddleWare.html) documentation to understand how middlewares
//	/// work.
//	pub fn before(mut self, before: Box<MiddleWare<Request>>) -> Self {
//		if let Some(ref mut archandler) = self.handler {
//			archandler.before = Some(Arc::new(before));
//		}
//
//		self
//	}

//	/// Mount a global MiddleWare on the server, Note that it takes a type
//	/// [`MiddleWare<Response>`](trait.MiddleWare.html#impl-MiddleWare<Response>) this is because,
//	/// the middleware(s) supplied here are run before any other middleware or route handlers.
//	///
//	/// read the [`MiddleWare<T>`](trait.MiddleWare.html) documentation to understand how middlewares
//	/// work.
//	pub fn after(mut self, after: Box<MiddleWare<Response>>) -> Self {
//		if let Some(ref mut archandler) = self.handler {
//			archandler.after = Some(Arc::new(after));
//		}
//
//		self
//	}

	/// mount the Router on the ArcReactor
	pub fn routes(mut self, routes: Router) -> Self {
		let routes = Arc::new(box routes as Box<ArcService>);
		if let Some(ref mut archandler) = self.handler {
			archandler.handler = routes;
		} else {
			self.handler = Some(ArcHandler {
				before: None,
				after: None,
				handler: routes,
			});
		}

		self
	}

	/// Binds the listener and blocks the main thread while listening for incoming connections.
	///
	/// # Panics
	///
	/// Calling this function will panic if: no routes are supplied, or it cannot
	/// start the main event loop.

	#[must_use]
	pub fn initiate(self) -> io::Result<()> {
		println!("[arc-reactor]: Spawning threads!");
		let reactors = spawn(self.handler.expect("This thing needs routes to work!"))?;
		println!(
			"[arc-reactor]: Starting main event loop!\n[arc-reactor]: Spawned {} threads",
			reactors.len()
		);
		let mut core = Core::new()?;

		println!("[arc-reactor]: Started Main event loop!");
		let handle = core.handle();

		let addr = format!("0.0.0.0:{}", self.port).parse().unwrap();
		println!("[arc-reactor]: Binding to port {}", self.port);
		let listener = match TcpListener::bind(&addr, &handle) {
			Ok(listener) => listener,
			Err(e) => {
				eprintln!(
					"[arc-reactor]: Whoops! something else is running on port {}, {}",
					&self.port, e
				);
				return Err(e);
			}
		};

		let mut counter = 0;

		println!("[arc-reactor]: Running Main Event loop");
		core.run(listener.incoming().for_each(move |(socket, peerIp)| {
			let mut reactor = reactors[counter].lock().unwrap();
			reactor.peers.push((socket, peerIp));

			if let Some(ref task) = reactor.taskHandle {
				task.notify();
			}

			counter += 1;
			if counter == reactors.len() {
				counter = 0
			}
			Ok(())
		}))?;

		Ok(())
	}
}

fn spawn(RouteService: ArcHandler) -> io::Result<Vec<ReactorAlias>> {
	let mut reactors = Vec::new();
	let routeService = Arc::new(RouteService);

	for _ in 0..num_cpus::get() * 2 {
		let reactor = Reactor::new();
		reactors.push(reactor.clone());
		let routeService = routeService.clone();

		thread::spawn(move || {
			let mut core = Core::new().expect("Could not start event loop");
			let handle = core.handle();
			let http = Http::new();

			let handler = || {
				let mut reactor = reactor.lock().unwrap();
				for (socket, remote_ip) in reactor.peers.drain(..) {
					let service = routeService.clone();
					let future = socketHandler(
						socket,
						http.clone(),
						RootService {
							service,
							remote_ip,
							handle: handle.clone(),
						},
					);
					handle.spawn(future);
				}
				reactor.taskHandle = Some(task::current());
			};

			let future = ReactorFuture { handler };

			core.run(future).expect("Error running reactor core!");
		});
	}

	Ok(reactors)
}

#[async]
fn socketHandler(
	stream: TcpStream,
	http: Http<Chunk>,
	serviceHandler: RootService,
) -> Result<(), ()> {
	let _opaque = await!(http.serve_connection(stream, serviceHandler));
	Ok(())
}