-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlib.rs
1183 lines (1050 loc) · 39.3 KB
/
lib.rs
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg_attr(quicrpc_docsrs, feature(doc_cfg))]
use std::{fmt::Debug, future::Future, io, marker::PhantomData, ops::Deref};
use channel::none::NoReceiver;
use sealed::Sealed;
use serde::{de::DeserializeOwned, Serialize};
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
pub mod util;
#[cfg(not(feature = "rpc"))]
mod util;
/// Requirements for a RPC message
///
/// Even when just using the mem transport, we require messages to be Serializable and Deserializable.
/// Likewise, even when using the quinn transport, we require messages to be Send.
///
/// This does not seem like a big restriction. If you want a pure memory channel without the possibility
/// to also use the quinn transport, you might want to use a mpsc channel directly.
pub trait RpcMessage: Debug + Serialize + DeserializeOwned + Send + Sync + Unpin + 'static {}
impl<T> RpcMessage for T where
T: Debug + Serialize + DeserializeOwned + Send + Sync + Unpin + 'static
{
}
/// Marker trait for a service
///
/// This is usually implemented by a zero-sized struct.
/// It has various bounds to make derives easier.
pub trait Service: Send + Sync + Debug + Clone + 'static {}
mod sealed {
pub trait Sealed {}
}
/// Sealed marker trait for a sender
pub trait Sender: Debug + Sealed {}
/// Sealed marker trait for a receiver
pub trait Receiver: Debug + Sealed {}
/// Channels to be used for a message and service
pub trait Channels<S: Service> {
/// The sender type, can be either spsc, oneshot or none
type Tx: Sender;
/// The receiver type, can be either spsc, oneshot or none
///
/// For many services, the receiver is not needed, so it can be set to [`NoReceiver`].
type Rx: Receiver;
}
mod wasm_browser {
#![allow(dead_code)]
pub(crate) type BoxedFuture<'a, T> =
std::pin::Pin<Box<dyn std::future::Future<Output = T> + 'a>>;
}
mod multithreaded {
#![allow(dead_code)]
pub(crate) type BoxedFuture<'a, T> =
std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
}
#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
use multithreaded::*;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use wasm_browser::*;
/// Channels that abstract over local or remote sending
pub mod channel {
use std::io;
/// Oneshot channel, similar to tokio's oneshot channel
pub mod oneshot {
use std::{fmt::Debug, future::Future, io, pin::Pin, task};
use super::{RecvError, SendError};
use crate::util::FusedOneshotReceiver;
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (tx, rx) = tokio::sync::oneshot::channel();
(tx.into(), rx.into())
}
pub type BoxedSender<T> = Box<
dyn FnOnce(T) -> crate::BoxedFuture<'static, io::Result<()>> + Send + Sync + 'static,
>;
pub type BoxedReceiver<T> = crate::BoxedFuture<'static, io::Result<T>>;
pub enum Sender<T> {
Tokio(tokio::sync::oneshot::Sender<T>),
Boxed(BoxedSender<T>),
}
impl<T> Debug for Sender<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tokio(_) => f.debug_tuple("Tokio").finish(),
Self::Boxed(_) => f.debug_tuple("Boxed").finish(),
}
}
}
impl<T> From<tokio::sync::oneshot::Sender<T>> for Sender<T> {
fn from(tx: tokio::sync::oneshot::Sender<T>) -> Self {
Self::Tokio(tx)
}
}
impl<T> TryFrom<Sender<T>> for tokio::sync::oneshot::Sender<T> {
type Error = Sender<T>;
fn try_from(value: Sender<T>) -> Result<Self, Self::Error> {
match value {
Sender::Tokio(tx) => Ok(tx),
Sender::Boxed(_) => Err(value),
}
}
}
impl<T> Sender<T> {
pub async fn send(self, value: T) -> std::result::Result<(), SendError> {
match self {
Sender::Tokio(tx) => tx.send(value).map_err(|_| SendError::ReceiverClosed),
Sender::Boxed(f) => f(value).await.map_err(SendError::from),
}
}
}
impl<T> Sender<T> {
pub fn is_rpc(&self) -> bool
where
T: 'static,
{
match self {
Sender::Tokio(_) => false,
Sender::Boxed(_) => true,
}
}
}
impl<T> crate::sealed::Sealed for Sender<T> {}
impl<T> crate::Sender for Sender<T> {}
pub enum Receiver<T> {
Tokio(FusedOneshotReceiver<T>),
Boxed(BoxedReceiver<T>),
}
impl<T> Future for Receiver<T> {
type Output = std::result::Result<T, RecvError>;
fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> task::Poll<Self::Output> {
match self.get_mut() {
Self::Tokio(rx) => Pin::new(rx).poll(cx).map_err(|_| RecvError::SenderClosed),
Self::Boxed(rx) => Pin::new(rx).poll(cx).map_err(RecvError::Io),
}
}
}
/// Convert a tokio oneshot receiver to a receiver for this crate
impl<T> From<tokio::sync::oneshot::Receiver<T>> for Receiver<T> {
fn from(rx: tokio::sync::oneshot::Receiver<T>) -> Self {
Self::Tokio(FusedOneshotReceiver(rx))
}
}
impl<T> TryFrom<Receiver<T>> for tokio::sync::oneshot::Receiver<T> {
type Error = Receiver<T>;
fn try_from(value: Receiver<T>) -> Result<Self, Self::Error> {
match value {
Receiver::Tokio(tx) => Ok(tx.0),
Receiver::Boxed(_) => Err(value),
}
}
}
/// Convert a function that produces a future to a receiver for this crate
impl<T, F, Fut> From<F> for Receiver<T>
where
F: FnOnce() -> Fut,
Fut: Future<Output = io::Result<T>> + Send + 'static,
{
fn from(f: F) -> Self {
Self::Boxed(Box::pin(f()))
}
}
impl<T> Debug for Receiver<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tokio(_) => f.debug_tuple("Tokio").finish(),
Self::Boxed(_) => f.debug_tuple("Boxed").finish(),
}
}
}
impl<T> crate::sealed::Sealed for Receiver<T> {}
impl<T> crate::Receiver for Receiver<T> {}
}
/// SPSC channel, similar to tokio's mpsc channel
///
/// For the rpc case, the send side can not be cloned, hence spsc instead of mpsc.
pub mod spsc {
use std::{fmt::Debug, future::Future, io, pin::Pin};
use super::{RecvError, SendError};
use crate::RpcMessage;
pub fn channel<T>(buffer: usize) -> (Sender<T>, Receiver<T>) {
let (tx, rx) = tokio::sync::mpsc::channel(buffer);
(tx.into(), rx.into())
}
pub enum Sender<T> {
Tokio(tokio::sync::mpsc::Sender<T>),
Boxed(Box<dyn BoxedSender<T>>),
}
impl<T> Sender<T> {
pub fn is_rpc(&self) -> bool
where
T: 'static,
{
match self {
Sender::Tokio(_) => false,
Sender::Boxed(x) => x.is_rpc(),
}
}
}
impl<T> From<tokio::sync::mpsc::Sender<T>> for Sender<T> {
fn from(tx: tokio::sync::mpsc::Sender<T>) -> Self {
Self::Tokio(tx)
}
}
impl<T> TryFrom<Sender<T>> for tokio::sync::mpsc::Sender<T> {
type Error = Sender<T>;
fn try_from(value: Sender<T>) -> Result<Self, Self::Error> {
match value {
Sender::Tokio(tx) => Ok(tx),
Sender::Boxed(_) => Err(value),
}
}
}
pub trait BoxedSender<T>: Debug + Send + Sync + 'static {
fn send(
&mut self,
value: T,
) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>>;
fn try_send(
&mut self,
value: T,
) -> Pin<Box<dyn Future<Output = io::Result<bool>> + Send + '_>>;
fn is_rpc(&self) -> bool;
}
pub trait BoxedReceiver<T>: Debug + Send + Sync + 'static {
fn recv(
&mut self,
) -> Pin<Box<dyn Future<Output = std::result::Result<Option<T>, RecvError>> + Send + '_>>;
}
impl<T> Debug for Sender<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tokio(_) => f.debug_tuple("Tokio").finish(),
Self::Boxed(_) => f.debug_tuple("Boxed").finish(),
}
}
}
impl<T: RpcMessage> Sender<T> {
pub async fn send(&mut self, value: T) -> std::result::Result<(), SendError> {
match self {
Sender::Tokio(tx) => {
tx.send(value).await.map_err(|_| SendError::ReceiverClosed)
}
Sender::Boxed(sink) => sink.send(value).await.map_err(SendError::from),
}
}
pub async fn try_send(&mut self, value: T) -> std::result::Result<(), SendError> {
match self {
Sender::Tokio(tx) => match tx.try_send(value) {
Ok(()) => Ok(()),
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
Err(SendError::ReceiverClosed)
}
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => Ok(()),
},
Sender::Boxed(sink) => {
sink.try_send(value).await.map_err(SendError::from)?;
Ok(())
}
}
}
}
impl<T> crate::sealed::Sealed for Sender<T> {}
impl<T> crate::Sender for Sender<T> {}
pub enum Receiver<T> {
Tokio(tokio::sync::mpsc::Receiver<T>),
Boxed(Box<dyn BoxedReceiver<T>>),
}
impl<T: RpcMessage> Receiver<T> {
/// Receive a message
///
/// Returns Ok(None) if the sender has been dropped or the remote end has
/// cleanly closed the connection.
///
/// Returns an an io error if there was an error receiving the message.
pub async fn recv(&mut self) -> std::result::Result<Option<T>, RecvError> {
match self {
Self::Tokio(rx) => Ok(rx.recv().await),
Self::Boxed(rx) => Ok(rx.recv().await?),
}
}
}
impl<T> From<tokio::sync::mpsc::Receiver<T>> for Receiver<T> {
fn from(rx: tokio::sync::mpsc::Receiver<T>) -> Self {
Self::Tokio(rx)
}
}
impl<T> TryFrom<Receiver<T>> for tokio::sync::mpsc::Receiver<T> {
type Error = Receiver<T>;
fn try_from(value: Receiver<T>) -> Result<Self, Self::Error> {
match value {
Receiver::Tokio(tx) => Ok(tx),
Receiver::Boxed(_) => Err(value),
}
}
}
impl<T> Debug for Receiver<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Tokio(_) => f.debug_tuple("Tokio").finish(),
Self::Boxed(_) => f.debug_tuple("Boxed").finish(),
}
}
}
impl<T> crate::sealed::Sealed for Receiver<T> {}
impl<T> crate::Receiver for Receiver<T> {}
}
/// No channels, used when no communication is needed
pub mod none {
use crate::sealed::Sealed;
#[derive(Debug)]
pub struct NoSender;
impl Sealed for NoSender {}
impl crate::Sender for NoSender {}
#[derive(Debug)]
pub struct NoReceiver;
impl Sealed for NoReceiver {}
impl crate::Receiver for NoReceiver {}
}
/// Error when sending a oneshot or spsc message. For local communication,
/// the only thing that can go wrong is that the receiver has been dropped.
///
/// For rpc communication, there can be any number of errors, so this is a
/// generic io error.
#[derive(Debug, thiserror::Error)]
pub enum SendError {
#[error("receiver closed")]
ReceiverClosed,
#[error("io error: {0}")]
Io(#[from] io::Error),
}
impl From<SendError> for io::Error {
fn from(e: SendError) -> Self {
match e {
SendError::ReceiverClosed => io::Error::new(io::ErrorKind::BrokenPipe, e),
SendError::Io(e) => e,
}
}
}
/// Error when receiving a oneshot or spsc message. For local communication,
/// the only thing that can go wrong is that the sender has been closed.
///
/// For rpc communication, there can be any number of errors, so this is a
/// generic io error.
#[derive(Debug, thiserror::Error)]
pub enum RecvError {
#[error("sender closed")]
SenderClosed,
#[error("io error: {0}")]
Io(#[from] io::Error),
}
impl From<RecvError> for io::Error {
fn from(e: RecvError) -> Self {
match e {
RecvError::Io(e) => e,
RecvError::SenderClosed => io::Error::new(io::ErrorKind::BrokenPipe, e),
}
}
}
}
/// A wrapper for a message with channels to send and receive it.
/// This expands the protocol message to a full message that includes the
/// active and unserializable channels.
///
/// rx and tx can be set to an appropriate channel kind.
pub struct WithChannels<I: Channels<S>, S: Service> {
/// The inner message.
pub inner: I,
/// The return channel to send the response to. Can be set to [`crate::channel::none::NoSender`] if not needed.
pub tx: <I as Channels<S>>::Tx,
/// The request channel to receive the request from. Can be set to [`NoReceiver`] if not needed.
pub rx: <I as Channels<S>>::Rx,
/// The current span where the full message was created.
#[cfg(feature = "message_spans")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "message_spans")))]
pub span: tracing::Span,
}
impl<I: Channels<S> + Debug, S: Service> Debug for WithChannels<I, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("")
.field(&self.inner)
.field(&self.tx)
.field(&self.rx)
.finish()
}
}
impl<I: Channels<S>, S: Service> WithChannels<I, S> {
#[cfg(feature = "message_spans")]
pub fn parent_span_opt(&self) -> Option<&tracing::Span> {
Some(&self.span)
}
}
/// Tuple conversion from inner message and tx/rx channels to a WithChannels struct
///
/// For the case where you want both tx and rx channels.
impl<I: Channels<S>, S: Service, Tx, Rx> From<(I, Tx, Rx)> for WithChannels<I, S>
where
I: Channels<S>,
<I as Channels<S>>::Tx: From<Tx>,
<I as Channels<S>>::Rx: From<Rx>,
{
fn from(inner: (I, Tx, Rx)) -> Self {
let (inner, tx, rx) = inner;
Self {
inner,
tx: tx.into(),
rx: rx.into(),
#[cfg(feature = "message_spans")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "message_spans")))]
span: tracing::Span::current(),
}
}
}
/// Tuple conversion from inner message and tx channel to a WithChannels struct
///
/// For the very common case where you just need a tx channel to send the response to.
impl<I, S, Tx> From<(I, Tx)> for WithChannels<I, S>
where
I: Channels<S, Rx = NoReceiver>,
S: Service,
<I as Channels<S>>::Tx: From<Tx>,
{
fn from(inner: (I, Tx)) -> Self {
let (inner, tx) = inner;
Self {
inner,
tx: tx.into(),
rx: NoReceiver,
#[cfg(feature = "message_spans")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "message_spans")))]
span: tracing::Span::current(),
}
}
}
/// Deref so you can access the inner fields directly
impl<I: Channels<S>, S: Service> Deref for WithChannels<I, S> {
type Target = I;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
/// A client to the service `S` using the local message type `M` and the remote
/// message type `R`.
///
/// `R` is typically a serializable enum with a case for each possible message
/// type. It can be thought of as the definition of the protocol.
///
/// `M` is typically an enum with a case for each possible message type, where
/// each case is a `WithChannels` struct that extends the inner protocol message
/// with a local tx and rx channel as well as a tracing span to allow for
/// keeping tracing context across async boundaries.
///
/// In some cases, `M` and `R` can be enums for a subset of the protocol. E.g.
/// if you have a subsystem that only handles a part of the messages.
///
/// The service type `S` provides a scope for the protocol messages. It exists
/// so you can use the same message with multiple services.
#[derive(Debug)]
pub struct Client<M, R, S>(ClientInner<M>, PhantomData<(R, S)>);
impl<M, R, S> Clone for Client<M, R, S> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<M, R, S> From<LocalSender<M, S>> for Client<M, R, S> {
fn from(tx: LocalSender<M, S>) -> Self {
Self(ClientInner::Local(tx.0), PhantomData)
}
}
impl<M, R, S> From<tokio::sync::mpsc::Sender<M>> for Client<M, R, S> {
fn from(tx: tokio::sync::mpsc::Sender<M>) -> Self {
LocalSender::from(tx).into()
}
}
impl<M, R, S> Client<M, R, S> {
/// Create a new client to a remote service using the given quinn `endpoint`
/// and a socket `addr` of the remote service.
#[cfg(feature = "rpc")]
pub fn quinn(endpoint: quinn::Endpoint, addr: std::net::SocketAddr) -> Self {
Self::boxed(rpc::QuinnRemoteConnection::new(endpoint, addr))
}
/// Create a new client from a `rpc::RemoteConnection` trait object.
/// This is used from crates that want to provide other transports than quinn,
/// such as the iroh transport.
#[cfg(feature = "rpc")]
pub fn boxed(remote: impl rpc::RemoteConnection) -> Self {
Self(ClientInner::Remote(Box::new(remote)), PhantomData)
}
/// Get the local sender. This is useful if you don't care about remote
/// requests.
pub fn local(&self) -> Option<LocalSender<M, S>> {
match &self.0 {
ClientInner::Local(tx) => Some(tx.clone().into()),
ClientInner::Remote(..) => None,
}
}
/// Create a sender that allows sending messages to the service.
///
/// In the local case, this is just a clone which has almost zero overhead.
/// Creating a local sender can not fail.
///
/// In the remote case, this involves lazily creating a connection to the
/// remote side and then creating a new stream on the underlying
/// [`quinn`] or iroh connection.
///
/// In both cases, the returned sender is fully self contained.
#[allow(clippy::type_complexity)]
pub fn request(
&self,
) -> impl Future<
Output = Result<Request<LocalSender<M, S>, rpc::RemoteSender<R, S>>, RequestError>,
> + 'static
where
S: Service,
M: Send + Sync + 'static,
R: 'static,
{
#[cfg(feature = "rpc")]
{
let cloned = match &self.0 {
ClientInner::Local(tx) => Request::Local(tx.clone()),
ClientInner::Remote(connection) => Request::Remote(connection.clone_boxed()),
};
async move {
match cloned {
Request::Local(tx) => Ok(Request::Local(tx.into())),
#[cfg(feature = "rpc")]
Request::Remote(conn) => {
let (send, recv) = conn.open_bi().await?;
Ok(Request::Remote(rpc::RemoteSender::new(send, recv)))
}
}
}
}
#[cfg(not(feature = "rpc"))]
{
let ClientInner::Local(tx) = &self.0 else {
unreachable!()
};
let tx = tx.clone().into();
async move { Ok(Request::Local(tx)) }
}
}
}
#[derive(Debug)]
pub(crate) enum ClientInner<M> {
Local(tokio::sync::mpsc::Sender<M>),
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
Remote(Box<dyn rpc::RemoteConnection>),
#[cfg(not(feature = "rpc"))]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
Remote(PhantomData<M>),
}
impl<M> Clone for ClientInner<M> {
fn clone(&self) -> Self {
match self {
Self::Local(tx) => Self::Local(tx.clone()),
#[cfg(feature = "rpc")]
Self::Remote(conn) => Self::Remote(conn.clone_boxed()),
#[cfg(not(feature = "rpc"))]
Self::Remote(_) => unreachable!(),
}
}
}
/// Error when opening a request. When cross-process rpc is disabled, this is
/// an empty enum since local requests can not fail.
#[derive(Debug, thiserror::Error)]
pub enum RequestError {
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
#[error("error establishing connection: {0}")]
Connect(#[from] quinn::ConnectError),
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
#[error("error opening stream: {0}")]
Connection(#[from] quinn::ConnectionError),
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
#[error("error opening stream: {0}")]
Other(#[from] anyhow::Error),
}
/// Error type that subsumes all possible errors in this crate, for convenience.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("request error: {0}")]
Request(#[from] RequestError),
#[error("send error: {0}")]
Send(#[from] channel::SendError),
#[error("recv error: {0}")]
Recv(#[from] channel::RecvError),
#[cfg(feature = "rpc")]
#[error("recv error: {0}")]
Write(#[from] rpc::WriteError),
}
impl From<Error> for io::Error {
fn from(e: Error) -> Self {
match e {
Error::Request(e) => e.into(),
Error::Send(e) => e.into(),
Error::Recv(e) => e.into(),
#[cfg(feature = "rpc")]
Error::Write(e) => e.into(),
}
}
}
impl From<RequestError> for io::Error {
fn from(e: RequestError) -> Self {
match e {
#[cfg(feature = "rpc")]
RequestError::Connect(e) => io::Error::other(e),
#[cfg(feature = "rpc")]
RequestError::Connection(e) => e.into(),
#[cfg(feature = "rpc")]
RequestError::Other(e) => io::Error::other(e),
}
}
}
/// A local sender for the service `S` using the message type `M`.
///
/// This is a wrapper around an in-memory channel (currently [`tokio::sync::mpsc::Sender`]),
/// that adds nice syntax for sending messages that can be converted into
/// [`WithChannels`].
#[derive(Debug)]
#[repr(transparent)]
pub struct LocalSender<M, S>(tokio::sync::mpsc::Sender<M>, std::marker::PhantomData<S>);
impl<M, S> Clone for LocalSender<M, S> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<M, S> From<tokio::sync::mpsc::Sender<M>> for LocalSender<M, S> {
fn from(tx: tokio::sync::mpsc::Sender<M>) -> Self {
Self(tx, PhantomData)
}
}
#[cfg(not(feature = "rpc"))]
pub mod rpc {
pub struct RemoteSender<R, S>(std::marker::PhantomData<(R, S)>);
}
#[cfg(feature = "rpc")]
#[cfg_attr(quicrpc_docsrs, doc(cfg(feature = "rpc")))]
pub mod rpc {
//! Module for cross-process RPC using [`quinn`].
use std::{fmt::Debug, future::Future, io, marker::PhantomData, pin::Pin, sync::Arc};
use quinn::ConnectionError;
use serde::{de::DeserializeOwned, Serialize};
use smallvec::SmallVec;
use tokio::task::JoinSet;
use tracing::{trace, trace_span, warn, Instrument};
use crate::{
channel::{
none::NoSender,
oneshot,
spsc::{self, BoxedReceiver, BoxedSender},
RecvError, SendError,
},
util::{now_or_never, AsyncReadVarintExt, WriteVarintExt},
BoxedFuture, RequestError, RpcMessage,
};
/// Error that can occur when writing the initial message when doing a
/// cross-process RPC.
#[derive(Debug, thiserror::Error)]
pub enum WriteError {
/// Error writing to the stream with quinn
#[error("error writing to stream: {0}")]
Quinn(#[from] quinn::WriteError),
/// Generic IO error, e.g. when serializing the message or when using
/// other transports.
#[error("error serializing: {0}")]
Io(#[from] io::Error),
}
impl From<WriteError> for io::Error {
fn from(e: WriteError) -> Self {
match e {
WriteError::Io(e) => e,
WriteError::Quinn(e) => e.into(),
}
}
}
/// Trait to abstract over a client connection to a remote service.
///
/// This isn't really that much abstracted, since the result of open_bi must
/// still be a quinn::SendStream and quinn::RecvStream. This is just so we
/// can have different connection implementations for normal quinn connections,
/// iroh connections, and possibly quinn connections with disabled encryption
/// for performance.
///
/// This is done as a trait instead of an enum, so we don't need an iroh
/// dependency in the main crate.
pub trait RemoteConnection: Send + Sync + Debug + 'static {
/// Boxed clone so the trait is dynable.
fn clone_boxed(&self) -> Box<dyn RemoteConnection>;
/// Open a bidirectional stream to the remote service.
fn open_bi(
&self,
) -> BoxedFuture<std::result::Result<(quinn::SendStream, quinn::RecvStream), RequestError>>;
}
/// A connection to a remote service.
///
/// Initially this does just have the endpoint and the address. Once a
/// connection is established, it will be stored.
#[derive(Debug, Clone)]
pub(crate) struct QuinnRemoteConnection(Arc<QuinnRemoteConnectionInner>);
#[derive(Debug)]
struct QuinnRemoteConnectionInner {
pub endpoint: quinn::Endpoint,
pub addr: std::net::SocketAddr,
pub connection: tokio::sync::Mutex<Option<quinn::Connection>>,
}
impl QuinnRemoteConnection {
pub fn new(endpoint: quinn::Endpoint, addr: std::net::SocketAddr) -> Self {
Self(Arc::new(QuinnRemoteConnectionInner {
endpoint,
addr,
connection: Default::default(),
}))
}
}
impl RemoteConnection for QuinnRemoteConnection {
fn clone_boxed(&self) -> Box<dyn RemoteConnection> {
Box::new(self.clone())
}
fn open_bi(
&self,
) -> BoxedFuture<std::result::Result<(quinn::SendStream, quinn::RecvStream), RequestError>>
{
let this = self.0.clone();
Box::pin(async move {
let mut guard = this.connection.lock().await;
let pair = match guard.as_mut() {
Some(conn) => {
// try to reuse the connection
match conn.open_bi().await {
Ok(pair) => pair,
Err(_) => {
// try with a new connection, just once
*guard = None;
connect_and_open_bi(&this.endpoint, &this.addr, guard).await?
}
}
}
None => connect_and_open_bi(&this.endpoint, &this.addr, guard).await?,
};
Ok(pair)
})
}
}
async fn connect_and_open_bi(
endpoint: &quinn::Endpoint,
addr: &std::net::SocketAddr,
mut guard: tokio::sync::MutexGuard<'_, Option<quinn::Connection>>,
) -> Result<(quinn::SendStream, quinn::RecvStream), RequestError> {
let conn = endpoint.connect(*addr, "localhost")?.await?;
let (send, recv) = conn.open_bi().await?;
*guard = Some(conn);
Ok((send, recv))
}
/// A connection to a remote service that can be used to send the initial message.
#[derive(Debug)]
pub struct RemoteSender<R, S>(
quinn::SendStream,
quinn::RecvStream,
std::marker::PhantomData<(R, S)>,
);
impl<R, S> RemoteSender<R, S> {
pub fn new(send: quinn::SendStream, recv: quinn::RecvStream) -> Self {
Self(send, recv, PhantomData)
}
pub async fn write(
self,
msg: impl Into<R>,
) -> std::result::Result<(quinn::SendStream, quinn::RecvStream), WriteError>
where
R: Serialize,
{
let RemoteSender(mut send, recv, _) = self;
let msg = msg.into();
let mut buf = SmallVec::<[u8; 128]>::new();
buf.write_length_prefixed(msg)?;
send.write_all(&buf).await?;
Ok((send, recv))
}
}
impl<T: DeserializeOwned> From<quinn::RecvStream> for oneshot::Receiver<T> {
fn from(mut read: quinn::RecvStream) -> Self {
let fut = async move {
let size = read.read_varint_u64().await?.ok_or(io::Error::new(
io::ErrorKind::UnexpectedEof,
"failed to read size",
))?;
let rest = read
.read_to_end(size as usize)
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let msg: T = postcard::from_bytes(&rest)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
io::Result::Ok(msg)
};
oneshot::Receiver::from(|| fut)
}
}
impl<T: RpcMessage> From<quinn::RecvStream> for spsc::Receiver<T> {
fn from(read: quinn::RecvStream) -> Self {
spsc::Receiver::Boxed(Box::new(QuinnReceiver {
recv: read,
_marker: PhantomData,
}))
}
}
impl From<quinn::SendStream> for NoSender {
fn from(write: quinn::SendStream) -> Self {
let _ = write;
NoSender
}
}
impl<T: RpcMessage> From<quinn::SendStream> for oneshot::Sender<T> {
fn from(mut writer: quinn::SendStream) -> Self {
oneshot::Sender::Boxed(Box::new(move |value| {
Box::pin(async move {
// write via a small buffer to avoid allocation for small values
let mut buf = SmallVec::<[u8; 128]>::new();
buf.write_length_prefixed(value)?;
writer.write_all(&buf).await?;
io::Result::Ok(())
})
}))
}
}
impl<T: RpcMessage> From<quinn::SendStream> for spsc::Sender<T> {
fn from(write: quinn::SendStream) -> Self {
spsc::Sender::Boxed(Box::new(QuinnSender {
send: write,
buffer: SmallVec::new(),
_marker: PhantomData,
}))
}
}
struct QuinnReceiver<T> {
recv: quinn::RecvStream,
_marker: std::marker::PhantomData<T>,
}
impl<T> Debug for QuinnReceiver<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QuinnReceiver").finish()
}
}
impl<T: RpcMessage> BoxedReceiver<T> for QuinnReceiver<T> {
fn recv(
&mut self,
) -> Pin<Box<dyn Future<Output = std::result::Result<Option<T>, RecvError>> + Send + '_>>
{
Box::pin(async {
let read = &mut self.recv;
let Some(size) = read.read_varint_u64().await? else {
return Ok(None);
};
let mut buf = vec![0; size as usize];
read.read_exact(&mut buf)
.await
.map_err(|e| io::Error::new(io::ErrorKind::UnexpectedEof, e))?;
let msg: T = postcard::from_bytes(&buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(msg))
})
}
}
impl<T> Drop for QuinnReceiver<T> {
fn drop(&mut self) {}
}
struct QuinnSender<T> {
send: quinn::SendStream,
buffer: SmallVec<[u8; 128]>,
_marker: std::marker::PhantomData<T>,
}
impl<T> Debug for QuinnSender<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QuinnSender").finish()
}
}
impl<T: RpcMessage> BoxedSender<T> for QuinnSender<T> {
fn send(&mut self, value: T) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>> {
Box::pin(async {
let value = value;
self.buffer.clear();
self.buffer.write_length_prefixed(value)?;
self.send.write_all(&self.buffer).await?;
self.buffer.clear();