1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! Inter-Process Communication Remote Procedure Calls
//! 
//! [![Crates.io](https://img.shields.io/crates/v/ipc-rpc.svg)](https://crates.io/crates/ipc-rpc/)
//! 
//! This Rust library is a wrapper over [`servo/ipc-channel`](https://github.com/servo/ipc-channel) that adds many new features.
//! 
//! - Bi-directional communication by default.
//! - [Future](https://doc.rust-lang.org/stable/std/future/trait.Future.html) based reply mechanism allows easy and accurate pairing of requests and responses.
//! - (Optional, enabled by default) Validation on startup that message schemas match between the server and client. No more debugging bad deserializations. Relies on [`schemars`](https://crates.io/crates/schemars).
//! - Streamlined initialization of IPC channels for common use cases, while still allowing for more flexible and robust dynamic initialization in more unique scenarios.
//! 
//! Compatible with anything that can run `servo/ipc-channel`, which at time of writing includes
//! 
//! - Windows
//! - MacOS
//! - Linux
//! - FreeBSD
//! - OpenBSD
//! 
//! Additionally, `servo/ipc-channel` supports the following platforms but only while in `inprocess` mode, which is not capable of communication between processes.
//! 
//! - Android
//! - iOS
//! - WASI
//! 
//! ## tokio
//! 
//! This crate uses the [`tokio`](https://crates.io/crates/tokio) runtime for executing futures, and it is a hard requirement that users of `ipc-rpc` must use `tokio`. There are no plans to add support for other
//! executors, but sufficient demand for other executors may change that.
//! 
//! # Cargo features
//! 
//! This crate exposes one feature, `message-schema-validation`, which is on by default. This enables functionality related to the [`schemars`](https://crates.io/crates/schemars) crate.
//! When enabled, the software will attempt to validate the user message schema on initialization of the connection. Failure to validate is not a critical failure, and won't crash the program. 
//! An error will be emitted in the logs, and this status can be retrieved programmatically via many functions, all called `schema_validation()`.
//! 
//! If you decide that a failure to validate the schema should be a critical failure you can add the following line of code to your program for execution after a connection is established.
//! 
//! ### Server
//! ```rust
//! server.schema_validation().await.unwrap().assert_success();
//! ```
//! 
//! ### Client
//! ```rust
//! client.schema_validation().await.unwrap().assert_success();
//! ``` 
//! 
//! # Limitations
//!
//! Much like `servo/ipc-channel`, servers may only serve one client. Overcoming this limitation would require work within `servo/ipc-channel`.

use std::collections::HashMap;
use std::{
    env,
    ffi::OsString,
    future::Future,
    io,
    pin::Pin,
    str::FromStr,
    sync::Arc,
    task::{Context, Poll},
    time::{self, Duration},
};

use futures::{Stream, StreamExt};
use ipc_channel::ipc::{IpcError, IpcReceiver, IpcSender, TryRecvError};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::Path;
use thiserror::Error;
use tokio::sync::{mpsc, watch};
use tokio::time::Instant;
use uuid::Uuid;

#[cfg(feature = "message-schema-validation")]
use schemars::{schema::RootSchema, schema_for, JsonSchema};

mod client;
pub use client::*;
mod server;
pub use server::*;

/// This key can be used to connect to the IPC server it came with, even outside of this process.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ConnectionKey(String);

impl TryFrom<String> for ConnectionKey {
    type Error = uuid::Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        uuid::Uuid::parse_str(&s).map(move |_| Self(s))
    }
}

impl FromStr for ConnectionKey {
    type Err = uuid::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        uuid::Uuid::parse_str(s).map(|_| Self(s.to_string()))
    }
}

impl ToString for ConnectionKey {
    fn to_string(&self) -> String {
        self.0.clone()
    }
}

impl From<ConnectionKey> for OsString {
    fn from(s: ConnectionKey) -> Self {
        OsString::from(s.0)
    }
}

impl From<ConnectionKey> for String {
    fn from(key: ConnectionKey) -> Self {
        key.0
    }
}

