1
//! Lower level connection type based on nonblocking IO.
2
//!
3
//! This module defines [`NonblockingConnection`], which provides a nonblocking
4
//! wrapper around an underlying nonblocking stream,
5
//! [`WriteHandle`], which queues messages for a `NonblockingConnection`,
6
//! and [`EventLoop`], a trait wrapping access to an event loop
7
//! based on poll, select, kqueue, epoll, etc.
8
//!
9
//! `NonblockingConnection` is used directly in `RpcPoll` if the user wants to provide their own
10
//! event loop, or wrapped in a [`BlockingConnection`](super::BlockingConnection)
11
//! if this RPC library is providing its own event loop.
12

            
13
use crate::{
14
    msgs::{request::ValidatedRequest, response::UnparsedResponse},
15
    util::define_from_for_arc,
16
};
17
use std::{
18
    io::{self, Read as _, Write as _},
19
    mem::{self},
20
    sync::{Arc, Mutex},
21
};
22

            
23
#[cfg(unix)]
24
use std::os::fd::BorrowedFd as BorrowedOsHandle;
25
#[cfg(windows)]
26
use std::os::windows::io::BorrowedSocket as BorrowedOsHandle;
27

            
28
use super::{Stream, retry_eintr};
29

            
30
/// A lower-level implementation of nonblocking IO for an open stream to the RPC server.
31
///
32
/// Unlike [`BlockingConnection`], this type _does not_ handle the IO event polling loops:
33
/// the caller is required to provide their own.
34
///
35
/// [`BlockingConnection`]: super::BlockingConnection
36
#[derive(derive_more::Debug)]
37
pub(crate) struct NonblockingConnection {
38
    /// A write handle used to write onto this stream.
39
    #[debug(ignore)]
40
    write_handle: WriteHandle,
41

            
42
    /// A buffer of incoming messages (possibly partial) from the RPC server.
43
    //
44
    // TODO: Consider using a VecDeque or BytesMut or such.
45
    read_buf: Vec<u8>,
46

            
47
    /// The underlying nonblocking stream.
48
    #[debug(ignore)]
49
    stream: Box<dyn Stream>,
50
}
51

            
52
/// A return value from [`NonblockingConnection::interact_once`].
53
#[derive(Debug, Clone)]
54
pub(crate) enum PollStatus {
55
    /// The stream is closed.
56
    Closed,
57

            
58
    /// No progress can be made until the stream is available for further IO.
59
    WouldBlock,
60

            
61
    /// We have received a message.
62
    Msg(UnparsedResponse),
63
}
64

            
65
/// Possible return value from [`NonblockingConnection::flush_queue()`] or [`WriteHandle::send_valid()`].
66
#[derive(Debug)]
67
pub(crate) enum WriteStatus {
68
    /// We have written the data.
69
    Written,
70

            
71
    /// We are closing this connection; no data was written.
72
    Closing,
73
}
74

            
75
/// A handle that can be used to queue outgoing messages for a nonblocking stream.
76
///
77
/// Note that queueing a message has no effect unless some party is polling the stream,
78
/// either with [`BlockingConnection::interact()`], or [`NonblockingConnection::interact_once()`].
79
///
80
/// [`BlockingConnection::interact()`]: super::BlockingConnection::interact
81
#[derive(Clone, Debug)]
82
pub(crate) struct WriteHandle {
83
    /// The actual implementation type for this writer.
84
    inner: Arc<Mutex<WriteHandleImpl>>,
85
}
86

            
87
impl WriteHandle {
88
    /// Queue an outgoing message for a nonblocking stream.
89
2094
    pub(crate) fn send_valid(&self, msg: &ValidatedRequest) -> io::Result<WriteStatus> {
90
        let mut w: std::sync::MutexGuard<'_, WriteHandleImpl> =
91
2094
            self.inner.lock().expect("Poisoned lock");
92
2094
        let WriteState::Writing(buf) = &mut w.write_buf else {
93
            return Ok(WriteStatus::Closing);
94
        };
95

            
96
2094
        let was_empty = buf.is_empty();
97
2094
        buf.extend_from_slice(msg.as_ref().as_bytes());
98

            
99
        // See TOCTOU note on `WriteHandleImpl`:
100
        // we need to change our interest while we are holding the
101
        // above mutex.
102
2094
        if was_empty {
103
405
            w.event_loop.start_writing()?;
104
1689
        }
105
2094
        Ok(WriteStatus::Written)
106
2094
    }
107

            
108
    /// Initiate a shutdown on this writer.
109
    ///
110
    ///
111
    pub(crate) fn begin_closing(&self) -> io::Result<()> {
112
        let mut w = self.inner.lock().expect("Poisoned lock");
113

            
114
        w.write_buf = WriteState::Closing;
115

            
116
        // See TOCTOU note on `WriteHandleImpl`:
117
        // we need to change our interest while we are holding the
118
        // above mutex.
119
        //
120
        // We 'start writing' here to ensure that any existing loop wakes up and notices that
121
        // this connection is shutting down.
122
        w.event_loop.start_writing()?;
123
        Ok(())
124
    }
125
}
126

            
127
/// An error that has occurred while sending a request.
128
#[derive(Clone, Debug, thiserror::Error)]
129
#[non_exhaustive]
130
pub enum SendRequestError {
131
    /// An IO error occurred while sending a request.
132
    #[error("Unable to wake poling loop")]
133
    Io(#[source] Arc<io::Error>),
134
    /// We found a problem in the JSON while sending a request.
135
    #[error("Invalid Json request")]
136
    InvalidRequest(#[from] crate::InvalidRequestError),
137
    /// Internal error while re-encoding request.  Should be impossible.
138
    #[error("Unable to re-encode request after parsing it‽")]
139
    ReEncode(#[source] Arc<serde_json::Error>),
140
}
141
define_from_for_arc!( io::Error => SendRequestError [Io] );
142

            
143
/// State object describing what we are doing
144
/// for the write side of a connection.
145
#[derive(Debug)]
146
enum WriteState {
147
    /// We're writing from a a buffer (if the buffer is nonempty).
148
    //
149
    // TODO: Consider using a VecDeque or BytesMut or such.
150
    Writing(Vec<u8>),
151

            
152
    /// We are planning to shut down the connection.
153
    ///
154
    /// No more data is allowed or will be written.
155
    Closing,
156
}
157

            
158
/// The inner implementation for [`WriteHandle`].
159
///
160
/// NOTE: We need to be careful to avoid TOCTOU problems with this type:
161
/// It would be bad if a writing thread said "now I care about write events",
162
/// and then the interactor checked the
163
/// buffer and found it empty, and only then did the writing thread add to the buffer.
164
///
165
/// To solve this, we put the `write_buf` and the `event_loop` behind the same lock:
166
/// While the interactor is checking the buffer, nobody is able to add to the buffer _or_ wake the
167
/// interactor.
168
#[derive(derive_more::Debug)]
169
struct WriteHandleImpl {
170
    /// An underlying buffer holding messages to be sent to the RPC server,
171
    /// or our shutdown status.
172
    write_buf: WriteState,
173

            
174
    /// The handle to use to wake the polling loop.
175
    #[debug(ignore)]
176
    event_loop: Box<dyn EventLoop>,
177
}
178

            
179
impl NonblockingConnection {
180
    /// Create a new `NonblockingConnection` from a provided [`EventLoop`] and [`Stream`].
181
7
    pub(crate) fn new(event_loop: Box<dyn EventLoop>, stream: Box<dyn Stream>) -> Self {
182
7
        Self {
183
7
            write_handle: WriteHandle {
184
7
                inner: Arc::new(Mutex::new(WriteHandleImpl {
185
7
                    write_buf: WriteState::Writing(Default::default()),
186
7
                    event_loop,
187
7
                })),
188
7
            },
189
7
            read_buf: Default::default(),
190
7
            stream,
191
7
        }
192
7
    }
193

            
194
    /// Return a reference to this connection as a mio source.
195
    ///
196
    /// Returns None if this is was not constructed with a mio stream,
197
    /// or if `downgrade_source` has been called.
198
131
    pub(super) fn as_mio_source(&mut self) -> Option<&mut dyn mio::event::Source> {
199
131
        self.stream.as_mut().as_mio_source()
200
131
    }
201

            
202
    /// Remove any mio wrappers from this connection.
203
    pub(super) fn downgrade_source(&mut self) {
204
        // We need this rigamarole because `self.stream = self.stream.remove_mio()`
205
        // gives a "can't move out of self.stream, which is behind a mutable reference"
206
        // error.
207
        let mut s: Box<dyn Stream> = Box::new(std::io::empty());
208
        mem::swap(&mut s, &mut self.stream);
209
        self.stream = s.remove_mio();
210
    }
211

            
212
    /// Return a new [`WriteHandle`] that can be used to queue messages to be sent via this connection.
213
6
    pub(crate) fn writer(&self) -> WriteHandle {
214
6
        self.write_handle.clone()
215
6
    }
216

            
217
    /// Try to return an OS-level handle for use with this connection.
218
    ///
219
    /// This is an fd on unix and a SOCKET on windows.
220
    pub(crate) fn try_as_handle(&self) -> io::Result<BorrowedOsHandle<'_>> {
221
        self.stream.try_as_handle()
222
    }
223

            
224
    /// Replace the current `EventLoop` this [`NonblockingConnection`].
225
    ///
226
    /// This should only be done while nothing else is interacting with the stream or the waker.
227
    pub(crate) fn replace_event_loop_handle(&mut self, new_event_loop_handle: Box<dyn EventLoop>) {
228
        let mut h = self.write_handle.inner.lock().expect("Poisoned lock");
229
        h.event_loop = new_event_loop_handle;
230
    }
231

            
232
    /// Return true iff this [`NonblockingConnection`] currently wants to write
233
    ///
234
    /// See [`RpcPoll::wants_to_write`] and [`EventLoop`]
235
    /// for the semantics.
236
    ///
237
    /// [`RpcPoll::wants_to_write`]: crate::RpcPoll::wants_to_write
238
    /// [`EventLoop`]: crate::EventLoop
239
127
    pub(crate) fn wants_to_write(&self) -> bool {
240
127
        self.has_data_to_write()
241
127
    }
242

            
243
    /// Try to exchange messages with the RPC server.
244
    ///
245
    /// If the stream proves to be closed, returns [`PollStatus::Closed`].
246
    ///
247
    /// If a message is available, returns [`PollStatus::Msg`].
248
    /// (Note that a message may be available in the internal buffer here
249
    /// even if try_reading is false.)
250
    ///
251
    /// If no message is available, return [`PollStatus::WouldBlock`].
252
4220
    pub(crate) fn interact_once(&mut self) -> io::Result<PollStatus> {
253
        use io::ErrorKind::WouldBlock;
254

            
255
4220
        if let Some(msg) = self.extract_msg()? {
256
3724
            return Ok(PollStatus::Msg(msg));
257
496
        }
258

            
259
496
        match self.flush_queue() {
260
            Ok(WriteStatus::Closing) => return Ok(PollStatus::Closed),
261
495
            Ok(WriteStatus::Written) => {}
262
1
            Err(e) if e.kind() == WouldBlock => {}
263
            Err(e) => return Err(e),
264
        }
265

            
266
496
        match self.read_msg() {
267
368
            Ok(Some(msg)) => return Ok(PollStatus::Msg(msg)),
268
            Ok(None) => return Ok(PollStatus::Closed),
269
128
            Err(e) if e.kind() == WouldBlock => {}
270
1
            Err(e) => return Err(e),
271
        }
272

            
273
127
        Ok(PollStatus::WouldBlock)
274
4220
    }
275

            
276
    /// Internal helper: Try to get a buffered message out of our `read_buf`.
277
    ///
278
    /// Returns Ok(None) if there are no complete lines in the buffer.
279
    ///
280
    /// If there is a line, but it is not valid UTF-8, returns an error and discards the line.
281
5085
    fn extract_msg(&mut self) -> io::Result<Option<UnparsedResponse>> {
282
        // Look for an eol within the buffer.
283
5085
        let Some(eol_pos) = memchr::memchr(b'\n', &self.read_buf[..]) else {
284
993
            return Ok(None);
285
        };
286
        // Split off the part of the buffer ending with the EOF from the remainder.
287
4092
        let mut line = self.read_buf.split_off(eol_pos + 1);
288
        // Put the message in "line" and the remainder of the buffer in read_buf.
289
4092
        mem::swap(&mut line, &mut self.read_buf);
290
        // Try to convert the line to an UnparsedResponse.
291
4092
        match String::from_utf8(line) {
292
4092
            Ok(s) => Ok(Some(UnparsedResponse::new(s))),
293
            Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e)),
294
        }
295
5085
    }
296

            
297
    /// Internal helper: Return true if there is any outgoing data queued to be written.
298
127
    fn has_data_to_write(&self) -> bool {
299
127
        let w = self.write_handle.inner.lock().expect("Lock poisoned");
300
        // See TOCTOU note on WriteHandleImpl: Our rule is to check whether we have data to write
301
        // within the same lock used to hold the waker, so that we can't lose any data.
302
127
        match &w.write_buf {
303
127
            WriteState::Writing(b) => !b.is_empty(),
304
            WriteState::Closing => false,
305
        }
306
127
    }
307

            
308
    /// Helper: Try to get a message, reading into our read_buf as needed.
309
    ///
310
    /// (We don't use a BufReader here because
311
    /// its behavior with nonblocking IO is kind of underspecified.)
312
496
    fn read_msg(&mut self) -> io::Result<Option<UnparsedResponse>> {
313
        const READLEN: usize = 4096;
314
        loop {
315
865
            if let Some(msg) = self.extract_msg()? {
316
368
                return Ok(Some(msg));
317
497
            }
318

            
319
497
            let len_orig = self.read_buf.len();
320
            // TODO: Impose a maximum length?
321
497
            self.read_buf.resize(len_orig + READLEN, 0);
322
497
            let result = retry_eintr(|| self.stream.read(&mut self.read_buf[len_orig..]));
323
497
            match result {
324
                Ok(0) => return Ok(None),
325
                Ok(n) => {
326
369
                    self.read_buf.truncate(len_orig + n);
327
                }
328
                Err(e) => {
329
128
                    self.read_buf.truncate(len_orig);
330
128
                    return Err(e);
331
                }
332
            }
333
        }
334
496
    }
335

            
336
    /// Try to flush data from the underlying write buffer.
337
    ///
338
    /// Returns `Ok(Written)` only if all of the data is flushed, and the write buffer has become empty.
339
    ///
340
    /// Returns `Ok(Closing)` if we have been told to close the connection.
341
    ///
342
    /// Returns an error if the write failed, including with a `WouldBlock`.
343
496
    fn flush_queue(&mut self) -> io::Result<WriteStatus> {
344
496
        let mut w = self.write_handle.inner.lock().expect("Poisoned lock.");
345

            
346
        loop {
347
899
            let WriteState::Writing(buf) = &mut w.write_buf else {
348
                w.event_loop.stop_writing()?;
349
                return Ok(WriteStatus::Closing);
350
            };
351
899
            if buf.is_empty() {
352
495
                return Ok(WriteStatus::Written);
353
404
            }
354

            
355
404
            let n = retry_eintr(|| self.stream.write(buf))?;
356
403
            vec_pop_from_front(buf, n);
357

            
358
403
            if buf.is_empty() {
359
402
                w.event_loop.stop_writing()?;
360
1
            }
361

            
362
            // This is a no-op for the streams we support so far, but it could be necessary if
363
            // we support more kinds in the future.
364
403
            let () = retry_eintr(|| self.stream.flush())?;
365
        }
366
496
    }
367
}
368

            
369
/// Representation of an event loop that can watch a handle and arrange to call `poll`
370
///
371
/// Provided to the event-driven nonblocking RPC connection API,
372
/// by the user, via [`connect_polling`].
373
///
374
/// This is only used along with [`RpcPoll`]; if you aren't using that type,
375
/// you don't need to worry about this trait.
376
///
377
/// # Operating principles
378
///
379
/// The user code must implement an event loop,
380
/// which can monitor for handle readability/writeability.
381
///
382
/// The RPC library provides the user code with
383
/// the OS handle for the transport connection.
384
///
385
/// The RPC library always wants to read from the handle.
386
/// It informs the user code whether the RPC library wants to write to the handle.
387
///
388
/// When the handle is readable, or (if applicable) writeable,
389
/// the user code must call into the RPC library via [`RpcPoll::poll`]
390
/// so that the library can perform IO.
391
///
392
/// # Implementation strategies
393
///
394
/// The RPC library's API is designed to be easy to interface
395
/// to existing event loops.
396
///
397
/// ## Plumbing to using an existing event loop
398
///
399
/// With an existing event loop which is suitably reentrant across multiple threads,
400
/// or in single-threaded programs with an existing event loop:
401
///
402
///  * Call `connect_polling`; use `try_as_fd` or `try_as_socket`
403
///    on the returned `RpcPoll` to obtain the OS handle.
404
///  * Register the OS handle with the event loop,
405
///    and ask to be notified when the handle is readable.
406
///  * Implement `EventLoop::start_writing` and `EventLoop::stop_writing`:
407
///    `start_writing` should reregister the handle with the event loop
408
///    to request writeability notifications too;
409
///    `stop_writing` should stop writeability notifications.
410
///  * When notified that the handle is readable or writeable,
411
///    call [`RpcPoll::poll`].
412
///
413
/// Depending on the event loop's API, the type implementing `EventLoop`
414
/// might be a unit struct (if the event loop is global);
415
/// or it might be a handle onto the event loop,
416
/// or some kind of "event source" object if the event loop has those.
417
///
418
/// ## "Main thread only" event loops in multithreaded programs
419
///
420
/// Many real event loops have a "main thread",
421
/// and require all changes to OS handle interests to happen on that thread.
422
///
423
/// If you can't guarantee that all calls to `submit` will be made on the main thread,
424
/// you need to arrange that `start_writing` can add the writeability interest
425
/// even if another thread is currently blocked in the event loop waiting for IO events.
426
///
427
/// To achieve this:
428
///
429
///  * Use an inter-thread communication facility, such as an event loop "waker",
430
///    a self-pipe, or similar technique.  (We'll call this the "waker".)
431
///  * Entrol the receiving end of the waker in the event loop during setup.
432
///  * `EventLoop` contains just the sending handle of the waker,
433
///    not a reference to the real event loop.
434
///    `start_writing` notifies the waker.  `stop_writing` is a no-op.
435
///
436
/// When the event loop notifies your glue code (necessarily, on the main thread)
437
/// that the waker, or the RPC connection OS handle, is ready for IO:
438
///
439
///  * Repeatedly call `RpcPoll::poll` and dispatch any returned `Response`,
440
///    until it returns `WouldBlock`.
441
///  * Call `RpcPoll::wants_to_write` and adjust the RPC connection OS handle interest,
442
///    in the event loop.
443
///
444
/// (You can respond to all such wakeups with this identical, idempotent, response.)
445
///
446
/// # Single-threaded open-coded event loops
447
///
448
/// In a single-threaded program, with an open-coded event loop,
449
/// it is permissible to simply call `wants_to_write`
450
/// to determine the correct value for `pollfd.events`
451
/// (`POLLIN`, plus `POLLOUT` iff `wants_to_write`),
452
/// then `poll(2)`,
453
/// and `RpcPoll::poll` and/or `submit` after `poll(2)`.
454
///
455
/// You can pass an `EventLoop` which implements
456
/// `start_writing` and `stop_writing` as no-ops.
457
///
458
/// (This is because only `submit` can cause `wants_to_write` to change to `true`,
459
/// and if there is only one thread, you can know that you're not calling `submit`
460
/// between `wants_to_write` and `poll(2)`.)
461
///
462
/// # Detailed requirements and guarantees
463
///
464
/// Progress will only be made during calls to `poll`.
465
/// In particular, `submit` does not actually send the data.
466
///
467
/// The program should not sleep, without arranging that readability
468
/// and (as applicable) writeability of the RPC connection handle
469
/// will result in a wakeup.
470
///
471
/// `start_writing` must be effective right away,
472
/// without waiting for any other events:
473
/// if `submit` can be called while another thread
474
/// is in the program's event loop waiting for OS events,
475
/// user code implementing `start_writing` must
476
/// arrange to wake up the event loop if necessary,
477
/// so that writeability will result in a call to `poll`.
478
///
479
/// `start_writing` is only ever called from `submit`,
480
/// on the same thread.
481
///
482
/// `stop_writing` is only ever called from `RpcPoll::poll`,
483
/// on the same thread.
484
///
485
/// All changes to the value which would be returned from `wants_to_write`
486
/// are reflected in `start_writing` and `stop_writing`,
487
/// and vice versa.
488
///
489
/// It is OK to call `RpcPoll::poll` when the handle is not known to be ready;
490
/// `RpcPoll::poll` never blocks, and instead immediately returns `WouldBlock`.
491
/// (A loop which calls `RpcPoll::poll` should involve waiting for
492
/// appropriate readiness on the underling OS handle,
493
/// as the program would otherwise spin rather than wait.)
494
///
495
/// Immediately after creation, a connection made with `connect_polling`
496
/// is not interested in writing.
497
///
498
/// # Relationship to the synchronous API
499
///
500
/// It is also permissible to call the [`.execute()`](crate::RpcConn::execute)
501
/// family of methods on the `RpcConn` returned from `connect_polling`.
502
///
503
/// In this case, `start_writing` might be called
504
/// from `execute`, not just from `submit`.
505
///
506
/// [`RpcPoll`]: crate::RpcPoll
507
/// [`RpcPoll::poll`]: crate::RpcPoll::poll
508
/// [`connect_polling`]: crate::conn::RpcConnBuilder::connect_polling
509
//
510
// When the underlying IO loop is `mio`, this is a [`MioWaker`];
511
// otherwise, it is some user-provided type.
512
pub trait EventLoop: Send + Sync {
513
    /// Alert the polling thread that we are no longer interested in write events.
514
    ///
515
    /// In a user-provided `EventLoop`,
516
    /// this method will only be invoked from within [`RpcPoll::poll`](crate::RpcPoll::poll).
517
    fn stop_writing(&mut self) -> io::Result<()>;
518

            
519
    /// Alert the polling thread that we have become interested in write events.
520
    ///
521
    /// In a user-provided `EventLoop`,
522
    /// this method will only be invoked from within one of the `submit`, `execute`, or `shutdown` methods
523
    /// on [`RpcConn`](crate::RpcConn).
524
    fn start_writing(&mut self) -> io::Result<()>;
525
}
526

            
527
/// Remove n elements from the front of v.
528
///
529
/// # Panics
530
///
531
/// Panics if `n > v.len()`.
532
408
fn vec_pop_from_front(v: &mut Vec<u8>, n: usize) {
533
    // This returns an iterator, but we don't need to actually iterate over the elements.
534
    // The compiler appears to be smart enough to optimize it away.
535
    // (Cargo asm indicates that this optimizes down to a memmove.)
536
408
    v.drain(0..n);
537
408
}
538

            
539
#[cfg(test)]
540
mod test {
541
    // @@ begin test lint list maintained by maint/add_warning @@
542
    #![allow(clippy::bool_assert_comparison)]
543
    #![allow(clippy::clone_on_copy)]
544
    #![allow(clippy::dbg_macro)]
545
    #![allow(clippy::mixed_attributes_style)]
546
    #![allow(clippy::print_stderr)]
547
    #![allow(clippy::print_stdout)]
548
    #![allow(clippy::single_char_pattern)]
549
    #![allow(clippy::unwrap_used)]
550
    #![allow(clippy::unchecked_time_subtraction)]
551
    #![allow(clippy::useless_vec)]
552
    #![allow(clippy::needless_pass_by_value)]
553
    #![allow(clippy::string_slice)] // See arti#2571
554
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
555

            
556
    use assert_matches::assert_matches;
557
    use std::cmp::min;
558

            
559
    use super::*;
560

            
561
    impl super::PollStatus {
562
        fn unwrap_msg(self) -> UnparsedResponse {
563
            match self {
564
                PollStatus::Msg(msg) => msg,
565
                other => panic!("Wanted Msg; found {other:?}"),
566
            }
567
        }
568
    }
569

            
570
    #[derive(Default, Debug)]
571
    struct TestWaker {
572
        n_wakes: usize,
573
    }
574
    impl EventLoop for TestWaker {
575
        fn start_writing(&mut self) -> io::Result<()> {
576
            self.n_wakes += 1;
577
            Ok(())
578
        }
579
        fn stop_writing(&mut self) -> io::Result<()> {
580
            Ok(())
581
        }
582
    }
583

            
584
    // Helper: Simulates nonblocking IO.
585
    //
586
    // Has interior mutability so we can inspect it.
587
    #[derive(Default, Debug, Clone)]
588
    struct TestStream {
589
        inner: Arc<Mutex<TestStreamInner>>,
590
    }
591
    #[derive(Default, Debug, Clone)]
592
    struct TestStreamInner {
593
        // Bytes that we have _received_ from the client.
594
        received: Vec<u8>,
595
        // Bytes that we are _sending_ to the client.
596
        sending: Vec<u8>,
597
        receive_capacity: Option<usize>,
598
    }
599
    impl TestStream {
600
        fn push(&self, b: &[u8]) {
601
            self.inner.lock().unwrap().sending.extend_from_slice(b);
602
        }
603
        fn drain(&self, n: usize) -> Vec<u8> {
604
            let mut s = self.inner.lock().unwrap();
605
            let n = min(n, s.received.len());
606
            let mut v = vec![0_u8; n];
607
            v[..].copy_from_slice(&s.received[..n]);
608
            vec_pop_from_front(&mut s.received, n);
609
            v
610
        }
611
    }
612

            
613
    impl io::Read for TestStream {
614
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
615
            let mut s = self.inner.lock().unwrap();
616
            if s.sending.is_empty() {
617
                return Err(io::ErrorKind::WouldBlock.into());
618
            }
619

            
620
            let n_to_copy = min(s.sending.len(), buf.len());
621
            buf[..n_to_copy].copy_from_slice(&s.sending[..n_to_copy]);
622
            vec_pop_from_front(&mut s.sending, n_to_copy);
623
            Ok(n_to_copy)
624
        }
625
    }
