iscp-rs 1.1.2

iSCPv2 Client Library
Documentation
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
use std::collections::HashMap;

use fnv::FnvHashMap;
use tokio::sync::{broadcast, mpsc};

use super::*;
use crate::{
    encoding::Decoder,
    message::{
        DownstreamCall, DownstreamChunk, DownstreamChunkAckComplete, DownstreamMetadata, Message,
        UpstreamCallAck, UpstreamChunkAck, message::Message as MessageEnum,
    },
    transport::Extractor,
};

#[derive(Debug)]
pub enum ReceivableDownstreamMsg {
    Chunk(DownstreamChunk),
    Metadata(DownstreamMetadata),
    ChunkAckComplete(DownstreamChunkAckComplete),
}

pub(super) async fn read_loop<T: TransportReader>(
    inner: Arc<ConnInner>,
    reader: &mut T,
    mut rx_read_loop_command: mpsc::UnboundedReceiver<ReadLoopCommand>,
    tx_pong: mpsc::Sender<crate::message::Pong>,
    tx_downstream_call: broadcast::Sender<DownstreamCall>,
    mut decoder: Decoder,
    mut extractor: Extractor,
) {
    let _ct_guard = inner.ct.clone().drop_guard();
    let mut channels = ReadLoopChannels::default();
    let mut buf = BytesMut::new();
    loop {
        buf.clear();
        tokio::select! {
            command = rx_read_loop_command.recv() => {
                if let Some(command) = command {
                    channels.process_command(command);
                } else {
                    return;
                }
            }
            result = reader.read(&mut buf) => {
                if let Err(e) = result {
                    log::error!("transport read error: {e}");
                    return;
                }
            }
            _ = inner.ct.cancelled() => {
                return;
            }
        }

        if let Err(e) = extractor.extract(&mut buf) {
            log::error!("message extraction error: {e}");
            return;
        }
        let msg = match decoder.decode_from(&buf) {
            Ok(msg) => msg,
            Err(e) => {
                log::error!("cannot decode message from stream: {e}");
                return;
            }
        };
        log::trace!("read message: {msg:?}");

        let msg = match msg.message {
            Some(MessageEnum::Ping(ping)) => {
                let pong = crate::message::Pong {
                    request_id: ping.request_id(),
                    ..Default::default()
                };
                if cancelled_return!(inner.ct, inner.tx_write_message.send(pong.into())).is_err() {
                    return;
                }
                continue;
            }
            Some(MessageEnum::Pong(pong)) => {
                if cancelled_return!(inner.ct, tx_pong.send(pong)).is_err() {
                    return;
                }
                continue;
            }
            Some(MessageEnum::Disconnect(disconnect)) => {
                log::info!(
                    "receive disconnect message, result_code = {:?}, {}",
                    disconnect.result_code(),
                    disconnect.result_string,
                );
                return;
            }
            Some(MessageEnum::DownstreamCall(call)) => {
                if tx_downstream_call.send(call).is_err() {
                    return;
                }
                continue;
            }
            _ => msg,
        };

        let Err(msg) = cancelled_return!(inner.ct, channels.process_message(msg)) else {
            continue;
        };

        if let Some(request_id) = msg.request_id()
            && request_id % 2 == 0
            && let Some(sender) = inner.remove_response_sender(request_id)
        {
            check_result!(debug, sender.send(msg), "response channel closed");
            continue;
        }

        log::trace!("drop received message");
        std::mem::drop(msg);
    }
}

#[derive(Default)]
pub struct ReadLoopChannels {
    tx_upstream_chunk_ack: FnvHashMap<u32, mpsc::Sender<UpstreamChunkAck>>,
    tx_downstream_msg: FnvHashMap<u32, mpsc::Sender<ReceivableDownstreamMsg>>,
    tx_call_ack: HashMap<String, oneshot::Sender<UpstreamCallAck>>,
}

pub enum ReadLoopCommand {
    AddUpstream {
        stream_id_alias: u32,
        tx_upstream_chunk_ack: mpsc::Sender<UpstreamChunkAck>,
    },
    RemoveUpstream {
        stream_id_alias: u32,
    },
    AddDownstream {
        stream_id_alias: u32,
        tx_downstream_msg: mpsc::Sender<ReceivableDownstreamMsg>,
    },
    RemoveDownstream {
        stream_id_alias: u32,
    },
    SubscribeCallAck {
        call_id: String,
        tx: oneshot::Sender<UpstreamCallAck>,
    },
    RemoveCallAck {
        call_id: String,
    },
}