/// The pending reply box maintains a list of messages that are awaiting a reply. Messages are
/// paired via their uuids, and delivered via the tokio mpsc framework to a future awaiting
/// the reply. If a reply never arrives eventually a spawned Future responsible for maintenance
/// of this mail box will clean them out and resolve the futures with a time out.
type PendingReplyEntry<U> = (
    Uuid,
    (
        mpsc::UnboundedSender<Result<InternalMessageKind<U>, IpcRpcError>>,
        time::Instant,
    ),
);
/// Internal protocol message structure. Wraps the actual user message with some structure
/// helpful to the mail delivery system. You could liken this to a letter's envelope.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(bound(deserialize = ""))]
struct InternalMessage<U: UserMessage> {
    /// An identifier used for pairing messages with responses. A response to a message should
    /// carry the same UUID the message itself had. Otherwise, the UUID should be unique.
    uuid: uuid::Uuid,
    /// The actual contents of the message.
    kind: InternalMessageKind<U>,
}

/// There are many reasons we might need to send a message. This enumerates them. The enum also
/// contains some messages intended for internal use that downstream users shouldn't concern
/// themselves with.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(bound(deserialize = ""))]
enum InternalMessageKind<U: UserMessage> {
    /// Initialize connection. Includes an IpcSender which can be used to communicate with the client.
    InitConnection(IpcSender<InternalMessage<U>>),
    /// The conversation has come to a close, it's time to shut down.
    Hangup,
    /// Downstream has a message to exchange.
    UserMessage(U),
    /// Describes the user message schema for validation purposes
    UserMessageSchema(String),
    /// Returned if the user message schema matched
    UserMessageSchemaOk,
    /// Returned if the user message schema did not match
    UserMessageSchemaError { other_schema: String },
}