626

            
627
    impl io::Write for TestStream {
628
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
629
            if buf.is_empty() {
630
                return Ok(0);
631
            }
632

            
633
            let mut s = self.inner.lock().unwrap();
634

            
635
            let n_to_copy = match s.receive_capacity {
636
                Some(0) => return Err(io::ErrorKind::WouldBlock.into()),
637
                Some(n) => min(n, buf.len()),
638
                None => buf.len(),
639
            };
640

            
641
            s.received.extend_from_slice(&buf[..n_to_copy]);
642
            if let Some(ref mut n) = s.receive_capacity {
643
                *n -= n_to_copy;
644
            }
645

            
646
            Ok(n_to_copy)
647
        }
648

            
649
        fn flush(&mut self) -> io::Result<()> {
650
            Ok(())
651
        }
652
    }
653
    impl Stream for TestStream {
654
        fn as_mio_source(&mut self) -> Option<&mut dyn mio::event::Source> {
655
            None
656
        }
657
        fn remove_mio(self: Box<Self>) -> Box<dyn Stream> {
658
            self
659
        }
660
        fn try_as_handle(&self) -> io::Result<BorrowedOsHandle<'_>> {
661
            Err(io::Error::from(io::ErrorKind::Other))
662
        }
663
    }
664

            
665
    fn assert_wants_rw(nb: &NonblockingConnection, r: &io::Result<PollStatus>) {
666
        assert_matches!(r, Ok(PollStatus::WouldBlock));
667
        assert_eq!(nb.wants_to_write(), true);
668
    }