impl ReadLoopChannels {
    pub fn process_command(&mut self, command: ReadLoopCommand) {
        match command {
            ReadLoopCommand::AddUpstream {
                stream_id_alias,
                tx_upstream_chunk_ack,
            } => {
                if self
                    .tx_upstream_chunk_ack
                    .insert(stream_id_alias, tx_upstream_chunk_ack)
                    .is_some()
                {
                    log::warn!("stream id alias {stream_id_alias} (up) may be duplicated");
                }
            }
            ReadLoopCommand::RemoveUpstream { stream_id_alias } => {
                if self
                    .tx_upstream_chunk_ack
                    .remove(&stream_id_alias)
                    .is_none()
                {
                    log::warn!("stream id alias {stream_id_alias} (up) not registered");
                }
            }
            ReadLoopCommand::AddDownstream {
                stream_id_alias,
                tx_downstream_msg,
            } => {
                if self
                    .tx_downstream_msg
                    .insert(stream_id_alias, tx_downstream_msg)
                    .is_some()
                {
                    log::warn!("stream id alias {stream_id_alias} (down) may be duplicated");
                }
            }
            ReadLoopCommand::RemoveDownstream { stream_id_alias } => {
                if self.tx_downstream_msg.remove(&stream_id_alias).is_none() {
                    log::warn!("stream id alias {stream_id_alias} (down) not registered");
                }
            }
            ReadLoopCommand::SubscribeCallAck { call_id, tx } => {
                if self.tx_call_ack.insert(call_id, tx).is_some() {
                    log::warn!("call id duplication detected");
                }
            }
            ReadLoopCommand::RemoveCallAck { call_id } => {
                self.tx_call_ack.remove(&call_id);
            }
        }
    }

    pub async fn process_message(&mut self, msg: Message) -> Result<(), Message> {
        match msg.message {
            Some(MessageEnum::UpstreamChunkAck(ack)) => {
                if let Some(tx) = self.tx_upstream_chunk_ack.get(&ack.stream_id_alias) {
                    let _ = tx.send(ack).await;
                }
            }
            Some(MessageEnum::DownstreamChunk(chunk)) => {
                if let Some(tx) = self.tx_downstream_msg.get(&chunk.stream_id_alias) {
                    let _ = tx.send(ReceivableDownstreamMsg::Chunk(chunk)).await;
                }
            }
            Some(MessageEnum::DownstreamMetadata(metadata)) => {
                if let Some(tx) = self.tx_downstream_msg.get(&metadata.stream_id_alias) {
                    let _ = tx.send(ReceivableDownstreamMsg::Metadata(metadata)).await;
                }
            }
            Some(MessageEnum::DownstreamChunkAckComplete(complete)) => {
                if let Some(tx) = self.tx_downstream_msg.get(&complete.stream_id_alias) {
                    let _ = tx
                        .send(ReceivableDownstreamMsg::ChunkAckComplete(complete))
                        .await;
                }
            }
            Some(MessageEnum::UpstreamCallAck(ack)) => {
                if let Some(tx) = self.tx_call_ack.remove(&ack.call_id) {
                    let _ = tx.send(ack);
                }
            }
            _ => {
                return Err(msg);
            }
        }
        Ok(())
    }
}

pub(crate) struct SendCommandGuard {
    command: Option<ReadLoopCommand>,
    tx: mpsc::UnboundedSender<ReadLoopCommand>,
}

impl SendCommandGuard {
    pub fn new(tx: &mpsc::UnboundedSender<ReadLoopCommand>, command: ReadLoopCommand) -> Self {
        Self {
            command: Some(command),
            tx: tx.clone(),
        }
    }
}

impl Drop for SendCommandGuard {
    fn drop(&mut self) {
        let _ = self.tx.send(self.command.take().unwrap());
    }
}

pub(crate) struct DownstreamCallReceiver(pub(super) broadcast::Receiver<DownstreamCall>);

impl DownstreamCallReceiver {
    #[cfg(test)]
    pub(crate) fn new(rx: broadcast::Receiver<DownstreamCall>) -> Self {
        Self(rx)
    }

