| 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 crossbeam_queue::ArrayQueue; |
| 7 |
use mio::Token; |
| 8 |
use std::cell::UnsafeCell; |
| 9 |
use std::collections::VecDeque; |
| 10 |
use std::io::{self, Error, ErrorKind, Result}; |
| 11 |
use std::marker::PhantomPinned; |
| 12 |
use std::mem::ManuallyDrop; |
| 13 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 14 |
use std::sync::{Arc, Weak}; |
| 15 |
|
| 16 |
use crate::ipccore::EventLoopHandle; |
| 17 |
|
| 18 |
// This provides a safe-ish method for a thread to allocate |
| 19 |
// stack storage space for a result, then pass a (wrapped) |
| 20 |
// pointer to that location to another thread via |
| 21 |
// a CompletionWriter to eventually store a result into. |
| 22 |
struct Completion<T> { |
| 23 |
item: UnsafeCell<Option<T>>, |
| 24 |
writer: AtomicBool, |
| 25 |
_pin: PhantomPinned, // disable rustc's no-alias |
| 26 |
} |
| 27 |
|
| 28 |
impl<T> Completion<T> { |
| 29 |
fn new() -> Self { |
| 30 |
Completion { |
| 31 |
item: UnsafeCell::new(None), |
| 32 |
writer: AtomicBool::new(false), |
| 33 |
_pin: PhantomPinned, |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
// Wait until the writer completes, then return the result. |
| 38 |
// This is intended to be a single-use function, once the writer |
| 39 |
// has completed any further attempts to wait will return None. |
| 40 |
fn wait(&self) -> Option<T> { |
| 41 |
// Wait for the writer to complete or be dropped. |
| 42 |
while self.writer.load(Ordering::Acquire) { |
| 43 |
std::thread::park(); |
| 44 |
} |
| 45 |
unsafe { (*self.item.get()).take() } |
| 46 |
} |
| 47 |
|
| 48 |
// Create a writer for the other thread to store the |
| 49 |
// expected result into. |
| 50 |
fn writer(&self) -> CompletionWriter<T> { |
| 51 |
assert!(!self.writer.load(Ordering::Relaxed)); |
| 52 |
self.writer.store(true, Ordering::Release); |
| 53 |
CompletionWriter { |
| 54 |
ptr: self as *const _ as *mut _, |
| 55 |
waiter: std::thread::current(), |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl<T> Drop for Completion<T> { |
| 61 |
fn drop(&mut self) { |
| 62 |
// Wait for the outstanding writer to complete before |
| 63 |
// dropping, since the CompletionWriter references |
| 64 |
// memory owned by this object. |
| 65 |
while self.writer.load(Ordering::Acquire) { |
| 66 |
std::thread::park(); |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
struct CompletionWriter<T> { |
| 72 |
ptr: *mut Completion<T>, // Points to a Completion on another thread's stack |
| 73 |
waiter: std::thread::Thread, // Identifies thread waiting for completion |
| 74 |
} |
| 75 |
|
| 76 |
impl<T> CompletionWriter<T> { |
| 77 |
fn set(self, value: T) { |
| 78 |
// Store the result into the Completion's memory. |
| 79 |
// Since `set` consumes `self`, rely on `Drop` to |
| 80 |
// mark the writer as done and wake the Completion's |
| 81 |
// thread. |
| 82 |
unsafe { |
| 83 |
assert!((*self.ptr).writer.load(Ordering::Relaxed)); |
| 84 |
*(*self.ptr).item.get() = Some(value); |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
impl<T> Drop for CompletionWriter<T> { |
| 90 |
fn drop(&mut self) { |
| 91 |
// Mark writer as complete - if `set` was not called, |
| 92 |
// the waiter will receive `None`. |
| 93 |
unsafe { |
| 94 |
(*self.ptr).writer.store(false, Ordering::Release); |
| 95 |
} |
| 96 |
// Wake the Completion's thread. |
| 97 |
self.waiter.unpark(); |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
// Safety: CompletionWriter holds a pointer to a Completion |
| 102 |
// residing on another thread's stack. The Completion always |
| 103 |
// waits for an outstanding writer if present, and CompletionWriter |
| 104 |
// releases the waiter and wakes the Completion's thread on drop, |
| 105 |
// so this pointer will always be live for the duration of a |
| 106 |
// CompletionWriter. |
| 107 |
unsafe impl<T> Send for CompletionWriter<T> {} |
| 108 |
|
| 109 |
// RPC message handler. Implemented by ClientHandler (for Client) |
| 110 |
// and ServerHandler (for Server). |
| 111 |
pub(crate) trait Handler { |
| 112 |
type In; |
| 113 |
type Out; |
| 114 |
|
| 115 |
// Consume a request |
| 116 |
fn consume(&mut self, request: Self::In) -> Result<()>; |
| 117 |
|
| 118 |
// Produce a response |
| 119 |
fn produce(&mut self) -> Result<Option<Self::Out>>; |
| 120 |
} |
| 121 |
|
| 122 |
// Client RPC definition. This supplies the expected message |
| 123 |
// request and response types. |
| 124 |
pub trait Client { |
| 125 |
type ServerMessage; |
| 126 |
type ClientMessage; |
| 127 |
} |
| 128 |
|
| 129 |
// Server RPC definition. This supplies the expected message |
| 130 |
// request and response types. `process` is passed inbound RPC |
| 131 |
// requests by the ServerHandler to be responded to by the server. |
| 132 |
pub trait Server { |
| 133 |
type ServerMessage; |
| 134 |
type ClientMessage; |
| 135 |
|
| 136 |
fn process(&mut self, req: Self::ServerMessage) -> Self::ClientMessage; |
| 137 |
} |
| 138 |
|
| 139 |
// RPC Client Proxy implementation. |
| 140 |
type ProxyRequest<Request, Response> = (Request, CompletionWriter<Response>); |
| 141 |
|
| 142 |
// RPC Proxy that may be `clone`d for use by multiple owners/threads. |
| 143 |
// A Proxy `call` arranges for the supplied request to be transmitted |
| 144 |
// to the associated Server via RPC and blocks awaiting the response |
| 145 |
// via the associated `Completion`. |
| 146 |
// A ClientHandler normally lives until the last Proxy is dropped, but if the ClientHandler |
| 147 |
// encounters an internal error, `requests` will fail to upgrade, allowing |
| 148 |
// the proxy to report an error. |
| 149 |
#[derive(Debug)] |
| 150 |
pub struct Proxy<Request, Response> { |
| 151 |
handle: Option<(EventLoopHandle, Token)>, |
| 152 |
requests: ManuallyDrop<RequestQueueSender<ProxyRequest<Request, Response>>>, |
| 153 |
} |
| 154 |
|
| 155 |
impl<Request, Response> Proxy<Request, Response> { |
| 156 |
fn new(requests: RequestQueueSender<ProxyRequest<Request, Response>>) -> Self { |
| 157 |
Self { |
| 158 |
handle: None, |
| 159 |
requests: ManuallyDrop::new(requests), |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
pub fn call(&self, request: Request) -> Result<Response> { |
| 164 |
let response = Completion::new(); |
| 165 |
self.requests.push((request, response.writer()))?; |
| 166 |
self.wake_connection(); |
| 167 |
match response.wait() { |
| 168 |
Some(resp) => Ok(resp), |
| 169 |
None => Err(Error::new(ErrorKind::Other, "proxy recv error")), |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
pub(crate) fn connect_event_loop(&mut self, handle: EventLoopHandle, token: Token) { |
| 174 |
self.handle = Some((handle, token)); |
| 175 |
} |
| 176 |
|
| 177 |
fn wake_connection(&self) { |
| 178 |
let (handle, token) = self |
| 179 |
.handle |
| 180 |
.as_ref() |
| 181 |
.expect("proxy not connected to event loop"); |
| 182 |
handle.wake_connection(*token); |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
impl<Request, Response> Clone for Proxy<Request, Response> { |
| 187 |
fn clone(&self) -> Self { |
| 188 |
let mut clone = Self::new((*self.requests).clone()); |
| 189 |
let (handle, token) = self |
| 190 |
.handle |
| 191 |
.as_ref() |
| 192 |
.expect("proxy not connected to event loop"); |
| 193 |
clone.connect_event_loop(handle.clone(), *token); |
| 194 |
clone |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
impl<Request, Response> Drop for Proxy<Request, Response> { |
| 199 |
fn drop(&mut self) { |
| 200 |
trace!("Proxy drop, waking EventLoop"); |
| 201 |
// Must drop `requests` before waking the connection, otherwise |
| 202 |
// the wake may be processed before the (last) weak reference is |
| 203 |
// dropped. |
| 204 |
let last_proxy = self.requests.live_proxies(); |
| 205 |
unsafe { |
| 206 |
ManuallyDrop::drop(&mut self.requests); |
| 207 |
} |
| 208 |
if last_proxy == 1 && self.handle.is_some() { |
| 209 |
self.wake_connection() |
| 210 |
} |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
const RPC_CLIENT_INITIAL_PROXIES: usize = 32; // Initial proxy pre-allocation per client. |
| 215 |
|
| 216 |
// Client-specific Handler implementation. |
| 217 |
// The IPC EventLoop Driver calls this to execute client-specific |
| 218 |
// RPC handling. Serialized messages sent via a Proxy are queued |
| 219 |
// for transmission when `produce` is called. |
| 220 |
// Deserialized messages are passed via `consume` to |
| 221 |
// trigger response completion by sending the response via a channel |
| 222 |
// connected to a ProxyResponse. |
| 223 |
pub(crate) struct ClientHandler<C: Client> { |
| 224 |
in_flight: VecDeque<CompletionWriter<C::ClientMessage>>, |
| 225 |
requests: Arc<RequestQueue<ProxyRequest<C::ServerMessage, C::ClientMessage>>>, |
| 226 |
} |
| 227 |
|
| 228 |
impl<C: Client> ClientHandler<C> { |
| 229 |
fn new( |
| 230 |
requests: Arc<RequestQueue<ProxyRequest<C::ServerMessage, C::ClientMessage>>>, |
| 231 |
) -> ClientHandler<C> { |
| 232 |
ClientHandler::<C> { |
| 233 |
in_flight: VecDeque::with_capacity(RPC_CLIENT_INITIAL_PROXIES), |
| 234 |
requests, |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
impl<C: Client> Handler for ClientHandler<C> { |
| 240 |
type In = C::ClientMessage; |
| 241 |
type Out = C::ServerMessage; |
| 242 |
|
| 243 |
fn consume(&mut self, response: Self::In) -> Result<()> { |
| 244 |
trace!("ClientHandler::consume"); |
| 245 |
if let Some(response_writer) = self.in_flight.pop_front() { |
| 246 |
response_writer.set(response); |
| 247 |
} else { |
| 248 |
return Err(Error::new(ErrorKind::Other, "request/response mismatch")); |
| 249 |
} |
| 250 |
|
| 251 |
Ok(()) |
| 252 |
} |
| 253 |
|
| 254 |
fn produce(&mut self) -> Result<Option<Self::Out>> { |
| 255 |
trace!("ClientHandler::produce"); |
| 256 |
|
| 257 |
// If the weak count is zero, no proxies are attached and |
| 258 |
// no further proxies can be attached since every proxy |
| 259 |
// after the initial one is cloned from an existing instance. |
| 260 |
self.requests.check_live_proxies()?; |
| 261 |
// Try to get a new message |
| 262 |
match self.requests.pop() { |
| 263 |
Some((request, response_writer)) => { |
| 264 |
trace!(" --> received request"); |
| 265 |
self.in_flight.push_back(response_writer); |
| 266 |
Ok(Some(request)) |
| 267 |
} |
| 268 |
None => { |
| 269 |
trace!(" --> no request"); |
| 270 |
Ok(None) |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
#[derive(Debug)] |
| 277 |
pub(crate) struct RequestQueue<T> { |
| 278 |
queue: ArrayQueue<T>, |
| 279 |
} |
| 280 |
|
| 281 |
impl<T> RequestQueue<T> { |
| 282 |
pub(crate) fn new(size: usize) -> Self { |
| 283 |
RequestQueue { |
| 284 |
queue: ArrayQueue::new(size), |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
pub(crate) fn pop(&self) -> Option<T> { |
| 289 |
self.queue.pop() |
| 290 |
} |
| 291 |
|
| 292 |
pub(crate) fn new_sender(self: &Arc<Self>) -> RequestQueueSender<T> { |
| 293 |
RequestQueueSender { |
| 294 |
inner: Arc::downgrade(self), |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
pub(crate) fn check_live_proxies(self: &Arc<Self>) -> Result<()> { |
| 299 |
if Arc::weak_count(self) == 0 { |
| 300 |
return Err(io::ErrorKind::ConnectionAborted.into()); |
| 301 |
} |
| 302 |
Ok(()) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
pub(crate) struct RequestQueueSender<T> { |
| 307 |
inner: Weak<RequestQueue<T>>, |
| 308 |
} |
| 309 |
|
| 310 |
impl<T> RequestQueueSender<T> { |
| 311 |
pub(crate) fn push(&self, request: T) -> Result<()> { |
| 312 |
if let Some(consumer) = self.inner.upgrade() { |
| 313 |
if consumer.queue.push(request).is_err() { |
| 314 |
debug!("Proxy[{:p}]: call failed - CH::requests full", self); |
| 315 |
return Err(io::ErrorKind::ConnectionAborted.into()); |
| 316 |
} |
| 317 |
return Ok(()); |
| 318 |
} |
| 319 |
debug!("Proxy[{:p}]: call failed - CH::requests dropped", self); |
| 320 |
Err(Error::new(ErrorKind::Other, "proxy send error")) |
| 321 |
} |
| 322 |
|
| 323 |
pub(crate) fn live_proxies(&self) -> usize { |
| 324 |
Weak::weak_count(&self.inner) |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
impl<T> Clone for RequestQueueSender<T> { |
| 329 |
fn clone(&self) -> Self { |
| 330 |
Self { |
| 331 |
inner: self.inner.clone(), |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
impl<T> std::fmt::Debug for RequestQueueSender<T> { |
| 337 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 338 |
f.debug_struct("RequestQueueProducer") |
| 339 |
.field("inner", &self.inner.as_ptr()) |
| 340 |
.finish() |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
#[allow(clippy::type_complexity)] |
| 345 |
pub(crate) fn make_client<C: Client>( |
| 346 |
) -> Result<(ClientHandler<C>, Proxy<C::ServerMessage, C::ClientMessage>)> { |
| 347 |
let requests = Arc::new(RequestQueue::new(RPC_CLIENT_INITIAL_PROXIES)); |
| 348 |
let proxy_req = requests.new_sender(); |
| 349 |
let handler = ClientHandler::new(requests); |
| 350 |
|
| 351 |
Ok((handler, Proxy::new(proxy_req))) |
| 352 |
} |
| 353 |
|
| 354 |
// Server-specific Handler implementation. |
| 355 |
// The IPC EventLoop Driver calls this to execute server-specific |
| 356 |
// RPC handling. Deserialized messages are passed via `consume` to the |
| 357 |
// associated `server` for processing. Server responses are then queued |
| 358 |
// for RPC to the associated client when `produce` is called. |
| 359 |
pub(crate) struct ServerHandler<S: Server> { |
| 360 |
server: S, |
| 361 |
in_flight: VecDeque<S::ClientMessage>, |
| 362 |
} |
| 363 |
|
| 364 |
impl<S: Server> Handler for ServerHandler<S> { |
| 365 |
type In = S::ServerMessage; |
| 366 |
type Out = S::ClientMessage; |
| 367 |
|
| 368 |
fn consume(&mut self, message: Self::In) -> Result<()> { |
| 369 |
trace!("ServerHandler::consume"); |
| 370 |
let response = self.server.process(message); |
| 371 |
self.in_flight.push_back(response); |
| 372 |
Ok(()) |
| 373 |
} |
| 374 |
|
| 375 |
fn produce(&mut self) -> Result<Option<Self::Out>> { |
| 376 |
trace!("ServerHandler::produce"); |
| 377 |
|
| 378 |
// Return the ready response |
| 379 |
match self.in_flight.pop_front() { |
| 380 |
Some(res) => { |
| 381 |
trace!(" --> received response"); |
| 382 |
Ok(Some(res)) |
| 383 |
} |
| 384 |
None => { |
| 385 |
trace!(" --> no response ready"); |
| 386 |
Ok(None) |
| 387 |
} |
| 388 |
} |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
const RPC_SERVER_INITIAL_CLIENTS: usize = 32; // Initial client allocation per server. |
| 393 |
|
| 394 |
pub(crate) fn make_server<S: Server>(server: S) -> ServerHandler<S> { |
| 395 |
ServerHandler::<S> { |
| 396 |
server, |
| 397 |
in_flight: VecDeque::with_capacity(RPC_SERVER_INITIAL_CLIENTS), |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
#[cfg(test)] |
| 402 |
mod test { |
| 403 |
use super::*; |
| 404 |
|
| 405 |
#[test] |
| 406 |
fn basic() { |
| 407 |
let queue = Arc::new(RequestQueue::new(1)); |
| 408 |
let producer = queue.new_sender(); |
| 409 |
assert!(queue.pop().is_none()); |
| 410 |
producer.push(1).unwrap(); |
| 411 |
assert!(queue.pop().is_some()); |
| 412 |
assert!(queue.pop().is_none()); |
| 413 |
} |
| 414 |
|
| 415 |
#[test] |
| 416 |
fn queue_dropped() { |
| 417 |
let queue = Arc::new(RequestQueue::new(1)); |
| 418 |
let producer = queue.new_sender(); |
| 419 |
drop(queue); |
| 420 |
assert!(producer.push(1).is_err()); |
| 421 |
} |
| 422 |
|
| 423 |
#[test] |
| 424 |
fn queue_full() { |
| 425 |
let queue = Arc::new(RequestQueue::new(1)); |
| 426 |
let producer = queue.new_sender(); |
| 427 |
producer.push(1).unwrap(); |
| 428 |
assert!(producer.push(2).is_err()); |
| 429 |
} |
| 430 |
|
| 431 |
#[test] |
| 432 |
fn queue_producer_clone() { |
| 433 |
let queue = Arc::new(RequestQueue::new(1)); |
| 434 |
let producer = queue.new_sender(); |
| 435 |
let producer2 = producer.clone(); |
| 436 |
producer.push(1).unwrap(); |
| 437 |
assert!(producer2.push(2).is_err()); |
| 438 |
} |
| 439 |
|
| 440 |
#[test] |
| 441 |
fn queue_producer_drop() { |
| 442 |
let queue = Arc::new(RequestQueue::new(1)); |
| 443 |
let producer = queue.new_sender(); |
| 444 |
let producer2 = producer.clone(); |
| 445 |
drop(producer); |
| 446 |
assert!(producer2.push(2).is_ok()); |
| 447 |
} |
| 448 |
|
| 449 |
#[test] |
| 450 |
fn queue_producer_weak() { |
| 451 |
let queue = Arc::new(RequestQueue::new(1)); |
| 452 |
let producer = queue.new_sender(); |
| 453 |
let producer2 = producer.clone(); |
| 454 |
drop(queue); |
| 455 |
assert!(producer2.push(2).is_err()); |
| 456 |
} |
| 457 |
|
| 458 |
#[test] |
| 459 |
fn queue_producer_shutdown() { |
| 460 |
let queue = Arc::new(RequestQueue::new(1)); |
| 461 |
let producer = queue.new_sender(); |
| 462 |
let producer2 = producer.clone(); |
| 463 |
producer.push(1).unwrap(); |
| 464 |
assert!(Arc::weak_count(&queue) == 2); |
| 465 |
drop(producer); |
| 466 |
assert!(Arc::weak_count(&queue) == 1); |
| 467 |
drop(producer2); |
| 468 |
assert!(Arc::weak_count(&queue) == 0); |
| 469 |
} |
| 470 |
} |