/// Errors which can occur with ipc-rpc during operation.
#[derive(Clone, Debug, Error)]
pub enum IpcRpcError {
    #[error("io error")]
    IoError(#[from] Arc<io::Error>),
    #[error("internal ipc channel error")]
    IpcChannelError(#[from] Arc<ipc_channel::Error>),
    #[error("connection initialization timed out")]
    ConnectTimeout,
    #[error("connection established, but initial handshake was not performed properly")]
    HandshakeFailure,
    #[error("client already connected")]
    ClientAlreadyConnected,
    #[error("peer disconnected")]
    Disconnected,
    #[error("time out while waiting for a reply")]
    ReplyTimeout,
    #[error("connection dropped pre-emptively")]
    ConnectionDropped,
}

impl From<io::Error> for IpcRpcError {
    fn from(e: io::Error) -> Self {
        Self::IoError(Arc::new(e))
    }
}

impl From<ipc_channel::Error> for IpcRpcError {
    fn from(e: ipc_channel::Error) -> Self {
        Self::IpcChannelError(Arc::new(e))
    }
}

// Arbitrarily chosen performance tuning constants, will likely be tuned in response to real world performance.
#[cfg(not(test))]
const PENDING_REPLY_CLEANUP_DURATION: Duration = Duration::from_secs(10);
#[cfg(not(test))]
const PENDING_REPLY_CLEANUP_CHECK_DURATION: Duration = Duration::from_secs(5);

// A different set of constants, chosen to make the unit tests run faster.
#[cfg(test)]
const PENDING_REPLY_CLEANUP_DURATION: Duration = Duration::from_millis(10);
#[cfg(test)]
const PENDING_REPLY_CLEANUP_CHECK_DURATION: Duration = Duration::from_millis(5);

/// Processes incoming messages for both the client and the server. Responsible for distributing
/// and generating replies.
async fn process_incoming_mail<
    Fut: Future<Output = Option<U>> + Send,
    F: Fn(U) -> Fut + Send + Sync + 'static,
    U: UserMessage,
>(
    is_server: bool,
    mut pending_reply_receiver: mpsc::UnboundedReceiver<PendingReplyEntry<U>>,
    mut receiver: IpcReceiveStream<InternalMessage<U>>,
    message_handler: F,
    response_sender: IpcSender<InternalMessage<U>>,
    status_sender: watch::Sender<ConnectionStatus>,
) {
    let mut pending_replies = HashMap::<
        Uuid,
        (
            mpsc::UnboundedSender<Result<InternalMessageKind<U>, IpcRpcError>>,
            time::Instant,
        ),
    >::new();
    let message_handler = Arc::new(message_handler);
    let log_prefix = get_log_prefix(is_server);
    log::info!("{}Processing incoming mail!", log_prefix);
    let mut consecutive_error_count = 0;
    let now = Instant::now();
    let mut pending_reply_scheduled_time = now + PENDING_REPLY_CLEANUP_CHECK_DURATION;
    loop {
        // Empty out the pending reply receiver before entering the select below. This guarantees
        // that all queued reply drop boxes are processed before we start receiving incoming mail.
        while let Ok(pending_reply) = pending_reply_receiver.try_recv() {
            pending_replies.insert(pending_reply.0, pending_reply.1);
        }
        tokio::select! {
            _ = tokio::time::sleep_until(pending_reply_scheduled_time) => {
                pending_replies.retain(|_k, v| {
                    let keep = v.1.elapsed() < PENDING_REPLY_CLEANUP_DURATION;
                    if !keep {
                        let _ = v.0.send(Err(IpcRpcError::ReplyTimeout));
                    }
                    keep
                });
                pending_reply_scheduled_time += PENDING_REPLY_CLEANUP_CHECK_DURATION;
            }
            pending_reply = pending_reply_receiver.recv() => {
                match pending_reply {
                    None => {
                        // Sender got dropped, time to close up shop.
                        break;
                    }
                    Some(pending_reply) => {
                        pending_replies.insert(pending_reply.0, pending_reply.1);
                    }
                }
            },
            r = receiver.next() => {
                match r {
                    None => {
                        // incoming mail stream ended, time to shut down.
                        break;
                    }
                    Some(Err(e)) => {
                        if let IpcError::Disconnected = e {
                            log::info!("{}Peer disconnected.", log_prefix);
                            break;
                        } else {
                            log::error!("{}Error receiving message from peer {:?}", log_prefix, e);
                            consecutive_error_count += 1;
                            if consecutive_error_count > 20 {
                                log::error!("{}Too many consecutive errors, shutting down.", log_prefix);
                                break;
                            }
                        }
                    }
                    Some(Ok(message)) => {
                        consecutive_error_count = 0;
                        log::debug!("{}Got message! {:?}", log_prefix, message);
                        let reply = pending_replies.remove(&message.uuid);
                        if let Some((reply_drop_box, _)) = reply {
                            log::debug!("{}It's a reply, forwarding!", log_prefix);
                            // If the end user doesn't want this message that's fine.
                            let _ = reply_drop_box.send(Ok(message.kind));
                        } else {
                            log::debug!("{}It's not a reply, handling!", log_prefix);
                            let message_uuid = message.uuid;
                            match message.kind {
                                InternalMessageKind::UserMessage(user_message) => {
                                    let message_handler = Arc::clone(&message_handler);
                                    let response_sender = response_sender.clone();
                                    tokio::spawn(async move {
                                        if let Some(m) = message_handler(user_message).await {
                                            let r = response_sender.send(InternalMessage {
                                                uuid: message_uuid,
                                                kind: InternalMessageKind::UserMessage(m),
                                            });
                                            if let Err(e) = r {
                                                log::error!("Failed to send reply {e:?}");
                                            }
                                        }
                                    });
                                }
                                #[cfg(feature = "message-schema-validation")]
                                InternalMessageKind::UserMessageSchema(other_schema) => {
                                    let my_schema = schema_for!(U);
                                    let kind = match serde_json::from_str::<RootSchema>(&other_schema) {
                                        Ok(other_schema) => {
                                            if other_schema == my_schema {
                                                InternalMessageKind::UserMessageSchemaOk
                                            } else {
                                                InternalMessageKind::UserMessageSchemaError {
                                                    other_schema: serde_json::to_string(&my_schema).expect("upstream guarantees this won't fail")
                                                }
                                            }
                                        },
                                        Err(_) => {
                                            log::error!("Failed to deserialize incoming schema properly, got {other_schema:?}");
                                            InternalMessageKind::UserMessageSchemaError {
                                                other_schema: serde_json::to_string(&my_schema).expect("upstream guarantees this won't fail")
                                            }
                                        }
                                    };
                                    let r = response_sender.send(InternalMessage {
                                        uuid: message_uuid,
                                        kind,
                                    });
                                    if let Err(e) = r {
                                        log::error!("Failed to send validation response {e:#?}");
                                    }
                                }
                                InternalMessageKind::Hangup => {
                                    break;
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }
    }
    let _ = status_sender.send(ConnectionStatus::DisconnectedCleanly);
}

fn get_log_prefix(is_server: bool) -> String {
    let first_arg = env::args()
        .next()
        .unwrap_or_else(|| String::from("Unknown"));
    let process = Path::new(&first_arg)
        .file_name()
        .unwrap_or_else(|| "Unknown".as_ref())
        .to_string_lossy();
    if is_server {
        format!("{} as Server: ", process)
    } else {
        format!("{} as Client: ", process)
    }
}

/// Reports the status of the connection between the server and the client
#[derive(Clone, Debug)]
pub enum ConnectionStatus {
    /// The server is waiting for a client to connect. A client never waits for a server to connect.
    WaitingForClient,
    /// The connection is active.
    Connected,
    /// A shutdown happened, and this was normal. Nothing unexpected happened.
    DisconnectedCleanly,
    /// An unexpected shutdown occurred, error contained within.
    DisconnectError(IpcRpcError),
}

impl ConnectionStatus {
    pub fn session_end_result(&self) -> Option<Result<(), IpcRpcError>> {
        match self {
            ConnectionStatus::WaitingForClient | ConnectionStatus::Connected => None,
            ConnectionStatus::DisconnectedCleanly => Some(Ok(())),
            ConnectionStatus::DisconnectError(e) => Some(Err(e.clone())),
        }
    }
}

/// This future represents a reply to a previous message. It is not a public type. This is to permit
/// future flexibility in how this interface is implemented.
struct IpcReplyFuture<U: UserMessage> {
    receiver: mpsc::UnboundedReceiver<Result<InternalMessageKind<U>, IpcRpcError>>,
}

impl<U: UserMessage> Future for IpcReplyFuture<U> {
    type Output = Result<InternalMessageKind<U>, IpcRpcError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.receiver.poll_recv(cx).map(|o| match o {
            Some(m) => m,
            None => Err(IpcRpcError::ConnectionDropped),
        })
    }
}

struct IpcReceiveStream<T> {
    receiver: mpsc::UnboundedReceiver<Result<T, IpcError>>,
}

impl<T> IpcReceiveStream<T>
where
    T: Send + for<'de> Deserialize<'de> + Serialize + 'static,
{
    pub fn new(ipc_receiver: IpcReceiver<T>) -> Self {
        let (sender, receiver) = mpsc::unbounded_channel();
        tokio::task::spawn_blocking(move || loop {
            match ipc_receiver.try_recv_timeout(Duration::from_millis(250)) {
                Ok(msg) => {
                    if sender.send(Ok(msg)).is_err() {
                        break;
                    }
                }
                Err(TryRecvError::IpcError(e)) => {
                    if sender.send(Err(e)).is_err() {
                        break;
                    }
                }
                Err(TryRecvError::Empty) => {
                    if sender.is_closed() {
                        break;
                    }
                }
            }
        });
        Self { receiver }
    }
}

impl<T> Stream for IpcReceiveStream<T> {
    type Item = Result<T, IpcError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.receiver.poll_recv(cx)
    }
}

/// Reports the outcome of automatic schema validation testing. This testing is performed
/// on connection initiation.
#[derive(Debug, Clone)]
pub enum SchemaValidationStatus {
    /// Crate was compiled without default features, so validation does not function.
    ValidationDisabledAtCompileTime,
    /// Internal error
    ValidationNotPerformedProperly,
    /// Internal error
    ValidationCommunicationFailed(IpcRpcError),
    /// Schemas matched, all clear
    SchemasMatched,
    /// Schemas didn't match, schemas provided for comparison
    SchemaMismatch {
        our_schema: String,
        their_schema: String,
    },
}

impl SchemaValidationStatus {
    /// Returns true if this is an instance of [`Self::SchemasMatched`], and false otherwise.
    pub fn is_success(&self) -> bool {
        matches!(self, SchemaValidationStatus::SchemasMatched)
    }

    /// Panics if this status is not [`Self::SchemasMatched`], and prints the debug information into the panic.
    pub fn assert_success(&self) {
        if !self.is_success() {
            panic!("ipc-rpc user message schema failed to validate, error {self:#?}");
        }
    }
}

/// A combination trait which represents all of the traits needed for a type to be
/// used as a message with this library.
///
/// # Note on `JsonSchema`
/// `JsonSchema` is a trait from the [`schemars`](https://crates.io/crates/schemars) crate.
/// Deriving it for your message allows `ipc-rpc` to perform validation on message schemas
/// after communication has started. The results of this validation are logged, and stored in
/// [IpcRpcClient::schema_validated], [IpcRpcServer::schema_validated], and [IpcRpc::schema_validated].
/// A failed validation will not crash the program.
///
/// Despite what this may imply, `ipc-rpc` does not use JSON for messages internally.
///
/// If you find yourself unable to derive `JsonSchema` then consider turning off
/// default features for the `ipc-rpc` crate. Once you do, the `JsonSchema` requirement
/// will go away.
#[cfg(feature = "message-schema-validation")]
pub trait UserMessage:
    'static + Send + Debug + Clone + DeserializeOwned + Serialize + JsonSchema
{
}

#[cfg(feature = "message-schema-validation")]
impl<T> UserMessage for T where
    T: 'static + Send + Debug + Clone + DeserializeOwned + Serialize + JsonSchema
{
}

/// A combination trait which represents all of the traits needed for a type to be
/// used as a message with this library.
#[cfg(not(feature = "message-schema-validation"))]
pub trait UserMessage: 'static + Send + Debug + Clone + DeserializeOwned + Serialize {}

#[cfg(not(feature = "message-schema-validation"))]
impl<T> UserMessage for T where T: 'static + Send + Debug + Clone + DeserializeOwned + Serialize {}

/// Invokes an RPC call within the current async runtime.
///
/// # Params
/// - `sender`: A reference to an [IpcRpcServer], [IpcRpcClient], or [IpcRpc]
/// - `to_send`: The message sent to the remote
/// - `receiver`: The expected response pattern, followed by a handler for it.
///
/// # Returns
/// The value returned by `receiver`.
///
/// # Panics
/// Panics if the message received from the remote doesn't match the pattern specified
/// in receiver.
///
/// # Example
///
/// ```ignore
/// rpc_call!(
///     sender: client,
///     to_send: Message::MakeMeASandwich,
///     receiver: Message::ASandwich(parts) => {
///         log::info!("I got a sandwich! It contains\n{parts:#?}");
///     },
/// )
/// .unwrap()
/// ```
#[macro_export]
macro_rules! rpc_call {
    (sender: $sender:expr, to_send: $to_send:expr, receiver: $received:pat_param => $to_do:block,) => {
        $sender.send($to_send).await.map(|m| match m {
            $received => $to_do,
            _ => panic!("rpc_call response didn't match given pattern"),
        })
    };
}

#[cfg(test)]
mod tests {
    use tokio::time::timeout;

    use super::*;

    #[cfg(not(feature = "message-schema-validation"))]
    compile_error!("Tests must be executed with all features on");

    #[derive(Deserialize, Serialize, Debug, Clone, JsonSchema)]
    pub struct IpcProtocolMessage {
        pub kind: IpcProtocolMessageKind,
    }

    #[derive(Deserialize, Serialize, Debug, Clone, JsonSchema)]
    pub enum IpcProtocolMessageKind {
        TestMessage,
        ClientTestReply,
        ServerTestReply,
    }

    #[test_log::test(tokio::test)]
    async fn basic_dialogue() {
        let (server_key, mut server) =
            server::IpcRpcServer::initialize_server(|message: IpcProtocolMessage| async move {
                match message.kind {
                    IpcProtocolMessageKind::TestMessage => Some(IpcProtocolMessage {
                        kind: IpcProtocolMessageKind::ServerTestReply,
                    }),
                    _ => None,
                }
            })
            .await
            .unwrap();
        let mut client = client::IpcRpcClient::initialize_client(
            server_key,
            |message: IpcProtocolMessage| async move {
                match message.kind {
                    IpcProtocolMessageKind::TestMessage => Some(IpcProtocolMessage {
                        kind: IpcProtocolMessageKind::ClientTestReply,
                    }),
                    _ => None,
                }
            },
        )
        .await
        .unwrap();
        server.schema_validated().await.unwrap().assert_success();
        client.schema_validated().await.unwrap().assert_success();
        let client_reply = server
            .send(IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage,
            })
            .await;
        if !matches!(
            client_reply.as_ref().map(|r| &r.kind),
            Ok(IpcProtocolMessageKind::ClientTestReply)
        ) {
            panic!("client reply was of unexpected type: {:?}", client_reply);
        }
        let server_reply = client
            .send(IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage,
            })
            .await;
        if !matches!(
            server_reply.as_ref().map(|r| &r.kind),
            Ok(IpcProtocolMessageKind::ServerTestReply)
        ) {
            panic!("server reply was of unexpected type: {:?}", server_reply);
        }
    }

    #[test_log::test(tokio::test)]
    async fn send_without_await() {
        let (server_success_sender, mut server_success_receiver) = mpsc::unbounded_channel();
        let (client_success_sender, mut client_success_receiver) = mpsc::unbounded_channel();
        let (server_key, mut server) =
            server::IpcRpcServer::initialize_server(move |message: IpcProtocolMessage| {
                let server_success_sender = server_success_sender.clone();
                async move {
                    match message.kind {
                        IpcProtocolMessageKind::TestMessage => {
                            server_success_sender.send(()).unwrap()
                        }
                        _ => {}
                    }
                    None
                }
            })
            .await
            .unwrap();
        let mut client = client::IpcRpcClient::initialize_client(
            server_key,
            move |message: IpcProtocolMessage| {
                let client_success_sender = client_success_sender.clone();
                async move {
                    match message.kind {
                        IpcProtocolMessageKind::TestMessage => {
                            client_success_sender.send(()).unwrap()
                        }
                        _ => {}
                    }
                    None
                }
            },
        )
        .await
        .unwrap();
        server.schema_validated().await.unwrap().assert_success();
        client.schema_validated().await.unwrap().assert_success();
        let _ = server.send(IpcProtocolMessage {
            kind: IpcProtocolMessageKind::TestMessage,
        });
        let _ = client.send(IpcProtocolMessage {
            kind: IpcProtocolMessageKind::TestMessage,
        });
        assert_eq!(
            timeout(Duration::from_secs(3), server_success_receiver.recv()).await,
            Ok(Some(()))
        );
        assert_eq!(
            timeout(Duration::from_secs(3), client_success_receiver.recv()).await,
            Ok(Some(()))
        );
    }

    #[test_log::test(tokio::test)]
    async fn timeout_test() {
        let (server_key, mut server) =
            server::IpcRpcServer::initialize_server(|message: IpcProtocolMessage| async move {
                match message.kind {
                    _ => None,
                }
            })
            .await
            .unwrap();
        let mut client = client::IpcRpcClient::initialize_client(
            server_key,
            |message: IpcProtocolMessage| async move {
                match message.kind {
                    _ => None,
                }
            },
        )
        .await
        .unwrap();
        server.schema_validated().await.unwrap().assert_success();
        client.schema_validated().await.unwrap().assert_success();
        let client_reply = server
            .send(IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage,
            })
            .await;
        if !matches!(client_reply, Err(IpcRpcError::ReplyTimeout)) {
            panic!("client reply was of unexpected type: {:?}", client_reply);
        }
        let server_reply = client
            .send(IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage,
            })
            .await;
        if !matches!(server_reply, Err(IpcRpcError::ReplyTimeout)) {
            panic!("server reply was of unexpected type: {:?}", server_reply);
        }
    }

    // This test checks to see if a task has come to an end, so it must wait for the runtime to drop.
    // Therefore tokio::test is not an option.
    #[test_log::test]
    fn server_disconnect_test() {
        use std::time::Instant;

        // We use an empty Arc as a resource inside the message handler to prove the message handler
        // was dropped. If the message handler was dropped then the cleanup routines were executed.
        let drop_detector = Arc::new(());
        let drop_detector_clone = drop_detector.clone();
        let runtime = tokio::runtime::Runtime::new().unwrap();
        runtime.block_on(async move {
            let (server_key, server) = server::IpcRpcServer::initialize_server({
                let drop_detector_clone = drop_detector_clone.clone();
                move |message: IpcProtocolMessage| {
                    let drop_detector_clone = drop_detector_clone.clone();
                    async move {
                        match message.kind {
                            _ => {
                                // I don't expect this to ever be called, I just need the closure to take
                                // ownership of the Arc.
                                let _ = drop_detector_clone.clone();
                                None
                            }
                        }
                    }
                }
            })
            .await
            .unwrap();
            let client = client::IpcRpcClient::initialize_client(
                server_key,
                |message: IpcProtocolMessage| async move {
                    match message.kind {
                        _ => None,
                    }
                },
            )
            .await
            .unwrap();
            assert_eq!(Arc::strong_count(&drop_detector_clone), 3);
            drop(server);
            client.wait_for_server_to_disconnect().await.unwrap();
        });
        // It's important that the runtime be able to shut down quickly, so we'll assert it
        // shut down within 3 seconds.
        let start_shutdown = Instant::now();
        runtime.shutdown_timeout(Duration::from_secs(5));
        assert!(start_shutdown.elapsed() < Duration::from_secs(3));
        assert_eq!(Arc::strong_count(&drop_detector), 1);
    }

    // This test checks to see if a task has come to an end, so it must wait for the runtime to drop.
    // Therefore tokio::test is not an option.
    #[test_log::test]
    fn client_disconnect_test() {
        use std::time::Instant;

        // We use an empty Arc as a resource inside the message handler to prove the message handler
        // was dropped. If the message handler was dropped then the cleanup routines were executed.
        let drop_detector = Arc::new(());
        let drop_detector_clone = drop_detector.clone();
        let runtime = tokio::runtime::Runtime::new().unwrap();
        runtime.block_on(async move {
            let (server_key, mut server) =
                server::IpcRpcServer::initialize_server(|message: IpcProtocolMessage| async move {
                    match message.kind {
                        _ => None,
                    }
                })
                .await
                .unwrap();
            let client = client::IpcRpcClient::initialize_client(server_key, {
                let drop_detector_clone = drop_detector_clone.clone();
                move |message: IpcProtocolMessage| {
                    let _drop_detector_clone = drop_detector_clone.clone();
                    async move {
                        match message.kind {
                            _ => None,
                        }
                    }
                }
            })
            .await
            .unwrap();
            assert_eq!(Arc::strong_count(&drop_detector_clone), 3);
            drop(client);
            server.wait_for_client_to_disconnect().await.unwrap();
        });
        // It's important that the runtime be able to shut down quickly, so we'll assert it
        // shut down within 3 seconds.
        let start_shutdown = Instant::now();
        runtime.shutdown_timeout(Duration::from_secs(5));
        assert!(start_shutdown.elapsed() < Duration::from_secs(3));
        assert_eq!(Arc::strong_count(&drop_detector), 1);
    }

    #[test_log::test(tokio::test)]
    async fn rpc_call_macro_test() {
        let (server_key, mut server) =
            server::IpcRpcServer::initialize_server(|message: IpcProtocolMessage| async move {
                match message.kind {
                    _ => Some(IpcProtocolMessage {
                        kind: IpcProtocolMessageKind::ServerTestReply,
                    }),
                }
            })
            .await
            .unwrap();
        let mut client = client::IpcRpcClient::initialize_client(
            server_key,
            |message: IpcProtocolMessage| async move {
                match message.kind {
                    _ => Some(IpcProtocolMessage {
                        kind: IpcProtocolMessageKind::ClientTestReply,
                    }),
                }
            },
        )
        .await
        .unwrap();
        server.schema_validated().await.unwrap().assert_success();
        client.schema_validated().await.unwrap().assert_success();
        rpc_call!(
            sender: server,
            to_send: IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage
            },
            receiver: IpcProtocolMessage {
                kind: IpcProtocolMessageKind::ClientTestReply
            } => {

            },
        )
        .unwrap();
        rpc_call!(
            sender: client,
            to_send: IpcProtocolMessage {
                kind: IpcProtocolMessageKind::TestMessage
            },
            receiver: IpcProtocolMessage {
                kind: IpcProtocolMessageKind::ServerTestReply
            } => {

            },
        )
        .unwrap();
    }
}