    pub async fn recv(&mut self) -> Result<DownstreamCall, Error> {
        loop {
            match self.0.recv().await {
                Ok(msg) => {
                    return Ok(msg);
                }
                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                    return Err(Error::ConnectionClosed);
                }
                Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
                    // The dropped calls are unrecoverable; log and continue from the tail.
                    log::warn!("downstream call receiver lagged, {skipped} call(s) dropped");
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transport::TransportError;
    use tokio::sync::mpsc;
    use tokio::time::{Duration, timeout};
    use tokio_util::sync::CancellationToken;

    #[derive(Debug)]
    struct MockTransportReader {
        should_block: bool,
    }

    impl MockTransportReader {
        fn new(should_block: bool) -> Self {
            Self { should_block }
        }
    }

    impl TransportReader for MockTransportReader {
        async fn read(&mut self, _buf: &mut BytesMut) -> Result<(), TransportError> {
            if self.should_block {
                // Block forever to test cancellation
                std::future::pending().await
            } else {
                // Simulate a read error to terminate the loop
                Err(TransportError::new(std::io::Error::other("mock error")))
            }
        }

        async fn close(&mut self) -> Result<(), TransportError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_read_loop_cancellation_handling() {
        let ct = CancellationToken::new();
        let (waiter, _wg) = crate::internal::Waiter::new();
        let (waiter_rw, _wg_rw) = crate::internal::Waiter::new();

        let inner = Arc::new(ConnInner {
            tx_write_message: mpsc::channel(1).0,
            tx_unreliable_write_message: None,
            tx_read_loop_command: mpsc::unbounded_channel().0,
            tx_unreliable_read_loop_command: None,
            rx_downstream_call: broadcast::channel(1).1,
            response_senders: Mutex::new(Default::default()),
            request_id_counter: RequestIdCounter::new(),
            ct: ct.clone(),
            waiter,
            waiter_rw,
            response_message_timeout: Duration::from_secs(10),
            downstream_stream_id_alias_counter: Default::default(),
            channel_size: 100,
        });

        let (tx_pong, _rx_pong) = mpsc::channel(1);
        let (tx_downstream_call, _rx_downstream_call) = broadcast::channel(1);
        let (_tx_command, rx_command) = mpsc::unbounded_channel();

        let mut mock_reader = MockTransportReader::new(true); // Will block
        let decoder = crate::encoding::Decoder {};
        let extractor = crate::transport::Extractor::new(None, None);

        // Cancel immediately
        ct.cancel();

        let result = timeout(
            Duration::from_millis(100),
            read_loop(
                inner,
                &mut mock_reader,
                rx_command,
                tx_pong,
                tx_downstream_call,
                decoder,
                extractor,
            ),
        )
        .await;

        // The read loop should exit quickly due to cancellation
        assert!(
            result.is_ok(),
            "read_loop should exit quickly when cancelled"
        );
    }

    #[tokio::test]
    async fn test_read_loop_with_transport_error() {
        let ct = CancellationToken::new();
        let (waiter, _wg) = crate::internal::Waiter::new();
        let (waiter_rw, _wg_rw) = crate::internal::Waiter::new();

        let inner = Arc::new(ConnInner {
            tx_write_message: mpsc::channel(1).0,
            tx_unreliable_write_message: None,
            tx_read_loop_command: mpsc::unbounded_channel().0,
            tx_unreliable_read_loop_command: None,
            rx_downstream_call: broadcast::channel(1).1,
            response_senders: Mutex::new(Default::default()),
            request_id_counter: RequestIdCounter::new(),
            ct: ct.clone(),
            waiter,
            waiter_rw,
            response_message_timeout: Duration::from_secs(10),
            downstream_stream_id_alias_counter: Default::default(),
            channel_size: 100,
        });

        let (tx_pong, _rx_pong) = mpsc::channel(1);
        let (tx_downstream_call, _rx_downstream_call) = broadcast::channel(1);
        let (_tx_command, rx_command) = mpsc::unbounded_channel();

        let mut mock_reader = MockTransportReader::new(false); // Will return error
        let decoder = crate::encoding::Decoder {};
        let extractor = crate::transport::Extractor::new(None, None);

        // Should exit due to transport error
        let result = timeout(
            Duration::from_millis(100),
            read_loop(
                inner,
                &mut mock_reader,
                rx_command,
                tx_pong,
                tx_downstream_call,
                decoder,
                extractor,
            ),
        )
        .await;

        assert!(
            result.is_ok(),
            "read_loop should exit due to transport error"
        );
    }

    #[tokio::test]
    async fn test_cancellation_during_blocking_operations() {
        let ct = CancellationToken::new();
        let (waiter, _wg) = crate::internal::Waiter::new();
        let (waiter_rw, _wg_rw) = crate::internal::Waiter::new();

        let inner = Arc::new(ConnInner {
            tx_write_message: mpsc::channel(1).0,
            tx_unreliable_write_message: None,
            tx_read_loop_command: mpsc::unbounded_channel().0,
            tx_unreliable_read_loop_command: None,
            rx_downstream_call: broadcast::channel(1).1,
            response_senders: Mutex::new(Default::default()),
            request_id_counter: RequestIdCounter::new(),
            ct: ct.clone(),
            waiter,
            waiter_rw,
            response_message_timeout: Duration::from_secs(10),
            downstream_stream_id_alias_counter: Default::default(),
            channel_size: 100,
        });

        let (tx_pong, _rx_pong) = mpsc::channel(1);
        let (tx_downstream_call, _rx_downstream_call) = broadcast::channel(1);
        let (_tx_command, rx_command) = mpsc::unbounded_channel();

        let mut mock_reader = MockTransportReader::new(true); // Will block
        let decoder = crate::encoding::Decoder {};
        let extractor = crate::transport::Extractor::new(None, None);

        // Start the read loop
        let read_loop_task = tokio::spawn(async move {
            read_loop(
                inner,
                &mut mock_reader,
                rx_command,
                tx_pong,
                tx_downstream_call,
                decoder,
                extractor,
            )
            .await;
        });

        // Let it run briefly then cancel
        tokio::time::sleep(Duration::from_millis(10)).await;
        ct.cancel();

        // Should exit promptly due to cancellation
        let result = timeout(Duration::from_millis(100), read_loop_task).await;
        assert!(
            result.is_ok(),
            "read_loop should respect cancellation token"
        );
    }

    // A burst published before the receiver polls must arrive without loss now
    // that the channel is sized with `channel_size` instead of 1.
    #[tokio::test]
    async fn test_downstream_call_receiver_buffers_burst_without_loss() {
        const CHANNEL_SIZE: usize = 1024;
        const BURST: usize = 8;

        let (tx, rx) = broadcast::channel(CHANNEL_SIZE);
        let mut receiver = DownstreamCallReceiver::new(rx);

        // Publish the whole burst before the receiver polls.
        for i in 0..BURST {
            let call = DownstreamCall {
                call_id: format!("call-{i}"),
                request_call_id: format!("req-{i}"),
                ..Default::default()
            };
            tx.send(call).expect("send should succeed with a receiver");
        }

        // All calls must be received in order, none dropped.
        for i in 0..BURST {
            let call = timeout(Duration::from_secs(1), receiver.recv())
                .await
                .expect("recv should not hang")
                .expect("recv should not error");
            assert_eq!(
                call.request_call_id,
                format!("req-{i}"),
                "burst call {i} must be received without loss"
            );
        }
    }

    // At capacity 1, older calls are dropped and surface as a `Lagged` error
    // rather than being silently collapsed.
    #[tokio::test]
    async fn test_downstream_call_receiver_capacity_one_drops_and_lags() {
        let (tx, rx) = broadcast::channel(1);
        // Subscribe before sending so the receiver observes the lag.
        let mut raw_rx = rx.resubscribe();
        std::mem::drop(rx);

        for i in 0..3 {
            let call = DownstreamCall {
                request_call_id: format!("req-{i}"),
                ..Default::default()
            };
            tx.send(call).expect("send should succeed");
        }

        // At capacity 1 the receiver reports a lag of the dropped calls.
        match raw_rx.try_recv() {
            Err(broadcast::error::TryRecvError::Lagged(skipped)) => {
                assert_eq!(skipped, 2, "two older calls must be dropped at capacity 1");
            }
            other => panic!("expected Lagged error at capacity 1, got {other:?}"),
        }
    }
}