| 1 |
// Copyright © 2021 Mozilla Foundation |
| 2 |
// |
| 3 |
// This program is made available under an ISC-style license. See the |
| 4 |
// accompanying file LICENSE for details |
| 5 |
|
| 6 |
use std::io::{self, Result}; |
| 7 |
use std::sync::{mpsc, Arc}; |
| 8 |
use std::thread; |
| 9 |
|
| 10 |
use mio::{event::Event, Events, Interest, Poll, Registry, Token, Waker}; |
| 11 |
use slab::Slab; |
| 12 |
|
| 13 |
use crate::messages::AssociateHandleForMessage; |
| 14 |
use crate::rpccore::{ |
| 15 |
make_client, make_server, Client, Handler, Proxy, RequestQueue, RequestQueueSender, Server, |
| 16 |
}; |
| 17 |
use crate::{ |
| 18 |
codec::Codec, |
| 19 |
codec::LengthDelimitedCodec, |
| 20 |
sys::{self, RecvMsg, SendMsg}, |
| 21 |
}; |
| 22 |
|
| 23 |
use serde::{de::DeserializeOwned, Serialize}; |
| 24 |
use std::fmt::Debug; |
| 25 |
|
| 26 |
const WAKE_TOKEN: Token = Token(!0); |
| 27 |
|
| 28 |
thread_local!(static IN_EVENTLOOP: std::cell::RefCell<Option<thread::ThreadId>> = const { std::cell::RefCell::new(None) }); |
| 29 |
|
| 30 |
fn assert_not_in_event_loop_thread() { |
| 31 |
IN_EVENTLOOP.with(|b| { |
| 32 |
assert_ne!(*b.borrow(), Some(thread::current().id())); |
| 33 |
}); |
| 34 |
} |
| 35 |
|
| 36 |
// Requests sent by an EventLoopHandle to be serviced by |
| 37 |
// the handle's associated EventLoop. |
| 38 |
enum Request { |
| 39 |
// See EventLoop::add_connection |
| 40 |
AddConnection( |
| 41 |
sys::Pipe, |
| 42 |
Box<dyn Driver + Send>, |
| 43 |
mpsc::Sender<Result<Token>>, |
| 44 |
), |
| 45 |
// See EventLoop::shutdown |
| 46 |
Shutdown, |
| 47 |
// See EventLoop::wake_connection |
| 48 |
WakeConnection(Token), |
| 49 |
} |
| 50 |
|
| 51 |
// EventLoopHandle is a cloneable external reference |
| 52 |
// to a running EventLoop, allowing registration of |
| 53 |
// new client and server connections, in addition to |
| 54 |
// requesting the EventLoop shut down cleanly. |
| 55 |
#[derive(Clone, Debug)] |
| 56 |
pub struct EventLoopHandle { |
| 57 |
waker: Arc<Waker>, |
| 58 |
requests: RequestQueueSender<Request>, |
| 59 |
} |
| 60 |
|
| 61 |
impl EventLoopHandle { |
| 62 |
pub fn bind_client<C: Client + 'static>( |
| 63 |
&self, |
| 64 |
connection: sys::Pipe, |
| 65 |
) -> Result<Proxy<<C as Client>::ServerMessage, <C as Client>::ClientMessage>> |
| 66 |
where |
| 67 |
<C as Client>::ServerMessage: Serialize + Debug + AssociateHandleForMessage + Send, |
| 68 |
<C as Client>::ClientMessage: DeserializeOwned + Debug + AssociateHandleForMessage + Send, |
| 69 |
{ |
| 70 |
let (handler, mut proxy) = make_client::<C>()?; |
| 71 |
let driver = Box::new(FramedDriver::new(handler)); |
| 72 |
let r = self.add_connection(connection, driver); |
| 73 |
trace!("EventLoop::bind_client {:?}", r); |
| 74 |
r.map(|token| { |
| 75 |
proxy.connect_event_loop(self.clone(), token); |
| 76 |
proxy |
| 77 |
}) |
| 78 |
} |
| 79 |
|
| 80 |
pub fn bind_server<S: Server + Send + 'static>( |
| 81 |
&self, |
| 82 |
server: S, |
| 83 |
connection: sys::Pipe, |
| 84 |
) -> Result<()> |
| 85 |
where |
| 86 |
<S as Server>::ServerMessage: DeserializeOwned + Debug + AssociateHandleForMessage + Send, |
| 87 |
<S as Server>::ClientMessage: Serialize + Debug + AssociateHandleForMessage + Send, |
| 88 |
{ |
| 89 |
let handler = make_server::<S>(server); |
| 90 |
let driver = Box::new(FramedDriver::new(handler)); |
| 91 |
let r = self.add_connection(connection, driver); |
| 92 |
trace!("EventLoop::bind_server {:?}", r); |
| 93 |
r.map(|_| ()) |
| 94 |
} |
| 95 |
|
| 96 |
// Register a new connection with associated driver on the EventLoop. |
| 97 |
// TODO: Since this is called from a Gecko main thread, make this non-blocking wrt. the EventLoop. |
| 98 |
fn add_connection( |
| 99 |
&self, |
| 100 |
connection: sys::Pipe, |
| 101 |
driver: Box<dyn Driver + Send>, |
| 102 |
) -> Result<Token> { |
| 103 |
assert_not_in_event_loop_thread(); |
| 104 |
let (tx, rx) = mpsc::channel(); |
| 105 |
self.requests |
| 106 |
.push(Request::AddConnection(connection, driver, tx)) |
| 107 |
.map_err(|_| { |
| 108 |
debug!("EventLoopHandle::add_connection send failed"); |
| 109 |
io::ErrorKind::ConnectionAborted |
| 110 |
})?; |
| 111 |
self.waker.wake()?; |
| 112 |
rx.recv().map_err(|_| { |
| 113 |
debug!("EventLoopHandle::add_connection recv failed"); |
| 114 |
io::ErrorKind::ConnectionAborted |
| 115 |
})? |
| 116 |
} |
| 117 |
|
| 118 |
// Signal EventLoop to shutdown. Causes EventLoop::poll to return Ok(false). |
| 119 |
fn shutdown(&self) -> Result<()> { |
| 120 |
self.requests.push(Request::Shutdown).map_err(|_| { |
| 121 |
debug!("EventLoopHandle::shutdown send failed"); |
| 122 |
io::ErrorKind::ConnectionAborted |
| 123 |
})?; |
| 124 |
self.waker.wake() |
| 125 |
} |
| 126 |
|
| 127 |
// Signal EventLoop to wake connection specified by `token` for processing. |
| 128 |
pub(crate) fn wake_connection(&self, token: Token) { |
| 129 |
if self.requests.push(Request::WakeConnection(token)).is_ok() { |
| 130 |
self.waker.wake().expect("wake failed"); |
| 131 |
} |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
// EventLoop owns all registered connections, and is responsible for calling each connection's |
| 136 |
// `handle_event` or `handle_wake` any time a readiness or wake event associated with that connection is |
| 137 |
// produced. |
| 138 |
struct EventLoop { |
| 139 |
poll: Poll, |
| 140 |
events: Events, |
| 141 |
waker: Arc<Waker>, |
| 142 |
name: String, |
| 143 |
connections: Slab<Connection>, |
| 144 |
requests: Arc<RequestQueue<Request>>, |
| 145 |
} |
| 146 |
|
| 147 |
const EVENT_LOOP_INITIAL_CLIENTS: usize = 64; // Initial client allocation, exceeding this will cause the connection slab to grow. |
| 148 |
const EVENT_LOOP_EVENTS_PER_ITERATION: usize = 256; // Number of events per poll() step, arbitrary limit. |
| 149 |
|
| 150 |
impl EventLoop { |
| 151 |
fn new(name: String) -> Result<EventLoop> { |
| 152 |
let poll = Poll::new()?; |
| 153 |
let waker = Arc::new(Waker::new(poll.registry(), WAKE_TOKEN)?); |
| 154 |
let eventloop = EventLoop { |
| 155 |
poll, |
| 156 |
events: Events::with_capacity(EVENT_LOOP_EVENTS_PER_ITERATION), |
| 157 |
waker, |
| 158 |
name, |
| 159 |
connections: Slab::with_capacity(EVENT_LOOP_INITIAL_CLIENTS), |
| 160 |
requests: Arc::new(RequestQueue::new(EVENT_LOOP_INITIAL_CLIENTS)), |
| 161 |
}; |
| 162 |
|
| 163 |
Ok(eventloop) |
| 164 |
} |
| 165 |
|
| 166 |
// Return a cloneable handle for controlling the EventLoop externally. |
| 167 |
fn handle(&mut self) -> EventLoopHandle { |
| 168 |
EventLoopHandle { |
| 169 |
waker: self.waker.clone(), |
| 170 |
requests: self.requests.new_sender(), |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
// Register a connection and driver. |
| 175 |
fn add_connection( |
| 176 |
&mut self, |
| 177 |
connection: sys::Pipe, |
| 178 |
driver: Box<dyn Driver + Send>, |
| 179 |
) -> Result<Token> { |
| 180 |
if self.connections.len() == self.connections.capacity() { |
| 181 |
trace!("{}: connection slab full, insert will allocate", self.name); |
| 182 |
} |
| 183 |
let entry = self.connections.vacant_entry(); |
| 184 |
let token = Token(entry.key()); |
| 185 |
assert_ne!(token, WAKE_TOKEN); |
| 186 |
let connection = Connection::new(connection, token, driver, self.poll.registry())?; |
| 187 |
debug!("{}: {:?}: new connection", self.name, token); |
| 188 |
entry.insert(connection); |
| 189 |
Ok(token) |
| 190 |
} |
| 191 |
|
| 192 |
// Step EventLoop once. Call this in a loop from a dedicated thread. |
| 193 |
// Returns false if EventLoop is shutting down. |
| 194 |
// Each step may call `handle_event` on any registered connection that |
| 195 |
// has received readiness events from the poll wakeup. |
| 196 |
fn poll(&mut self) -> Result<bool> { |
| 197 |
loop { |
| 198 |
let r = self.poll.poll(&mut self.events, None); |
| 199 |
match r { |
| 200 |
Ok(()) => break, |
| 201 |
Err(ref e) if interrupted(e) => continue, |
| 202 |
Err(e) => return Err(e), |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
for event in self.events.iter() { |
| 207 |
match event.token() { |
| 208 |
WAKE_TOKEN => { |
| 209 |
debug!("{}: WAKE: wake event, will process requests", self.name); |
| 210 |
} |
| 211 |
token => { |
| 212 |
debug!("{}: {:?}: connection event: {:?}", self.name, token, event); |
| 213 |
let done = if let Some(connection) = self.connections.get_mut(token.0) { |
| 214 |
match connection.handle_event(event, self.poll.registry()) { |
| 215 |
Ok(done) => { |
| 216 |
debug!("{}: connection {:?} done={}", self.name, token, done); |
| 217 |
done |
| 218 |
} |
| 219 |
Err(e) => { |
| 220 |
debug!("{}: {:?}: connection error: {:?}", self.name, token, e); |
| 221 |
true |
| 222 |
} |
| 223 |
} |
| 224 |
} else { |
| 225 |
// Spurious event, log and ignore. |
| 226 |
debug!( |
| 227 |
"{}: {:?}: token not found in slab: {:?}", |
| 228 |
self.name, token, event |
| 229 |
); |
| 230 |
false |
| 231 |
}; |
| 232 |
if done { |
| 233 |
debug!("{}: {:?}: done, removing", self.name, token); |
| 234 |
let mut connection = self.connections.remove(token.0); |
| 235 |
if let Err(e) = connection.shutdown(self.poll.registry()) { |
| 236 |
debug!( |
| 237 |
"{}: EventLoop drop - closing connection for {:?} failed: {:?}", |
| 238 |
self.name, token, e |
| 239 |
); |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
// If the waker was signalled there may be pending requests to process. |
| 247 |
while let Some(req) = self.requests.pop() { |
| 248 |
match req { |
| 249 |
Request::AddConnection(pipe, driver, tx) => { |
| 250 |
debug!("{}: EventLoop: handling add_connection", self.name); |
| 251 |
let r = self.add_connection(pipe, driver); |
| 252 |
tx.send(r).expect("EventLoop::add_connection"); |
| 253 |
} |
| 254 |
Request::Shutdown => { |
| 255 |
debug!("{}: EventLoop: handling shutdown", self.name); |
| 256 |
return Ok(false); |
| 257 |
} |
| 258 |
Request::WakeConnection(token) => { |
| 259 |
debug!( |
| 260 |
"{}: EventLoop: handling wake_connection {:?}", |
| 261 |
self.name, token |
| 262 |
); |
| 263 |
let done = if let Some(connection) = self.connections.get_mut(token.0) { |
| 264 |
match connection.handle_wake(self.poll.registry()) { |
| 265 |
Ok(done) => done, |
| 266 |
Err(e) => { |
| 267 |
debug!("{}: {:?}: connection error: {:?}", self.name, token, e); |
| 268 |
true |
| 269 |
} |
| 270 |
} |
| 271 |
} else { |
| 272 |
// Spurious wake, log and ignore. |
| 273 |
debug!( |
| 274 |
"{}: {:?}: token not found in slab: wake_connection", |
| 275 |
self.name, token |
| 276 |
); |
| 277 |
false |
| 278 |
}; |
| 279 |
if done { |
| 280 |
debug!("{}: {:?}: done (wake), removing", self.name, token); |
| 281 |
let mut connection = self.connections.remove(token.0); |
| 282 |
if let Err(e) = connection.shutdown(self.poll.registry()) { |
| 283 |
debug!( |
| 284 |
"{}: EventLoop drop - closing connection for {:?} failed: {:?}", |
| 285 |
self.name, token, e |
| 286 |
); |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
Ok(true) |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
impl Drop for EventLoop { |
| 298 |
fn drop(&mut self) { |
| 299 |
debug!("{}: EventLoop drop", self.name); |
| 300 |
for (token, connection) in &mut self.connections { |
| 301 |
debug!( |
| 302 |
"{}: EventLoop drop - closing connection for {:?}", |
| 303 |
self.name, token |
| 304 |
); |
| 305 |
if let Err(e) = connection.shutdown(self.poll.registry()) { |
| 306 |
debug!( |
| 307 |
"{}: EventLoop drop - closing connection for {:?} failed: {:?}", |
| 308 |
self.name, token, e |
| 309 |
); |
| 310 |
} |
| 311 |
} |
| 312 |
debug!("{}: EventLoop drop done", self.name); |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
// Connection wraps an interprocess connection (Pipe) and manages |
| 317 |
// receiving inbound and sending outbound buffers (and associated handles, if any). |
| 318 |
// The associated driver is responsible for message framing and serialization. |
| 319 |
struct Connection { |
| 320 |
io: sys::Pipe, |
| 321 |
token: Token, |
| 322 |
interest: Option<Interest>, |
| 323 |
inbound: sys::ConnectionBuffer, |
| 324 |
outbound: sys::ConnectionBuffer, |
| 325 |
driver: Box<dyn Driver + Send>, |
| 326 |
} |
| 327 |
|
| 328 |
pub(crate) const IPC_CLIENT_BUFFER_SIZE: usize = 16384; |
| 329 |
|
| 330 |
impl Connection { |
| 331 |
fn new( |
| 332 |
mut io: sys::Pipe, |
| 333 |
token: Token, |
| 334 |
driver: Box<dyn Driver + Send>, |
| 335 |
registry: &Registry, |
| 336 |
) -> Result<Connection> { |
| 337 |
let interest = Interest::READABLE; |
| 338 |
registry.register(&mut io, token, interest)?; |
| 339 |
Ok(Connection { |
| 340 |
io, |
| 341 |
token, |
| 342 |
interest: Some(interest), |
| 343 |
inbound: sys::ConnectionBuffer::with_capacity(IPC_CLIENT_BUFFER_SIZE), |
| 344 |
outbound: sys::ConnectionBuffer::with_capacity(IPC_CLIENT_BUFFER_SIZE), |
| 345 |
driver, |
| 346 |
}) |
| 347 |
} |
| 348 |
|
| 349 |
fn shutdown(&mut self, registry: &Registry) -> Result<()> { |
| 350 |
trace!( |
| 351 |
"{:?}: connection shutdown interest={:?}", |
| 352 |
self.token, |
| 353 |
self.interest |
| 354 |
); |
| 355 |
let r = self.io.shutdown(); |
| 356 |
trace!("{:?}: connection shutdown r={:?}", self.token, r); |
| 357 |
self.interest = None; |
| 358 |
registry.deregister(&mut self.io) |
| 359 |
} |
| 360 |
|
| 361 |
// Connections are always interested in READABLE. clear_readable is only |
| 362 |
// called when the connection is in the process of shutting down. |
| 363 |
fn clear_readable(&mut self, registry: &Registry) -> Result<()> { |
| 364 |
self.update_registration( |
| 365 |
registry, |
| 366 |
self.interest.and_then(|i| i.remove(Interest::READABLE)), |
| 367 |
) |
| 368 |
} |
| 369 |
|
| 370 |
// Connections toggle WRITABLE based on the state of the `outbound` buffer. |
| 371 |
fn set_writable(&mut self, registry: &Registry) -> Result<()> { |
| 372 |
self.update_registration( |
| 373 |
registry, |
| 374 |
Some( |
| 375 |
self.interest |
| 376 |
.map_or_else(|| Interest::WRITABLE, |i| i.add(Interest::WRITABLE)), |
| 377 |
), |
| 378 |
) |
| 379 |
} |
| 380 |
|
| 381 |
fn clear_writable(&mut self, registry: &Registry) -> Result<()> { |
| 382 |
self.update_registration( |
| 383 |
registry, |
| 384 |
self.interest.and_then(|i| i.remove(Interest::WRITABLE)), |
| 385 |
) |
| 386 |
} |
| 387 |
|
| 388 |
// Update connection registration with the current readiness event interests. |
| 389 |
fn update_registration( |
| 390 |
&mut self, |
| 391 |
registry: &Registry, |
| 392 |
new_interest: Option<Interest>, |
| 393 |
) -> Result<()> { |
| 394 |
// Note: Updating registration always triggers a writable event with NamedPipes, so |
| 395 |
// it's important to skip updating registration when the set of interests hasn't changed. |
| 396 |
if new_interest != self.interest { |
| 397 |
trace!( |
| 398 |
"{:?}: updating readiness registration old={:?} new={:?}", |
| 399 |
self.token, |
| 400 |
self.interest, |
| 401 |
new_interest |
| 402 |
); |
| 403 |
self.interest = new_interest; |
| 404 |
if let Some(interest) = self.interest { |
| 405 |
registry.reregister(&mut self.io, self.token, interest)?; |
| 406 |
} else { |
| 407 |
registry.deregister(&mut self.io)?; |
| 408 |
} |
| 409 |
} |
| 410 |
Ok(()) |
| 411 |
} |
| 412 |
|
| 413 |
// Handle readiness event. Errors returned are fatal for this connection, resulting in removal from the EventLoop connection list. |
| 414 |
// The EventLoop will call this for any connection that has received an event. |
| 415 |
fn handle_event(&mut self, event: &Event, registry: &Registry) -> Result<bool> { |
| 416 |
debug!("{:?}: handling event {:?}", self.token, event); |
| 417 |
assert_eq!(self.token, event.token()); |
| 418 |
let done = if event.is_readable() { |
| 419 |
self.recv_inbound()? |
| 420 |
} else { |
| 421 |
trace!("{:?}: not readable", self.token); |
| 422 |
false |
| 423 |
}; |
| 424 |
self.flush_outbound()?; |
| 425 |
if self.send_outbound(registry)? { |
| 426 |
// Hit EOF during send |
| 427 |
return Ok(true); |
| 428 |
} |
| 429 |
debug!( |
| 430 |
"{:?}: handling event done (recv done={}, outbound={})", |
| 431 |
self.token, |
| 432 |
done, |
| 433 |
self.outbound.is_empty() |
| 434 |
); |
| 435 |
let done = done && self.outbound.is_empty(); |
| 436 |
// If driver is done and outbound is clear, unregister connection. |
| 437 |
if done { |
| 438 |
trace!("{:?}: driver done, clearing read interest", self.token); |
| 439 |
self.clear_readable(registry)?; |
| 440 |
} |
| 441 |
Ok(done) |
| 442 |
} |
| 443 |
|
| 444 |
// Handle wake event. Errors returned are fatal for this connection, resulting in removal from the EventLoop connection list. |
| 445 |
// The EventLoop will call this to clear the outbound buffer for any connection that has received a wake event. |
| 446 |
fn handle_wake(&mut self, registry: &Registry) -> Result<bool> { |
| 447 |
debug!("{:?}: handling wake", self.token); |
| 448 |
self.flush_outbound()?; |
| 449 |
if self.send_outbound(registry)? { |
| 450 |
// Hit EOF during send |
| 451 |
return Ok(true); |
| 452 |
} |
| 453 |
debug!("{:?}: handling wake done", self.token); |
| 454 |
Ok(false) |
| 455 |
} |
| 456 |
|
| 457 |
fn recv_inbound(&mut self) -> Result<bool> { |
| 458 |
// If the connection is readable, read into inbound and pass to driver for processing until all ready data |
| 459 |
// has been consumed. |
| 460 |
loop { |
| 461 |
trace!("{:?}: pre-recv inbound: {:?}", self.token, self.inbound); |
| 462 |
let r = self.io.recv_msg(&mut self.inbound); |
| 463 |
match r { |
| 464 |
Ok(0) => { |
| 465 |
trace!( |
| 466 |
"{:?}: recv EOF unprocessed inbound={}", |
| 467 |
self.token, |
| 468 |
self.inbound.is_empty() |
| 469 |
); |
| 470 |
return Ok(true); |
| 471 |
} |
| 472 |
Ok(n) => { |
| 473 |
trace!("{:?}: recv bytes: {}, process_inbound", self.token, n); |
| 474 |
let r = self.driver.process_inbound(&mut self.inbound); |
| 475 |
trace!("{:?}: process_inbound done: {:?}", self.token, r); |
| 476 |
match r { |
| 477 |
Ok(done) => { |
| 478 |
if done { |
| 479 |
return Ok(true); |
| 480 |
} |
| 481 |
} |
| 482 |
Err(e) => { |
| 483 |
debug!( |
| 484 |
"{:?}: process_inbound error: {:?} unprocessed inbound={}", |
| 485 |
self.token, |
| 486 |
e, |
| 487 |
self.inbound.is_empty() |
| 488 |
); |
| 489 |
return Err(e); |
| 490 |
} |
| 491 |
} |
| 492 |
} |
| 493 |
Err(ref e) if would_block(e) => { |
| 494 |
trace!("{:?}: recv would_block: {:?}", self.token, e); |
| 495 |
return Ok(false); |
| 496 |
} |
| 497 |
Err(ref e) if interrupted(e) => { |
| 498 |
trace!("{:?}: recv interrupted: {:?}", self.token, e); |
| 499 |
continue; |
| 500 |
} |
| 501 |
Err(e) => { |
| 502 |
debug!("{:?}: recv error: {:?}", self.token, e); |
| 503 |
return Err(e); |
| 504 |
} |
| 505 |
} |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
fn flush_outbound(&mut self) -> Result<()> { |
| 510 |
// Enqueue outbound messages to the outbound buffer, then try to write out to connection. |
| 511 |
// There may be outbound messages even if there was no inbound processing, so always attempt |
| 512 |
// to enqueue and flush. |
| 513 |
trace!("{:?}: flush_outbound", self.token); |
| 514 |
let r = self.driver.flush_outbound(&mut self.outbound); |
| 515 |
trace!("{:?}: flush_outbound done: {:?}", self.token, r); |
| 516 |
if let Err(e) = r { |
| 517 |
debug!("{:?}: flush_outbound error: {:?}", self.token, e); |
| 518 |
return Err(e); |
| 519 |
} |
| 520 |
Ok(()) |
| 521 |
} |
| 522 |
|
| 523 |
fn send_outbound(&mut self, registry: &Registry) -> Result<bool> { |
| 524 |
// Attempt to flush outbound buffer. If the connection's write buffer is full, register for WRITABLE |
| 525 |
// and complete flushing when associated notitication arrives later. |
| 526 |
while !self.outbound.is_empty() { |
| 527 |
let r = self.io.send_msg(&mut self.outbound); |
| 528 |
match r { |
| 529 |
Ok(0) => { |
| 530 |
trace!("{:?}: send EOF", self.token); |
| 531 |
return Ok(true); |
| 532 |
} |
| 533 |
Ok(n) => { |
| 534 |
trace!("{:?}: send bytes: {}", self.token, n); |
| 535 |
} |
| 536 |
Err(ref e) if would_block(e) => { |
| 537 |
trace!( |
| 538 |
"{:?}: send would_block: {:?}, setting write interest", |
| 539 |
self.token, |
| 540 |
e |
| 541 |
); |
| 542 |
// Register for write events. |
| 543 |
self.set_writable(registry)?; |
| 544 |
break; |
| 545 |
} |
| 546 |
Err(ref e) if interrupted(e) => { |
| 547 |
trace!("{:?}: send interrupted: {:?}", self.token, e); |
| 548 |
continue; |
| 549 |
} |
| 550 |
Err(e) => { |
| 551 |
debug!("{:?}: send error: {:?}", self.token, e); |
| 552 |
return Err(e); |
| 553 |
} |
| 554 |
} |
| 555 |
trace!("{:?}: post-send: outbound {:?}", self.token, self.outbound); |
| 556 |
} |
| 557 |
// Outbound buffer flushed, clear registration for WRITABLE. |
| 558 |
if self.outbound.is_empty() { |
| 559 |
trace!("{:?}: outbound empty, clearing write interest", self.token); |
| 560 |
self.clear_writable(registry)?; |
| 561 |
} |
| 562 |
Ok(false) |
| 563 |
} |
| 564 |
} |
| 565 |
|
| 566 |
impl Drop for Connection { |
| 567 |
fn drop(&mut self) { |
| 568 |
debug!("{:?}: Connection drop", self.token); |
| 569 |
} |
| 570 |
} |
| 571 |
|
| 572 |
fn would_block(err: &std::io::Error) -> bool { |
| 573 |
err.kind() == std::io::ErrorKind::WouldBlock |
| 574 |
} |
| 575 |
|
| 576 |
fn interrupted(err: &std::io::Error) -> bool { |
| 577 |
err.kind() == std::io::ErrorKind::Interrupted |
| 578 |
} |
| 579 |
|
| 580 |
// Driver only has a single implementation, but must be hidden behind a Trait object to |
| 581 |
// hide the varying FramedDriver sizes (due to different `T` values). |
| 582 |
trait Driver { |
| 583 |
// Handle inbound messages. Returns true if Driver is done; this will trigger Connection removal and cleanup. |
| 584 |
fn process_inbound(&mut self, inbound: &mut sys::ConnectionBuffer) -> Result<bool>; |
| 585 |
|
| 586 |
// Write outbound messages to `outbound`. |
| 587 |
fn flush_outbound(&mut self, outbound: &mut sys::ConnectionBuffer) -> Result<()>; |
| 588 |
} |
| 589 |
|
| 590 |
// Length-delimited connection framing and (de)serialization is handled by the inbound and outbound processing. |
| 591 |
// Handlers can then process message Requests and Responses without knowledge of serialization or |
| 592 |
// handle remoting. |
| 593 |
impl<T> Driver for FramedDriver<T> |
| 594 |
where |
| 595 |
T: Handler, |
| 596 |
T::In: DeserializeOwned + Debug + AssociateHandleForMessage, |
| 597 |
T::Out: Serialize + Debug + AssociateHandleForMessage, |
| 598 |
{ |
| 599 |
// Caller passes `inbound` data, this function will trim any complete messages from `inbound` and pass them to the handler for processing. |
| 600 |
fn process_inbound(&mut self, inbound: &mut sys::ConnectionBuffer) -> Result<bool> { |
| 601 |
debug!("process_inbound: {:?}", inbound); |
| 602 |
|
| 603 |
// Repeatedly call `decode` as long as it produces items, passing each produced item to the handler to action. |
| 604 |
#[allow(unused_mut)] |
| 605 |
while let Some(mut item) = self.codec.decode(&mut inbound.buf)? { |
| 606 |
if item.has_associated_handle() { |
| 607 |
// On Unix, dequeue a handle from the connection and update the item's handle. |
| 608 |
#[cfg(unix)] |
| 609 |
{ |
| 610 |
let new = inbound |
| 611 |
.pop_handle() |
| 612 |
.expect("inbound handle expected for item"); |
| 613 |
unsafe { item.set_local_handle(new.take()) }; |
| 614 |
} |
| 615 |
// On Windows, the deserialized item contains the correct handle value, so |
| 616 |
// convert it to an owned handle on the item. |
| 617 |
#[cfg(windows)] |
| 618 |
{ |
| 619 |
assert!(inbound.pop_handle().is_none()); |
| 620 |
unsafe { item.set_local_handle() }; |
| 621 |
} |
| 622 |
} |
| 623 |
|
| 624 |
self.handler.consume(item)?; |
| 625 |
} |
| 626 |
|
| 627 |
Ok(false) |
| 628 |
} |
| 629 |
|
| 630 |
// Caller will try to write `outbound` to associated connection, queuing any data that can't be transmitted immediately. |
| 631 |
fn flush_outbound(&mut self, outbound: &mut sys::ConnectionBuffer) -> Result<()> { |
| 632 |
debug!("flush_outbound: {:?}", outbound.buf); |
| 633 |
|
| 634 |
// Repeatedly grab outgoing items from the handler, passing each to `encode` for serialization into `outbound`. |
| 635 |
while let Some(mut item) = self.handler.produce()? { |
| 636 |
let handle = if item.has_associated_handle() { |
| 637 |
#[allow(unused_mut)] |
| 638 |
let mut handle = item.take_handle(); |
| 639 |
// On Windows, the handle is transferred by duplicating it into the target remote process. |
| 640 |
#[cfg(windows)] |
| 641 |
unsafe { |
| 642 |
item.set_remote_handle(handle.send_to_target()?); |
| 643 |
} |
| 644 |
Some(handle) |
| 645 |
} else { |
| 646 |
None |
| 647 |
}; |
| 648 |
|
| 649 |
self.codec.encode(item, &mut outbound.buf)?; |
| 650 |
if let Some(handle) = handle { |
| 651 |
// `outbound` retains ownership of the handle until the associated |
| 652 |
// encoded item in `outbound.buf` is sent to the remote process. |
| 653 |
outbound.push_handle(handle); |
| 654 |
} |
| 655 |
} |
| 656 |
Ok(()) |
| 657 |
} |
| 658 |
} |
| 659 |
|
| 660 |
struct FramedDriver<T: Handler> { |
| 661 |
codec: LengthDelimitedCodec<T::Out, T::In>, |
| 662 |
handler: T, |
| 663 |
} |
| 664 |
|
| 665 |
impl<T: Handler> FramedDriver<T> { |
| 666 |
fn new(handler: T) -> FramedDriver<T> { |
| 667 |
FramedDriver { |
| 668 |
codec: Default::default(), |
| 669 |
handler, |
| 670 |
} |
| 671 |
} |
| 672 |
} |
| 673 |
|
| 674 |
#[derive(Debug)] |
| 675 |
pub struct EventLoopThread { |
| 676 |
thread: Option<thread::JoinHandle<Result<()>>>, |
| 677 |
name: String, |
| 678 |
handle: EventLoopHandle, |
| 679 |
} |
| 680 |
|
| 681 |
impl EventLoopThread { |
| 682 |
pub fn new<F1, F2>( |
| 683 |
name: String, |
| 684 |
stack_size: Option<usize>, |
| 685 |
after_start: F1, |
| 686 |
before_stop: F2, |
| 687 |
) -> Result<Self> |
| 688 |
where |
| 689 |
F1: Fn() + Send + 'static, |
| 690 |
F2: Fn() + Send + 'static, |
| 691 |
{ |
| 692 |
let mut event_loop = EventLoop::new(name.clone())?; |
| 693 |
let handle = event_loop.handle(); |
| 694 |
|
| 695 |
let builder = thread::Builder::new() |
| 696 |
.name(name.clone()) |
| 697 |
.stack_size(stack_size.unwrap_or(64 * 4096)); |
| 698 |
|
| 699 |
let thread = builder.spawn(move || { |
| 700 |
trace!("{}: event loop thread enter", event_loop.name); |
| 701 |
after_start(); |
| 702 |
let _thread_exit_guard = scopeguard::guard((), |_| before_stop()); |
| 703 |
|
| 704 |
let r = loop { |
| 705 |
let start = std::time::Instant::now(); |
| 706 |
let r = event_loop.poll(); |
| 707 |
trace!( |
| 708 |
"{}: event loop poll r={:?}, took={}μs", |
| 709 |
event_loop.name, |
| 710 |
r, |
| 711 |
start.elapsed().as_micros() |
| 712 |
); |
| 713 |
match r { |
| 714 |
Ok(true) => continue, |
| 715 |
_ => break r, |
| 716 |
} |
| 717 |
}; |
| 718 |
|
| 719 |
trace!("{}: event loop thread exit", event_loop.name); |
| 720 |
r.map(|_| ()) |
| 721 |
})?; |
| 722 |
|
| 723 |
Ok(EventLoopThread { |
| 724 |
thread: Some(thread), |
| 725 |
name, |
| 726 |
handle, |
| 727 |
}) |
| 728 |
} |
| 729 |
|
| 730 |
pub fn handle(&self) -> &EventLoopHandle { |
| 731 |
&self.handle |
| 732 |
} |
| 733 |
} |
| 734 |
|
| 735 |
impl Drop for EventLoopThread { |
| 736 |
// Shut down event loop and executor thread. Blocks until complete. |
| 737 |
fn drop(&mut self) { |
| 738 |
trace!("{}: EventLoopThread shutdown", self.name); |
| 739 |
if let Err(e) = self.handle.shutdown() { |
| 740 |
debug!("{}: initiating shutdown failed: {:?}", self.name, e); |
| 741 |
} |
| 742 |
let thread = self.thread.take().expect("event loop thread"); |
| 743 |
if let Err(e) = thread.join() { |
| 744 |
error!("{}: EventLoopThread failed: {:?}", self.name, e); |
| 745 |
} |
| 746 |
trace!("{}: EventLoopThread shutdown done", self.name); |
| 747 |
} |
| 748 |
} |
| 749 |
|
| 750 |
#[cfg(test)] |
| 751 |
mod test { |
| 752 |
use serde_derive::{Deserialize, Serialize}; |
| 753 |
|
| 754 |
use super::*; |
| 755 |
|
| 756 |
#[derive(Debug, Serialize, Deserialize, PartialEq)] |
| 757 |
enum TestServerMessage { |
| 758 |
TestRequest, |
| 759 |
} |
| 760 |
impl AssociateHandleForMessage for TestServerMessage {} |
| 761 |
|
| 762 |
struct TestServerImpl {} |
| 763 |
|
| 764 |
impl Server for TestServerImpl { |
| 765 |
type ServerMessage = TestServerMessage; |
| 766 |
type ClientMessage = TestClientMessage; |
| 767 |
|
| 768 |
fn process(&mut self, req: Self::ServerMessage) -> Self::ClientMessage { |
| 769 |
assert_eq!(req, TestServerMessage::TestRequest); |
| 770 |
TestClientMessage::TestResponse |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
#[derive(Debug, Serialize, Deserialize, PartialEq)] |
| 775 |
enum TestClientMessage { |
| 776 |
TestResponse, |
| 777 |
} |
| 778 |
|
| 779 |
impl AssociateHandleForMessage for TestClientMessage {} |
| 780 |
|
| 781 |
struct TestClientImpl {} |
| 782 |
|
| 783 |
impl Client for TestClientImpl { |
| 784 |
type ServerMessage = TestServerMessage; |
| 785 |
type ClientMessage = TestClientMessage; |
| 786 |
} |
| 787 |
|
| 788 |
fn init() { |
| 789 |
let _ = env_logger::builder().is_test(true).try_init(); |
| 790 |
} |
| 791 |
|
| 792 |
fn setup() -> ( |
| 793 |
EventLoopThread, |
| 794 |
EventLoopThread, |
| 795 |
Proxy<TestServerMessage, TestClientMessage>, |
| 796 |
) { |
| 797 |
// Server setup and registration. |
| 798 |
let server = EventLoopThread::new("test-server".to_string(), None, || {}, || {}) |
| 799 |
.expect("server EventLoopThread"); |
| 800 |
let server_handle = server.handle(); |
| 801 |
|
| 802 |
let (server_pipe, client_pipe) = sys::make_pipe_pair().expect("server make_pipe_pair"); |
| 803 |
server_handle |
| 804 |
.bind_server(TestServerImpl {}, server_pipe) |
| 805 |
.expect("server bind_server"); |
| 806 |
|
| 807 |
// Client setup and registration. |
| 808 |
let client = EventLoopThread::new("test-client".to_string(), None, || {}, || {}) |
| 809 |
.expect("client EventLoopThread"); |
| 810 |
let client_handle = client.handle(); |
| 811 |
|
| 812 |
let client_pipe = unsafe { sys::Pipe::from_raw_handle(client_pipe) }; |
| 813 |
let client_proxy = client_handle |
| 814 |
.bind_client::<TestClientImpl>(client_pipe) |
| 815 |
.expect("client bind_client"); |
| 816 |
|
| 817 |
(server, client, client_proxy) |
| 818 |
} |
| 819 |
|
| 820 |
// Verify basic EventLoopThread functionality works. Create a server and client EventLoopThread, then send |
| 821 |
// a single message from the client to the server and wait for the expected response. |
| 822 |
#[test] |
| 823 |
fn basic() { |
| 824 |
init(); |
| 825 |
let (server, client, client_proxy) = setup(); |
| 826 |
|
| 827 |
// RPC message from client to server. |
| 828 |
let response = client_proxy.call(TestServerMessage::TestRequest); |
| 829 |
let response = response.expect("client response"); |
| 830 |
assert_eq!(response, TestClientMessage::TestResponse); |
| 831 |
|
| 832 |
// Explicit shutdown. |
| 833 |
drop(client); |
| 834 |
drop(server); |
| 835 |
} |
| 836 |
|
| 837 |
// Same as `basic`, but shut down server before client. |
| 838 |
#[test] |
| 839 |
fn basic_reverse_drop_order() { |
| 840 |
init(); |
| 841 |
let (server, client, client_proxy) = setup(); |
| 842 |
|
| 843 |
// RPC message from client to server. |
| 844 |
let response = client_proxy.call(TestServerMessage::TestRequest); |
| 845 |
let response = response.expect("client response"); |
| 846 |
assert_eq!(response, TestClientMessage::TestResponse); |
| 847 |
|
| 848 |
// Explicit shutdown. |
| 849 |
drop(server); |
| 850 |
drop(client); |
| 851 |
} |
| 852 |
|
| 853 |
#[test] |
| 854 |
fn dead_server() { |
| 855 |
init(); |
| 856 |
let (server, _client, client_proxy) = setup(); |
| 857 |
drop(server); |
| 858 |
|
| 859 |
let response = client_proxy.call(TestServerMessage::TestRequest); |
| 860 |
response.expect_err("sending on closed channel"); |
| 861 |
} |
| 862 |
|
| 863 |
#[test] |
| 864 |
fn dead_client() { |
| 865 |
init(); |
| 866 |
let (_server, client, client_proxy) = setup(); |
| 867 |
drop(client); |
| 868 |
|
| 869 |
let response = client_proxy.call(TestServerMessage::TestRequest); |
| 870 |
response.expect_err("sending on a closed channel"); |
| 871 |
} |
| 872 |
|
| 873 |
#[test] |
| 874 |
fn disconnected_handle() { |
| 875 |
init(); |
| 876 |
let server = EventLoopThread::new("test-server".to_string(), None, || {}, || {}) |
| 877 |
.expect("server EventLoopThread"); |
| 878 |
let server_handle = server.handle().clone(); |
| 879 |
drop(server); |
| 880 |
|
| 881 |
server_handle |
| 882 |
.shutdown() |
| 883 |
.expect_err("sending on closed channel"); |
| 884 |
} |
| 885 |
|
| 886 |
#[test] |
| 887 |
fn clone_after_drop() { |
| 888 |
init(); |
| 889 |
let (server, client, client_proxy) = setup(); |
| 890 |
drop(server); |
| 891 |
drop(client); |
| 892 |
|
| 893 |
let clone = client_proxy.clone(); |
| 894 |
let response = clone.call(TestServerMessage::TestRequest); |
| 895 |
response.expect_err("sending to a dropped ClientHandler"); |
| 896 |
} |
| 897 |
|
| 898 |
#[test] |
| 899 |
fn basic_event_loop_thread_callbacks() { |
| 900 |
init(); |
| 901 |
let (start_tx, start_rx) = mpsc::channel(); |
| 902 |
let (stop_tx, stop_rx) = mpsc::channel(); |
| 903 |
|
| 904 |
let elt = EventLoopThread::new( |
| 905 |
"test-thread-callbacks".to_string(), |
| 906 |
None, |
| 907 |
move || start_tx.send(()).unwrap(), |
| 908 |
move || stop_tx.send(()).unwrap(), |
| 909 |
) |
| 910 |
.expect("server EventLoopThread"); |
| 911 |
|
| 912 |
start_rx.recv().expect("after_start callback done"); |
| 913 |
|
| 914 |
drop(elt); |
| 915 |
|
| 916 |
stop_rx.recv().expect("before_stop callback done"); |
| 917 |
} |
| 918 |
} |