669

            
670
    fn assert_wants_r_only(nb: &NonblockingConnection, r: &io::Result<PollStatus>) {
671
        assert_matches!(r, Ok(PollStatus::WouldBlock));
672
        assert_eq!(nb.wants_to_write(), false);
673
    }
674

            
675
    #[test]
676
    fn read_msg() {
677
        let test_stream = TestStream::default();
678
        let mut nbconn = NonblockingConnection::new(
679
            Box::new(TestWaker::default()),
680
            Box::new(test_stream.clone()),
681
        );
682

            
683
        // Try interacting with nothing to do.
684
        let r = nbconn.interact_once();
685
        assert_wants_r_only(&nbconn, &r);
686

            
687
        // Give it a partial message.
688
        test_stream.push(b"Hello world");
689
        let r = nbconn.interact_once();
690
        assert_wants_r_only(&nbconn, &r);
691

            
692
        // Finish the message.
693
        test_stream.push(b"\nAnd many happy");
694
        let r = nbconn.interact_once();
695
        assert_eq!(r.unwrap().unwrap_msg().as_str(), "Hello world\n");
696

            
697
        // Then it should block...
698
        let r = nbconn.interact_once();
699
        assert_wants_r_only(&nbconn, &r);
700

            
701
        // Finish two more messages, and leave a partial message.
702
        test_stream.push(b" returns\nof the day\nto you!");
703
        let r = nbconn.interact_once();
704
        assert_eq!(r.unwrap().unwrap_msg().as_str(), "And many happy returns\n");
705
        let r = nbconn.interact_once();
706
        assert_eq!(r.unwrap().unwrap_msg().as_str(), "of the day\n");
707
    }
