2017-01-25 18:51:41 +01:00
|
|
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
|
2016-02-05 13:40:41 +01:00
|
|
|
// This file is part of Parity.
|
|
|
|
|
|
|
|
// Parity is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
|
|
|
// Parity is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2016-10-20 14:49:12 +02:00
|
|
|
use std::sync::{Arc, Weak};
|
2016-01-12 17:33:40 +01:00
|
|
|
use std::thread::{self, JoinHandle};
|
2016-01-21 16:48:37 +01:00
|
|
|
use std::collections::HashMap;
|
2016-01-12 17:33:40 +01:00
|
|
|
use mio::*;
|
2016-10-30 09:56:34 +01:00
|
|
|
use mio::timer::{Timeout};
|
|
|
|
use mio::deprecated::{EventLoop, Handler, Sender, EventLoopBuilder};
|
2016-06-17 12:58:28 +02:00
|
|
|
use crossbeam::sync::chase_lev;
|
|
|
|
use slab::Slab;
|
2016-08-05 10:32:04 +02:00
|
|
|
use {IoError, IoHandler};
|
|
|
|
use worker::{Worker, Work, WorkType};
|
2016-10-30 09:56:34 +01:00
|
|
|
use parking_lot::{RwLock, Mutex};
|
2016-07-27 11:39:24 +02:00
|
|
|
use std::sync::{Condvar as SCondvar, Mutex as SMutex};
|
2016-10-30 09:56:34 +01:00
|
|
|
use std::time::Duration;
|
2016-07-13 19:59:59 +02:00
|
|
|
|
2016-01-22 00:11:19 +01:00
|
|
|
/// Timer ID
|
2016-01-12 17:33:40 +01:00
|
|
|
pub type TimerToken = usize;
|
2016-01-22 00:11:19 +01:00
|
|
|
/// Timer ID
|
2016-01-12 17:33:40 +01:00
|
|
|
pub type StreamToken = usize;
|
2016-01-22 00:11:19 +01:00
|
|
|
/// IO Hadndler ID
|
2016-01-21 16:48:37 +01:00
|
|
|
pub type HandlerId = usize;
|
2016-01-12 17:33:40 +01:00
|
|
|
|
2016-01-22 00:11:19 +01:00
|
|
|
/// Maximum number of tokens a handler can use
|
2016-01-21 16:48:37 +01:00
|
|
|
pub const TOKENS_PER_HANDLER: usize = 16384;
|
2016-06-17 12:58:28 +02:00
|
|
|
const MAX_HANDLERS: usize = 8;
|
|
|
|
|
2016-01-12 17:33:40 +01:00
|
|
|
/// Messages used to communicate with the event loop from other threads.
|
2016-01-21 16:48:37 +01:00
|
|
|
#[derive(Clone)]
|
2018-05-09 08:49:34 +02:00
|
|
|
pub enum IoMessage<Message> where Message: Send + Sized {
|
2016-01-12 17:33:40 +01:00
|
|
|
/// Shutdown the event loop
|
|
|
|
Shutdown,
|
|
|
|
/// Register a new protocol handler.
|
|
|
|
AddHandler {
|
2016-01-21 16:48:37 +01:00
|
|
|
handler: Arc<IoHandler<Message>+Send>,
|
|
|
|
},
|
2016-06-17 12:58:28 +02:00
|
|
|
RemoveHandler {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
},
|
2016-01-21 16:48:37 +01:00
|
|
|
AddTimer {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
token: TimerToken,
|
2018-04-14 21:35:58 +02:00
|
|
|
delay: Duration,
|
2016-09-01 14:12:26 +02:00
|
|
|
once: bool,
|
2016-01-21 16:48:37 +01:00
|
|
|
},
|
|
|
|
RemoveTimer {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
token: TimerToken,
|
|
|
|
},
|
|
|
|
RegisterStream {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
token: StreamToken,
|
|
|
|
},
|
2016-01-22 18:13:59 +01:00
|
|
|
DeregisterStream {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
token: StreamToken,
|
|
|
|
},
|
2016-01-21 16:48:37 +01:00
|
|
|
UpdateStreamRegistration {
|
|
|
|
handler_id: HandlerId,
|
|
|
|
token: StreamToken,
|
2016-01-12 17:33:40 +01:00
|
|
|
},
|
|
|
|
/// Broadcast a message across all protocol handlers.
|
2018-05-09 08:49:34 +02:00
|
|
|
UserMessage(Arc<Message>)
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// IO access point. This is passed to all IO handlers and provides an interface to the IO subsystem.
|
2018-05-09 08:49:34 +02:00
|
|
|
pub struct IoContext<Message> where Message: Send + Sync + 'static {
|
2016-01-22 00:11:19 +01:00
|
|
|
channel: IoChannel<Message>,
|
|
|
|
handler: HandlerId,
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> IoContext<Message> where Message: Send + Sync + 'static {
|
2016-01-12 17:33:40 +01:00
|
|
|
/// Create a new IO access point. Takes references to all the data that can be updated within the IO handler.
|
2016-01-21 16:48:37 +01:00
|
|
|
pub fn new(channel: IoChannel<Message>, handler: HandlerId) -> IoContext<Message> {
|
2016-01-12 17:33:40 +01:00
|
|
|
IoContext {
|
2016-01-21 16:48:37 +01:00
|
|
|
handler: handler,
|
|
|
|
channel: channel,
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-01 14:12:26 +02:00
|
|
|
/// Register a new recurring IO timer. 'IoHandler::timeout' will be called with the token.
|
2018-04-14 21:35:58 +02:00
|
|
|
pub fn register_timer(&self, token: TimerToken, delay: Duration) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::AddTimer {
|
2018-04-14 21:35:58 +02:00
|
|
|
token,
|
|
|
|
delay,
|
2016-01-21 16:48:37 +01:00
|
|
|
handler_id: self.handler,
|
2016-09-01 14:12:26 +02:00
|
|
|
once: false,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-09-01 14:12:26 +02:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Register a new IO timer once. 'IoHandler::timeout' will be called with the token.
|
2018-04-14 21:35:58 +02:00
|
|
|
pub fn register_timer_once(&self, token: TimerToken, delay: Duration) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::AddTimer {
|
2018-04-14 21:35:58 +02:00
|
|
|
token,
|
|
|
|
delay,
|
2016-09-01 14:12:26 +02:00
|
|
|
handler_id: self.handler,
|
|
|
|
once: true,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-21 16:48:37 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Delete a timer.
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn clear_timer(&self, token: TimerToken) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::RemoveTimer {
|
2016-01-21 16:48:37 +01:00
|
|
|
token: token,
|
|
|
|
handler_id: self.handler,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-21 16:48:37 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
2016-01-22 18:13:59 +01:00
|
|
|
|
2016-01-21 16:48:37 +01:00
|
|
|
/// Register a new IO stream.
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn register_stream(&self, token: StreamToken) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::RegisterStream {
|
2016-01-21 16:48:37 +01:00
|
|
|
token: token,
|
|
|
|
handler_id: self.handler,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-21 16:48:37 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2016-01-22 18:13:59 +01:00
|
|
|
/// Deregister an IO stream.
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn deregister_stream(&self, token: StreamToken) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::DeregisterStream {
|
2016-01-22 18:13:59 +01:00
|
|
|
token: token,
|
|
|
|
handler_id: self.handler,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-22 18:13:59 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2016-01-21 16:48:37 +01:00
|
|
|
/// Reregister an IO stream.
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn update_registration(&self, token: StreamToken) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send_io(IoMessage::UpdateStreamRegistration {
|
2016-01-21 16:48:37 +01:00
|
|
|
token: token,
|
|
|
|
handler_id: self.handler,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-21 16:48:37 +01:00
|
|
|
Ok(())
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Broadcast a message to other IO clients
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn message(&self, message: Message) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.channel.send(message)?;
|
2016-06-27 19:30:13 +02:00
|
|
|
Ok(())
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
2016-01-21 23:33:52 +01:00
|
|
|
|
|
|
|
/// Get message channel
|
|
|
|
pub fn channel(&self) -> IoChannel<Message> {
|
|
|
|
self.channel.clone()
|
|
|
|
}
|
2016-06-17 12:58:28 +02:00
|
|
|
|
|
|
|
/// Unregister current IO handler.
|
2018-05-22 06:35:13 +02:00
|
|
|
pub fn unregister_handler(&self) {
|
|
|
|
// `send_io` returns an error only if the channel is closed, which means that the
|
|
|
|
// background thread is no longer running. Therefore the handler is no longer active and
|
|
|
|
// can be considered as unregistered.
|
|
|
|
let _ = self.channel.send_io(IoMessage::RemoveHandler {
|
2016-06-17 12:58:28 +02:00
|
|
|
handler_id: self.handler,
|
2018-05-22 06:35:13 +02:00
|
|
|
});
|
2016-06-17 12:58:28 +02:00
|
|
|
}
|
|
|
|
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
2016-01-21 16:48:37 +01:00
|
|
|
#[derive(Clone)]
|
2016-01-12 17:33:40 +01:00
|
|
|
struct UserTimer {
|
2018-04-14 21:35:58 +02:00
|
|
|
delay: Duration,
|
2016-01-21 16:48:37 +01:00
|
|
|
timeout: Timeout,
|
2016-09-01 14:12:26 +02:00
|
|
|
once: bool,
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Root IO handler. Manages user handlers, messages and IO timers.
|
2016-01-21 16:48:37 +01:00
|
|
|
pub struct IoManager<Message> where Message: Send + Sync {
|
|
|
|
timers: Arc<RwLock<HashMap<HandlerId, UserTimer>>>,
|
2018-05-10 12:34:36 +02:00
|
|
|
handlers: Arc<RwLock<Slab<Arc<IoHandler<Message>>>>>,
|
2016-03-10 10:40:16 +01:00
|
|
|
workers: Vec<Worker>,
|
2016-01-21 16:48:37 +01:00
|
|
|
worker_channel: chase_lev::Worker<Work<Message>>,
|
2016-07-27 11:39:24 +02:00
|
|
|
work_ready: Arc<SCondvar>,
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> IoManager<Message> where Message: Send + Sync + 'static {
|
2016-01-12 17:33:40 +01:00
|
|
|
/// Creates a new instance and registers it with the event loop.
|
2016-10-20 14:49:12 +02:00
|
|
|
pub fn start(
|
|
|
|
event_loop: &mut EventLoop<IoManager<Message>>,
|
2018-05-10 12:34:36 +02:00
|
|
|
handlers: Arc<RwLock<Slab<Arc<IoHandler<Message>>>>>
|
2016-10-20 14:49:12 +02:00
|
|
|
) -> Result<(), IoError> {
|
2016-01-21 16:48:37 +01:00
|
|
|
let (worker, stealer) = chase_lev::deque();
|
|
|
|
let num_workers = 4;
|
2016-07-27 11:39:24 +02:00
|
|
|
let work_ready_mutex = Arc::new(SMutex::new(()));
|
|
|
|
let work_ready = Arc::new(SCondvar::new());
|
2016-02-10 12:50:27 +01:00
|
|
|
let workers = (0..num_workers).map(|i|
|
2016-02-10 16:35:52 +01:00
|
|
|
Worker::new(
|
|
|
|
i,
|
|
|
|
stealer.clone(),
|
2016-10-20 14:49:12 +02:00
|
|
|
IoChannel::new(event_loop.channel(), Arc::downgrade(&handlers)),
|
2016-02-10 16:35:52 +01:00
|
|
|
work_ready.clone(),
|
|
|
|
work_ready_mutex.clone(),
|
|
|
|
)
|
|
|
|
).collect();
|
2016-01-21 16:48:37 +01:00
|
|
|
|
2016-01-12 17:33:40 +01:00
|
|
|
let mut io = IoManager {
|
2016-01-21 16:48:37 +01:00
|
|
|
timers: Arc::new(RwLock::new(HashMap::new())),
|
2016-10-20 14:49:12 +02:00
|
|
|
handlers: handlers,
|
2016-01-21 16:48:37 +01:00
|
|
|
worker_channel: worker,
|
2016-03-10 10:40:16 +01:00
|
|
|
workers: workers,
|
2016-01-21 16:48:37 +01:00
|
|
|
work_ready: work_ready,
|
2016-01-12 17:33:40 +01:00
|
|
|
};
|
2016-12-27 12:53:56 +01:00
|
|
|
event_loop.run(&mut io)?;
|
2016-01-12 17:33:40 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> Handler for IoManager<Message> where Message: Send + Sync + 'static {
|
2016-01-12 17:33:40 +01:00
|
|
|
type Timeout = Token;
|
2016-01-13 13:56:48 +01:00
|
|
|
type Message = IoMessage<Message>;
|
2016-01-12 17:33:40 +01:00
|
|
|
|
2016-10-30 09:56:34 +01:00
|
|
|
fn ready(&mut self, _event_loop: &mut EventLoop<Self>, token: Token, events: Ready) {
|
|
|
|
let handler_index = token.0 / TOKENS_PER_HANDLER;
|
|
|
|
let token_id = token.0 % TOKENS_PER_HANDLER;
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(handler) = self.handlers.read().get(handler_index) {
|
2016-06-17 18:26:54 +02:00
|
|
|
if events.is_hup() {
|
|
|
|
self.worker_channel.push(Work { work_type: WorkType::Hup, token: token_id, handler: handler.clone(), handler_id: handler_index });
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
2016-06-17 18:26:54 +02:00
|
|
|
else {
|
|
|
|
if events.is_readable() {
|
|
|
|
self.worker_channel.push(Work { work_type: WorkType::Readable, token: token_id, handler: handler.clone(), handler_id: handler_index });
|
|
|
|
}
|
|
|
|
if events.is_writable() {
|
|
|
|
self.worker_channel.push(Work { work_type: WorkType::Writable, token: token_id, handler: handler.clone(), handler_id: handler_index });
|
|
|
|
}
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
2016-06-17 18:26:54 +02:00
|
|
|
self.work_ready.notify_all();
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn timeout(&mut self, event_loop: &mut EventLoop<Self>, token: Token) {
|
2016-10-30 09:56:34 +01:00
|
|
|
let handler_index = token.0 / TOKENS_PER_HANDLER;
|
|
|
|
let token_id = token.0 % TOKENS_PER_HANDLER;
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(handler) = self.handlers.read().get(handler_index) {
|
2016-11-01 18:52:52 +01:00
|
|
|
let maybe_timer = self.timers.read().get(&token.0).cloned();
|
|
|
|
if let Some(timer) = maybe_timer {
|
2016-09-01 14:12:26 +02:00
|
|
|
if timer.once {
|
|
|
|
self.timers.write().remove(&token_id);
|
2016-10-30 21:45:28 +01:00
|
|
|
event_loop.clear_timeout(&timer.timeout);
|
2016-09-01 14:12:26 +02:00
|
|
|
} else {
|
2018-04-14 21:35:58 +02:00
|
|
|
event_loop.timeout(token, timer.delay).expect("Error re-registering user timer");
|
2016-09-01 14:12:26 +02:00
|
|
|
}
|
2016-06-17 18:26:54 +02:00
|
|
|
self.worker_channel.push(Work { work_type: WorkType::Timeout, token: token_id, handler: handler.clone(), handler_id: handler_index });
|
|
|
|
self.work_ready.notify_all();
|
|
|
|
}
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn notify(&mut self, event_loop: &mut EventLoop<Self>, msg: Self::Message) {
|
2016-01-21 16:48:37 +01:00
|
|
|
match msg {
|
2016-03-10 10:40:16 +01:00
|
|
|
IoMessage::Shutdown => {
|
2016-04-06 23:45:19 +02:00
|
|
|
self.workers.clear();
|
2016-04-07 12:27:54 +02:00
|
|
|
event_loop.shutdown();
|
2016-03-10 10:40:16 +01:00
|
|
|
},
|
2016-01-21 16:48:37 +01:00
|
|
|
IoMessage::AddHandler { handler } => {
|
2018-05-10 12:34:36 +02:00
|
|
|
let handler_id = self.handlers.write().insert(handler.clone());
|
|
|
|
assert!(handler_id <= MAX_HANDLERS, "Too many handlers registered");
|
2016-10-20 14:49:12 +02:00
|
|
|
handler.initialize(&IoContext::new(IoChannel::new(event_loop.channel(), Arc::downgrade(&self.handlers)), handler_id));
|
2016-01-21 16:48:37 +01:00
|
|
|
},
|
2016-06-17 12:58:28 +02:00
|
|
|
IoMessage::RemoveHandler { handler_id } => {
|
|
|
|
// TODO: flush event loop
|
2016-10-20 14:49:12 +02:00
|
|
|
self.handlers.write().remove(handler_id);
|
2016-07-06 19:14:53 +02:00
|
|
|
// unregister timers
|
2016-07-13 19:59:59 +02:00
|
|
|
let mut timers = self.timers.write();
|
2016-07-06 19:14:53 +02:00
|
|
|
let to_remove: Vec<_> = timers.keys().cloned().filter(|timer_id| timer_id / TOKENS_PER_HANDLER == handler_id).collect();
|
|
|
|
for timer_id in to_remove {
|
|
|
|
let timer = timers.remove(&timer_id).expect("to_remove only contains keys from timers; qed");
|
2016-10-30 09:56:34 +01:00
|
|
|
event_loop.clear_timeout(&timer.timeout);
|
2016-07-06 19:14:53 +02:00
|
|
|
}
|
2016-06-17 12:58:28 +02:00
|
|
|
},
|
2016-09-01 14:12:26 +02:00
|
|
|
IoMessage::AddTimer { handler_id, token, delay, once } => {
|
2016-01-21 16:48:37 +01:00
|
|
|
let timer_id = token + handler_id * TOKENS_PER_HANDLER;
|
2018-04-14 21:35:58 +02:00
|
|
|
let timeout = event_loop.timeout(Token(timer_id), delay).expect("Error registering user timer");
|
2016-09-01 14:12:26 +02:00
|
|
|
self.timers.write().insert(timer_id, UserTimer { delay: delay, timeout: timeout, once: once });
|
2016-01-21 16:48:37 +01:00
|
|
|
},
|
|
|
|
IoMessage::RemoveTimer { handler_id, token } => {
|
|
|
|
let timer_id = token + handler_id * TOKENS_PER_HANDLER;
|
2016-07-13 19:59:59 +02:00
|
|
|
if let Some(timer) = self.timers.write().remove(&timer_id) {
|
2016-10-30 09:56:34 +01:00
|
|
|
event_loop.clear_timeout(&timer.timeout);
|
2016-01-21 16:48:37 +01:00
|
|
|
}
|
2016-01-12 17:33:40 +01:00
|
|
|
},
|
2016-01-21 16:48:37 +01:00
|
|
|
IoMessage::RegisterStream { handler_id, token } => {
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(handler) = self.handlers.read().get(handler_id) {
|
2016-06-17 18:26:54 +02:00
|
|
|
handler.register_stream(token, Token(token + handler_id * TOKENS_PER_HANDLER), event_loop);
|
|
|
|
}
|
2016-01-21 16:48:37 +01:00
|
|
|
},
|
2016-01-22 18:13:59 +01:00
|
|
|
IoMessage::DeregisterStream { handler_id, token } => {
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(handler) = self.handlers.read().get(handler_id) {
|
2016-06-17 18:26:54 +02:00
|
|
|
handler.deregister_stream(token, event_loop);
|
|
|
|
// unregister a timer associated with the token (if any)
|
|
|
|
let timer_id = token + handler_id * TOKENS_PER_HANDLER;
|
2016-07-13 19:59:59 +02:00
|
|
|
if let Some(timer) = self.timers.write().remove(&timer_id) {
|
2016-10-30 09:56:34 +01:00
|
|
|
event_loop.clear_timeout(&timer.timeout);
|
2016-06-17 18:26:54 +02:00
|
|
|
}
|
2016-02-15 11:54:38 +01:00
|
|
|
}
|
2016-01-22 18:13:59 +01:00
|
|
|
},
|
2016-01-21 16:48:37 +01:00
|
|
|
IoMessage::UpdateStreamRegistration { handler_id, token } => {
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(handler) = self.handlers.read().get(handler_id) {
|
2016-06-17 18:26:54 +02:00
|
|
|
handler.update_stream(token, Token(token + handler_id * TOKENS_PER_HANDLER), event_loop);
|
|
|
|
}
|
2016-01-21 16:48:37 +01:00
|
|
|
},
|
|
|
|
IoMessage::UserMessage(data) => {
|
2016-06-17 12:58:28 +02:00
|
|
|
//TODO: better way to iterate the slab
|
|
|
|
for id in 0 .. MAX_HANDLERS {
|
2016-10-20 14:49:12 +02:00
|
|
|
if let Some(h) = self.handlers.read().get(id) {
|
2016-06-17 12:58:28 +02:00
|
|
|
let handler = h.clone();
|
2018-05-09 08:49:34 +02:00
|
|
|
self.worker_channel.push(Work {
|
|
|
|
work_type: WorkType::Message(data.clone()),
|
|
|
|
token: 0,
|
|
|
|
handler: handler,
|
|
|
|
handler_id: id
|
|
|
|
});
|
2016-06-17 12:58:28 +02:00
|
|
|
}
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
2016-01-21 16:48:37 +01:00
|
|
|
self.work_ready.notify_all();
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
enum Handlers<Message> where Message: Send {
|
2018-05-10 12:34:36 +02:00
|
|
|
SharedCollection(Weak<RwLock<Slab<Arc<IoHandler<Message>>>>>),
|
2016-12-11 12:32:01 +01:00
|
|
|
Single(Weak<IoHandler<Message>>),
|
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message: Send> Clone for Handlers<Message> {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
use self::Handlers::*;
|
|
|
|
|
|
|
|
match *self {
|
|
|
|
SharedCollection(ref w) => SharedCollection(w.clone()),
|
|
|
|
Single(ref w) => Single(w.clone()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-13 23:13:57 +01:00
|
|
|
/// Allows sending messages into the event loop. All the IO handlers will get the message
|
|
|
|
/// in the `message` callback.
|
2018-05-09 08:49:34 +02:00
|
|
|
pub struct IoChannel<Message> where Message: Send {
|
2016-10-20 14:49:12 +02:00
|
|
|
channel: Option<Sender<IoMessage<Message>>>,
|
2016-12-11 12:32:01 +01:00
|
|
|
handlers: Handlers<Message>,
|
2016-01-13 23:13:57 +01:00
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> Clone for IoChannel<Message> where Message: Send + Sync + 'static {
|
2016-01-21 16:48:37 +01:00
|
|
|
fn clone(&self) -> IoChannel<Message> {
|
|
|
|
IoChannel {
|
2016-10-20 14:49:12 +02:00
|
|
|
channel: self.channel.clone(),
|
|
|
|
handlers: self.handlers.clone(),
|
2016-01-21 16:48:37 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> IoChannel<Message> where Message: Send + Sync + 'static {
|
2016-10-20 14:49:12 +02:00
|
|
|
/// Send a message through the channel
|
2016-01-17 23:07:58 +01:00
|
|
|
pub fn send(&self, message: Message) -> Result<(), IoError> {
|
2016-12-11 12:32:01 +01:00
|
|
|
match self.channel {
|
2018-05-09 08:49:34 +02:00
|
|
|
Some(ref channel) => channel.send(IoMessage::UserMessage(Arc::new(message)))?,
|
2016-12-27 12:53:56 +01:00
|
|
|
None => self.send_sync(message)?
|
2016-01-18 00:24:20 +01:00
|
|
|
}
|
2016-01-13 23:13:57 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
2016-01-18 00:24:20 +01:00
|
|
|
|
2016-10-20 14:49:12 +02:00
|
|
|
/// Send a message through the channel and handle it synchronously
|
|
|
|
pub fn send_sync(&self, message: Message) -> Result<(), IoError> {
|
2016-12-11 12:32:01 +01:00
|
|
|
match self.handlers {
|
|
|
|
Handlers::SharedCollection(ref handlers) => {
|
|
|
|
if let Some(handlers) = handlers.upgrade() {
|
|
|
|
for id in 0 .. MAX_HANDLERS {
|
|
|
|
if let Some(h) = handlers.read().get(id) {
|
|
|
|
let handler = h.clone();
|
|
|
|
handler.message(&IoContext::new(self.clone(), id), &message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Handlers::Single(ref handler) => {
|
|
|
|
if let Some(handler) = handler.upgrade() {
|
|
|
|
handler.message(&IoContext::new(self.clone(), 0), &message);
|
2016-10-20 14:49:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2016-01-22 00:11:19 +01:00
|
|
|
/// Send low level io message
|
2016-01-21 16:48:37 +01:00
|
|
|
pub fn send_io(&self, message: IoMessage<Message>) -> Result<(), IoError> {
|
|
|
|
if let Some(ref channel) = self.channel {
|
2016-12-27 12:53:56 +01:00
|
|
|
channel.send(message)?
|
2016-01-21 16:48:37 +01:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2017-01-10 12:23:59 +01:00
|
|
|
/// Create a new channel disconnected from an event loop.
|
2016-01-18 00:24:20 +01:00
|
|
|
pub fn disconnected() -> IoChannel<Message> {
|
2016-10-20 14:49:12 +02:00
|
|
|
IoChannel {
|
|
|
|
channel: None,
|
2016-12-11 12:32:01 +01:00
|
|
|
handlers: Handlers::SharedCollection(Weak::default()),
|
2016-10-20 14:49:12 +02:00
|
|
|
}
|
2016-01-18 00:24:20 +01:00
|
|
|
}
|
2016-01-21 16:48:37 +01:00
|
|
|
|
2016-12-11 12:32:01 +01:00
|
|
|
/// Create a new synchronous channel to a given handler.
|
|
|
|
pub fn to_handler(handler: Weak<IoHandler<Message>>) -> IoChannel<Message> {
|
|
|
|
IoChannel {
|
|
|
|
channel: None,
|
|
|
|
handlers: Handlers::Single(handler),
|
|
|
|
}
|
|
|
|
}
|
2018-05-10 12:34:36 +02:00
|
|
|
fn new(channel: Sender<IoMessage<Message>>, handlers: Weak<RwLock<Slab<Arc<IoHandler<Message>>>>>) -> IoChannel<Message> {
|
2016-10-20 14:49:12 +02:00
|
|
|
IoChannel {
|
|
|
|
channel: Some(channel),
|
2016-12-11 12:32:01 +01:00
|
|
|
handlers: Handlers::SharedCollection(handlers),
|
2016-10-20 14:49:12 +02:00
|
|
|
}
|
2016-01-21 16:48:37 +01:00
|
|
|
}
|
2016-01-13 23:13:57 +01:00
|
|
|
}
|
|
|
|
|
2016-01-12 17:33:40 +01:00
|
|
|
/// General IO Service. Starts an event loop and dispatches IO requests.
|
2016-01-13 13:56:48 +01:00
|
|
|
/// 'Message' is a notification message type
|
2018-05-09 08:49:34 +02:00
|
|
|
pub struct IoService<Message> where Message: Send + Sync + 'static {
|
2016-12-09 13:25:02 +01:00
|
|
|
thread: Mutex<Option<JoinHandle<()>>>,
|
2016-10-30 09:56:34 +01:00
|
|
|
host_channel: Mutex<Sender<IoMessage<Message>>>,
|
2018-05-10 12:34:36 +02:00
|
|
|
handlers: Arc<RwLock<Slab<Arc<IoHandler<Message>>>>>,
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> IoService<Message> where Message: Send + Sync + 'static {
|
2016-01-12 17:33:40 +01:00
|
|
|
/// Starts IO event loop
|
2016-08-05 10:32:04 +02:00
|
|
|
pub fn start() -> Result<IoService<Message>, IoError> {
|
2016-10-30 09:56:34 +01:00
|
|
|
let mut config = EventLoopBuilder::new();
|
2016-06-27 19:30:13 +02:00
|
|
|
config.messages_per_tick(1024);
|
2016-10-30 09:56:34 +01:00
|
|
|
let mut event_loop = config.build().expect("Error creating event loop");
|
2016-08-05 10:32:04 +02:00
|
|
|
let channel = event_loop.channel();
|
2018-05-10 12:34:36 +02:00
|
|
|
let handlers = Arc::new(RwLock::new(Slab::with_capacity(MAX_HANDLERS)));
|
2016-10-20 14:49:12 +02:00
|
|
|
let h = handlers.clone();
|
2016-01-12 17:33:40 +01:00
|
|
|
let thread = thread::spawn(move || {
|
2017-06-22 19:00:53 +02:00
|
|
|
IoManager::<Message>::start(&mut event_loop, h).expect("Error starting IO service");
|
2016-01-12 17:33:40 +01:00
|
|
|
});
|
|
|
|
Ok(IoService {
|
2016-12-09 13:25:02 +01:00
|
|
|
thread: Mutex::new(Some(thread)),
|
2016-10-30 09:56:34 +01:00
|
|
|
host_channel: Mutex::new(channel),
|
2016-10-20 14:49:12 +02:00
|
|
|
handlers: handlers,
|
2016-01-12 17:33:40 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-12-09 13:25:02 +01:00
|
|
|
pub fn stop(&self) {
|
2016-12-09 11:45:16 +01:00
|
|
|
trace!(target: "shutdown", "[IoService] Closing...");
|
|
|
|
// Clear handlers so that shared pointers are not stuck on stack
|
|
|
|
// in Channel::send_sync
|
|
|
|
self.handlers.write().clear();
|
|
|
|
self.host_channel.lock().send(IoMessage::Shutdown).unwrap_or_else(|e| warn!("Error on IO service shutdown: {:?}", e));
|
2016-12-09 13:25:02 +01:00
|
|
|
if let Some(thread) = self.thread.lock().take() {
|
2016-12-09 11:45:16 +01:00
|
|
|
thread.join().unwrap_or_else(|e| {
|
|
|
|
debug!(target: "shutdown", "Error joining IO service event loop thread: {:?}", e);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
trace!(target: "shutdown", "[IoService] Closed.");
|
|
|
|
}
|
|
|
|
|
2016-06-17 12:58:28 +02:00
|
|
|
/// Regiter an IO handler with the event loop.
|
|
|
|
pub fn register_handler(&self, handler: Arc<IoHandler<Message>+Send>) -> Result<(), IoError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
self.host_channel.lock().send(IoMessage::AddHandler {
|
2016-01-12 17:33:40 +01:00
|
|
|
handler: handler,
|
2016-12-27 12:53:56 +01:00
|
|
|
})?;
|
2016-01-12 17:33:40 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
2016-01-13 11:31:37 +01:00
|
|
|
|
|
|
|
/// Send a message over the network. Normaly `HostIo::send` should be used. This can be used from non-io threads.
|
2016-06-17 12:58:28 +02:00
|
|
|
pub fn send_message(&self, message: Message) -> Result<(), IoError> {
|
2018-05-09 08:49:34 +02:00
|
|
|
self.host_channel.lock().send(IoMessage::UserMessage(Arc::new(message)))?;
|
2016-01-13 11:31:37 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
2016-01-13 23:13:57 +01:00
|
|
|
|
|
|
|
/// Create a new message channel
|
2016-06-17 12:58:28 +02:00
|
|
|
pub fn channel(&self) -> IoChannel<Message> {
|
2016-10-30 09:56:34 +01:00
|
|
|
IoChannel::new(self.host_channel.lock().clone(), Arc::downgrade(&self.handlers))
|
2016-01-13 23:13:57 +01:00
|
|
|
}
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
|
2018-05-09 08:49:34 +02:00
|
|
|
impl<Message> Drop for IoService<Message> where Message: Send + Sync {
|
2016-01-12 17:33:40 +01:00
|
|
|
fn drop(&mut self) {
|
2016-12-09 11:45:16 +01:00
|
|
|
self.stop()
|
2016-01-12 17:33:40 +01:00
|
|
|
}
|
|
|
|
}
|