iroh_blobs/provider/
events.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
use std::{fmt::Debug, io, ops::Deref};

use irpc::{
    channel::{mpsc, none::NoSender, oneshot},
    rpc_requests, Channels, WithChannels,
};
use serde::{Deserialize, Serialize};
use snafu::Snafu;

use crate::{
    protocol::{
        GetManyRequest, GetRequest, ObserveRequest, PushRequest, ERR_INTERNAL, ERR_LIMIT,
        ERR_PERMISSION,
    },
    provider::{events::irpc_ext::IrpcClientExt, TransferStats},
    Hash,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ConnectMode {
    /// We don't get notification of connect events at all.
    #[default]
    None,
    /// We get a notification for connect events.
    Notify,
    /// We get a request for connect events and can reject incoming connections.
    Request,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ObserveMode {
    /// We don't get notification of connect events at all.
    #[default]
    None,
    /// We get a notification for connect events.
    Notify,
    /// We get a request for connect events and can reject incoming connections.
    Request,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum RequestMode {
    /// We don't get request events at all.
    #[default]
    None,
    /// We get a notification for each request, but no transfer events.
    Notify,
    /// We get a request for each request, and can reject incoming requests, but no transfer events.
    Request,
    /// We get a notification for each request as well as detailed transfer events.
    NotifyLog,
    /// We get a request for each request, and can reject incoming requests.
    /// We also get detailed transfer events.
    RequestLog,
    /// This request type is completely disabled. All requests will be rejected.
    Disabled,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ThrottleMode {
    /// We don't get these kinds of events at all
    #[default]
    None,
    /// We call throttle to give the event handler a way to throttle requests
    Throttle,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AbortReason {
    RateLimited,
    Permission,
}

#[derive(Debug, Snafu)]
pub enum ProgressError {
    Limit,
    Permission,
    #[snafu(transparent)]
    Internal {
        source: irpc::Error,
    },
}

impl From<ProgressError> for io::Error {
    fn from(value: ProgressError) -> Self {
        match value {
            ProgressError::Limit => io::ErrorKind::QuotaExceeded.into(),
            ProgressError::Permission => io::ErrorKind::PermissionDenied.into(),
            ProgressError::Internal { source } => source.into(),
        }
    }
}

pub trait HasErrorCode {
    fn code(&self) -> quinn::VarInt;
}

impl HasErrorCode for ProgressError {
    fn code(&self) -> quinn::VarInt {
        match self {
            ProgressError::Limit => ERR_LIMIT,
            ProgressError::Permission => ERR_PERMISSION,
            ProgressError::Internal { .. } => ERR_INTERNAL,
        }
    }
}

impl ProgressError {
    pub fn reason(&self) -> &'static [u8] {
        match self {
            ProgressError::Limit => b"limit",
            ProgressError::Permission => b"permission",
            ProgressError::Internal { .. } => b"internal",
        }
    }
}

impl From<AbortReason> for ProgressError {
    fn from(value: AbortReason) -> Self {
        match value {
            AbortReason::RateLimited => ProgressError::Limit,
            AbortReason::Permission => ProgressError::Permission,
        }
    }
}

impl From<irpc::channel::RecvError> for ProgressError {
    fn from(value: irpc::channel::RecvError) -> Self {
        ProgressError::Internal {
            source: value.into(),
        }
    }
}

impl From<irpc::channel::SendError> for ProgressError {
    fn from(value: irpc::channel::SendError) -> Self {
        ProgressError::Internal {
            source: value.into(),
        }
    }
}

pub type EventResult = Result<(), AbortReason>;
pub type ClientResult = Result<(), ProgressError>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventMask {
    /// Connection event mask
    pub connected: ConnectMode,
    /// Get request event mask
    pub get: RequestMode,
    /// Get many request event mask
    pub get_many: RequestMode,
    /// Push request event mask
    pub push: RequestMode,
    /// Observe request event mask
    pub observe: ObserveMode,
    /// throttling is somewhat costly, so you can disable it completely
    pub throttle: ThrottleMode,
}

impl Default for EventMask {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl EventMask {
    /// All event notifications are fully disabled. Push requests are disabled by default.
    pub const DEFAULT: Self = Self {
        connected: ConnectMode::None,
        get: RequestMode::None,
        get_many: RequestMode::None,
        push: RequestMode::Disabled,
        throttle: ThrottleMode::None,
        observe: ObserveMode::None,
    };

    /// All event notifications for read-only requests are fully enabled.
    ///
    /// If you want to enable push requests, which can write to the local store, you
    /// need to do it manually. Providing constants that have push enabled would
    /// risk misuse.
    pub const ALL_READONLY: Self = Self {
        connected: ConnectMode::Request,
        get: RequestMode::RequestLog,
        get_many: RequestMode::RequestLog,
        push: RequestMode::Disabled,
        throttle: ThrottleMode::Throttle,
        observe: ObserveMode::Request,
    };
}

/// Newtype wrapper that wraps an event so that it is a distinct type for the notify variant.
#[derive(Debug, Serialize, Deserialize)]
pub struct Notify<T>(T);

impl<T> Deref for Notify<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Debug, Default, Clone)]
pub struct EventSender {
    mask: EventMask,
    inner: Option<irpc::Client<ProviderProto>>,
}

#[derive(Debug, Default)]
enum RequestUpdates {
    /// Request tracking was not configured, all ops are no-ops
    #[default]
    None,
    /// Active request tracking, all ops actually send
    Active(mpsc::Sender<RequestUpdate>),
    /// Disabled request tracking, we just hold on to the sender so it drops
    /// once the request is completed or aborted.
    Disabled(#[allow(dead_code)] mpsc::Sender<RequestUpdate>),
}

#[derive(Debug)]
pub struct RequestTracker {
    updates: RequestUpdates,
    throttle: Option<(irpc::Client<ProviderProto>, u64, u64)>,
}

impl RequestTracker {
    fn new(
        updates: RequestUpdates,
        throttle: Option<(irpc::Client<ProviderProto>, u64, u64)>,
    ) -> Self {
        Self { updates, throttle }
    }

    /// A request tracker that doesn't track anything.
    pub const NONE: Self = Self {
        updates: RequestUpdates::None,
        throttle: None,
    };

    /// Transfer for index `index` started, size `size`
    pub async fn transfer_started(&self, index: u64, hash: &Hash, size: u64) -> irpc::Result<()> {
        if let RequestUpdates::Active(tx) = &self.updates {
            tx.send(
                TransferStarted {
                    index,
                    hash: *hash,
                    size,
                }
                .into(),
            )
            .await?;
        }
        Ok(())
    }

    /// Transfer progress for the previously reported blob, end_offset is the new end offset in bytes.
    pub async fn transfer_progress(&mut self, len: u64, end_offset: u64) -> ClientResult {
        if let RequestUpdates::Active(tx) = &mut self.updates {
            tx.try_send(TransferProgress { end_offset }.into()).await?;
        }
        if let Some((throttle, connection_id, request_id)) = &self.throttle {
            throttle
                .rpc(Throttle {
                    connection_id: *connection_id,
                    request_id: *request_id,
                    size: len,
                })
                .await??;
        }
        Ok(())
    }

    /// Transfer completed for the previously reported blob.
    pub async fn transfer_completed(&self, f: impl Fn() -> Box<TransferStats>) -> irpc::Result<()> {
        if let RequestUpdates::Active(tx) = &self.updates {
            tx.send(TransferCompleted { stats: f() }.into()).await?;
        }
        Ok(())
    }

    /// Transfer aborted for the previously reported blob.
    pub async fn transfer_aborted(&self, f: impl Fn() -> Box<TransferStats>) -> irpc::Result<()> {
        if let RequestUpdates::Active(tx) = &self.updates {
            tx.send(TransferAborted { stats: f() }.into()).await?;
        }
        Ok(())
    }
}

/// Client for progress notifications.
///
/// For most event types, the client can be configured to either send notifications or requests that
/// can have a response.
impl EventSender {
    /// A client that does not send anything.
    pub const DEFAULT: Self = Self {
        mask: EventMask::DEFAULT,
        inner: None,
    };

    pub fn new(client: tokio::sync::mpsc::Sender<ProviderMessage>, mask: EventMask) -> Self {
        Self {
            mask,
            inner: Some(irpc::Client::from(client)),
        }
    }

    pub fn channel(
        capacity: usize,
        mask: EventMask,
    ) -> (Self, tokio::sync::mpsc::Receiver<ProviderMessage>) {
        let (tx, rx) = tokio::sync::mpsc::channel(capacity);
        (Self::new(tx, mask), rx)
    }

    /// Log request events at trace level.
    pub fn tracing(&self, mask: EventMask) -> Self {
        use tracing::trace;
        let (tx, mut rx) = tokio::sync::mpsc::channel(32);
        n0_future::task::spawn(async move {
            fn log_request_events(
                mut rx: irpc::channel::mpsc::Receiver<RequestUpdate>,
                connection_id: u64,
                request_id: u64,
            ) {
                n0_future::task::spawn(async move {
                    while let Ok(Some(update)) = rx.recv().await {
                        trace!(%connection_id, %request_id, "{update:?}");
                    }
                });
            }
            while let Some(msg) = rx.recv().await {
                match msg {
                    ProviderMessage::ClientConnected(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                    }
                    ProviderMessage::ClientConnectedNotify(msg) => {
                        trace!("{:?}", msg.inner);
                    }
                    ProviderMessage::ConnectionClosed(msg) => {
                        trace!("{:?}", msg.inner);
                    }
                    ProviderMessage::GetRequestReceived(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::GetRequestReceivedNotify(msg) => {
                        trace!("{:?}", msg.inner);
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::GetManyRequestReceived(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::GetManyRequestReceivedNotify(msg) => {
                        trace!("{:?}", msg.inner);
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::PushRequestReceived(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::PushRequestReceivedNotify(msg) => {
                        trace!("{:?}", msg.inner);
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::ObserveRequestReceived(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::ObserveRequestReceivedNotify(msg) => {
                        trace!("{:?}", msg.inner);
                        log_request_events(msg.rx, msg.inner.connection_id, msg.inner.request_id);
                    }
                    ProviderMessage::Throttle(msg) => {
                        trace!("{:?}", msg.inner);
                        msg.tx.send(Ok(())).await.ok();
                    }
                }
            }
        });
        Self {
            mask,
            inner: Some(irpc::Client::from(tx)),
        }
    }

    /// A new client has been connected.
    pub async fn client_connected(&self, f: impl Fn() -> ClientConnected) -> ClientResult {
        if let Some(client) = &self.inner {
            match self.mask.connected {
                ConnectMode::None => {}
                ConnectMode::Notify => client.notify(Notify(f())).await?,
                ConnectMode::Request => client.rpc(f()).await??,
            }
        };
        Ok(())
    }

    /// A new client has been connected.
    pub async fn connection_closed(&self, f: impl Fn() -> ConnectionClosed) -> ClientResult {
        if let Some(client) = &self.inner {
            client.notify(f()).await?;
        };
        Ok(())
    }

    /// Abstract request, to DRY the 3 to 4 request types.
    ///
    /// DRYing stuff with lots of bounds is no fun at all...
    pub(crate) async fn request<Req>(
        &self,
        f: impl FnOnce() -> Req,
        connection_id: u64,
        request_id: u64,
    ) -> Result<RequestTracker, ProgressError>
    where
        ProviderProto: From<RequestReceived<Req>>,
        ProviderMessage: From<WithChannels<RequestReceived<Req>, ProviderProto>>,
        RequestReceived<Req>: Channels<
            ProviderProto,
            Tx = oneshot::Sender<EventResult>,
            Rx = mpsc::Receiver<RequestUpdate>,
        >,
        ProviderProto: From<Notify<RequestReceived<Req>>>,
        ProviderMessage: From<WithChannels<Notify<RequestReceived<Req>>, ProviderProto>>,
        Notify<RequestReceived<Req>>:
            Channels<ProviderProto, Tx = NoSender, Rx = mpsc::Receiver<RequestUpdate>>,
    {
        let client = self.inner.as_ref();
        Ok(self.create_tracker((
            match self.mask.get {
                RequestMode::None => RequestUpdates::None,
                RequestMode::Notify if client.is_some() => {
                    let msg = RequestReceived {
                        request: f(),
                        connection_id,
                        request_id,
                    };
                    RequestUpdates::Disabled(
                        client.unwrap().notify_streaming(Notify(msg), 32).await?,
                    )
                }
                RequestMode::Request if client.is_some() => {
                    let msg = RequestReceived {
                        request: f(),
                        connection_id,
                        request_id,
                    };
                    let (tx, rx) = client.unwrap().client_streaming(msg, 32).await?;
                    // bail out if the request is not allowed
                    rx.await??;
                    RequestUpdates::Disabled(tx)
                }
                RequestMode::NotifyLog if client.is_some() => {
                    let msg = RequestReceived {
                        request: f(),
                        connection_id,
                        request_id,
                    };
                    RequestUpdates::Active(client.unwrap().notify_streaming(Notify(msg), 32).await?)
                }
                RequestMode::RequestLog if client.is_some() => {
                    let msg = RequestReceived {
                        request: f(),
                        connection_id,
                        request_id,
                    };
                    let (tx, rx) = client.unwrap().client_streaming(msg, 32).await?;
                    // bail out if the request is not allowed
                    rx.await??;
                    RequestUpdates::Active(tx)
                }
                RequestMode::Disabled => {
                    return Err(ProgressError::Permission);
                }
                _ => RequestUpdates::None,
            },
            connection_id,
            request_id,
        )))
    }

    fn create_tracker(
        &self,
        (updates, connection_id, request_id): (RequestUpdates, u64, u64),
    ) -> RequestTracker {
        let throttle = match self.mask.throttle {
            ThrottleMode::None => None,
            ThrottleMode::Throttle => self
                .inner
                .clone()
                .map(|client| (client, connection_id, request_id)),
        };
        RequestTracker::new(updates, throttle)
    }
}

#[rpc_requests(message = ProviderMessage)]
#[derive(Debug, Serialize, Deserialize)]
pub enum ProviderProto {
    /// A new client connected to the provider.
    #[rpc(tx = oneshot::Sender<EventResult>)]
    ClientConnected(ClientConnected),

    /// A new client connected to the provider. Notify variant.
    #[rpc(tx = NoSender)]
    ClientConnectedNotify(Notify<ClientConnected>),

    /// A client disconnected from the provider.
    #[rpc(tx = NoSender)]
    ConnectionClosed(ConnectionClosed),

    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = oneshot::Sender<EventResult>)]
    /// A new get request was received from the provider.
    GetRequestReceived(RequestReceived<GetRequest>),

    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = NoSender)]
    /// A new get request was received from the provider.
    GetRequestReceivedNotify(Notify<RequestReceived<GetRequest>>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = oneshot::Sender<EventResult>)]
    GetManyRequestReceived(RequestReceived<GetManyRequest>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = NoSender)]
    GetManyRequestReceivedNotify(Notify<RequestReceived<GetManyRequest>>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = oneshot::Sender<EventResult>)]
    PushRequestReceived(RequestReceived<PushRequest>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = NoSender)]
    PushRequestReceivedNotify(Notify<RequestReceived<PushRequest>>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = oneshot::Sender<EventResult>)]
    ObserveRequestReceived(RequestReceived<ObserveRequest>),

    /// A new get request was received from the provider.
    #[rpc(rx = mpsc::Receiver<RequestUpdate>, tx = NoSender)]
    ObserveRequestReceivedNotify(Notify<RequestReceived<ObserveRequest>>),

    #[rpc(tx = oneshot::Sender<EventResult>)]
    Throttle(Throttle),
}

mod proto {
    use iroh::NodeId;
    use serde::{Deserialize, Serialize};

    use crate::{provider::TransferStats, Hash};

    #[derive(Debug, Serialize, Deserialize)]
    pub struct ClientConnected {
        pub connection_id: u64,
        pub node_id: NodeId,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct ConnectionClosed {
        pub connection_id: u64,
    }

    /// A new get request was received from the provider.
    #[derive(Debug, Serialize, Deserialize)]
    pub struct RequestReceived<R> {
        /// The connection id. Multiple requests can be sent over the same connection.
        pub connection_id: u64,
        /// The request id. There is a new id for each request.
        pub request_id: u64,
        /// The request
        pub request: R,
    }

    /// Request to throttle sending for a specific request.
    #[derive(Debug, Serialize, Deserialize)]
    pub struct Throttle {
        /// The connection id. Multiple requests can be sent over the same connection.
        pub connection_id: u64,
        /// The request id. There is a new id for each request.
        pub request_id: u64,
        /// Size of the chunk to be throttled. This will usually be 16 KiB.
        pub size: u64,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct TransferProgress {
        /// The end offset of the chunk that was sent.
        pub end_offset: u64,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct TransferStarted {
        pub index: u64,
        pub hash: Hash,
        pub size: u64,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct TransferCompleted {
        pub stats: Box<TransferStats>,
    }

    #[derive(Debug, Serialize, Deserialize)]
    pub struct TransferAborted {
        pub stats: Box<TransferStats>,
    }

    /// Stream of updates for a single request
    #[derive(Debug, Serialize, Deserialize, derive_more::From)]
    pub enum RequestUpdate {
        /// Start of transfer for a blob, mandatory event
        Started(TransferStarted),
        /// Progress for a blob - optional event
        Progress(TransferProgress),
        /// Successful end of transfer
        Completed(TransferCompleted),
        /// Aborted end of transfer
        Aborted(TransferAborted),
    }
}
pub use proto::*;

mod irpc_ext {
    use std::future::Future;

    use irpc::{
        channel::{mpsc, none::NoSender},
        Channels, RpcMessage, Service, WithChannels,
    };

    pub trait IrpcClientExt<S: Service> {
        fn notify_streaming<Req, Update>(
            &self,
            msg: Req,
            local_update_cap: usize,
        ) -> impl Future<Output = irpc::Result<mpsc::Sender<Update>>>
        where
            S: From<Req>,
            S::Message: From<WithChannels<Req, S>>,
            Req: Channels<S, Tx = NoSender, Rx = mpsc::Receiver<Update>>,
            Update: RpcMessage;
    }

    impl<S: Service> IrpcClientExt<S> for irpc::Client<S> {
        fn notify_streaming<Req, Update>(
            &self,
            msg: Req,
            local_update_cap: usize,
        ) -> impl Future<Output = irpc::Result<mpsc::Sender<Update>>>
        where
            S: From<Req>,
            S::Message: From<WithChannels<Req, S>>,
            Req: Channels<S, Tx = NoSender, Rx = mpsc::Receiver<Update>>,
            Update: RpcMessage,
        {
            let client = self.clone();
            async move {
                let request = client.request().await?;
                match request {
                    irpc::Request::Local(local) => {
                        let (req_tx, req_rx) = mpsc::channel(local_update_cap);
                        local
                            .send((msg, NoSender, req_rx))
                            .await
                            .map_err(irpc::Error::from)?;
                        Ok(req_tx)
                    }
                    irpc::Request::Remote(remote) => {
                        let (s, _) = remote.write(msg).await?;
                        Ok(s.into())
                    }
                }
            }
        }
    }
}