708

            
709
    #[test]
710
    fn write_msg() {
711
        let test_stream = TestStream::default();
712
        let mut nbconn = NonblockingConnection::new(
713
            Box::new(TestWaker::default()),
714
            Box::new(test_stream.clone()),
715
        );
716
        let writer = nbconn.writer();
717

            
718
        // Make sure we can write in a nonblocking way...
719
        let req1 = r#"{"id":7,
720
                 "obj":"foo",
721
                 "method":"arti:x-frob", "params":{},
722
                 "extra": "preserved"
723
            }"#;
724
        let v = ValidatedRequest::from_string_strict(req1).unwrap();
725
        writer.send_valid(&v).unwrap();
726

            
727
        // At this point the above request is queued, but won't be sent until we interact.
728
        {
729
            assert!(test_stream.inner.lock().unwrap().received.is_empty());
730
        }
731

            
732
        // Now interact. This will cause the whole request to get flushed.
733
        let r = nbconn.interact_once();
734
        assert_wants_r_only(&nbconn, &r);
735

            
736
        let m = test_stream.drain(v.as_ref().len());
737
        assert_eq!(m, v.as_ref().as_bytes());
738

            
739
        // Now try again, but with a blocked stream.
740
        {
741
            test_stream.inner.lock().unwrap().receive_capacity = Some(32);
742
        }
743
        writer.send_valid(&v).unwrap();
744

            
745
        let r: Result<PollStatus, io::Error> = nbconn.interact_once();
746
        assert_wants_rw(&nbconn, &r);
747
        {
748
            assert_eq!(test_stream.inner.lock().unwrap().received.len(), 32);
749
            // Make the capacity unlimited.
750
            test_stream.inner.lock().unwrap().receive_capacity = None;
751
        }
752
        let r: Result<PollStatus, io::Error> = nbconn.interact_once();
753
        assert_wants_r_only(&nbconn, &r);
754
        let m = test_stream.drain(v.as_ref().len());
755
        assert_eq!(m, v.as_ref().as_bytes());
756
    }
757
}