remoc 0.19.1

🦑 Remote multiplexed objects, channels, observable collections and RPC making remote interactions seamless. Provides multiple remote channels and RPC over TCP, TLS or any other transport.
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
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
//! Tests for the io channel.
//!
//! Like the bin channel, at least one end of the io channel must be remote.
//! These tests send the receiver to remote and keep the sender local.

use rand::{Rng, RngExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[cfg(feature = "js")]
use wasm_bindgen_test::wasm_bindgen_test;

use crate::loop_channel;
use remoc::{exec, rch::io};

// ============================================================================
// Basic functionality tests
// ============================================================================

/// Test sized channel with simple send/receive.
/// Pattern: Send receiver to remote, keep sender local.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_simple() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(11);

    // Verify size is known upfront
    assert_eq!(rx.size(), Some(11));
    assert_eq!(tx.expected_size(), Some(11));

    // Send receiver to remote
    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Size should still be known after transport
    assert_eq!(rx.size(), Some(11));

    // Run write and read concurrently to avoid flow control blocking
    let write_task = exec::spawn(async move {
        tx.write_all(b"hello world").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello world");
    assert_eq!(rx.bytes_received(), 11);
}

/// Test unsized channel with simple send/receive.
/// Pattern: Send receiver to remote, keep sender local.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_simple() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    // Size is unknown initially
    assert_eq!(rx.size(), None);
    assert_eq!(tx.expected_size(), None);

    // Send receiver to remote
    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Size still unknown
    assert_eq!(rx.size(), None);

    let write_task = exec::spawn(async move {
        tx.write_all(b"hello world").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello world");
    assert_eq!(rx.bytes_received(), 11);
    // Size should now be known after EOF
    assert_eq!(rx.size(), Some(11));
}

/// Test sized channel with sender sent to remote.
/// Pattern: Send sender to remote, keep receiver local.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_send_sender() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Sender>().await;

    let (tx, mut rx) = io::sized(11);

    // Send sender to remote
    a_tx.send(tx).await.unwrap();
    let mut tx = b_rx.recv().await.unwrap().unwrap();

    // Run write and read concurrently
    let read_task = exec::spawn(async move {
        let mut buf = Vec::new();
        rx.read_to_end(&mut buf).await.unwrap();
        assert_eq!(buf, b"hello world");
        assert_eq!(rx.bytes_received(), 11);
    });

    tx.write_all(b"hello world").await.unwrap();
    tx.shutdown().await.unwrap();

    read_task.await.unwrap();
}

// ============================================================================
// Edge case: Size 0
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_zero() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(0);
    assert_eq!(rx.size(), Some(0));

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        // Should not be able to write anything, just shutdown
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert!(buf.is_empty());
    assert_eq!(rx.bytes_received(), 0);
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_zero() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        // Write nothing, just shutdown
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert!(buf.is_empty());
    assert_eq!(rx.bytes_received(), 0);
    assert_eq!(rx.size(), Some(0));
}

// ============================================================================
// Failure cases: Size mismatch
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_send_more_than_announced() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(5);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Start reader to consume data so writer can proceed until it fails
    let read_task = exec::spawn(async move {
        let mut buf = Vec::new();
        let _ = rx.read_to_end(&mut buf).await;
    });

    // Try to write more than announced - should fail
    let result = tx.write_all(b"hello world").await;
    assert!(result.is_err(), "writing more than announced should fail");
    let err = result.unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::WriteZero);

    read_task.await.unwrap();
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_send_less_than_announced_sender_shutdown() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(100);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Start reader
    let read_task = exec::spawn(async move {
        let mut buf = Vec::new();
        let _ = rx.read_to_end(&mut buf).await;
    });

    // Write less than announced
    tx.write_all(b"short").await.unwrap();
    // Shutdown should fail because we didn't write enough
    let result = tx.shutdown().await;
    assert!(result.is_err(), "shutdown with insufficient data should fail");
    let err = result.unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);

    read_task.await.unwrap();
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_send_less_than_announced_receiver_eof() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(100);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Write less than announced
    tx.write_all(b"short").await.unwrap();
    // Drop sender without shutdown to simulate abnormal close
    drop(tx);

    // Receiver should fail with size mismatch
    let mut buf = Vec::new();
    let result = rx.read_to_end(&mut buf).await;
    assert!(result.is_err(), "receiver should fail on size mismatch");
    let err = result.unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
}

// ============================================================================
// Failure cases: Unsized without shutdown
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_no_shutdown() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Write some data but don't shutdown
    tx.write_all(b"hello").await.unwrap();
    // Drop sender without shutdown
    drop(tx);

    // Receiver should fail because size was never sent
    let mut buf = Vec::new();
    let result = rx.read_to_end(&mut buf).await;
    assert!(result.is_err(), "receiver should fail without proper shutdown");
    let err = result.unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
}

// ============================================================================
// Large data transfer
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_large_data() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let mut rng = rand::rng();
    let size: usize = rng.random_range(100_000..500_000);
    let mut data = vec![0u8; size];
    rng.fill_bytes(&mut data);

    let (mut tx, rx) = io::sized(size as u64);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let data_clone = data.clone();
    let write_task = exec::spawn(async move {
        tx.write_all(&data_clone).await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf.len(), size);
    assert_eq!(buf, data);
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_large_data() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let mut rng = rand::rng();
    let size: usize = rng.random_range(100_000..500_000);
    let mut data = vec![0u8; size];
    rng.fill_bytes(&mut data);

    let (mut tx, rx) = io::channel();

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let data_clone = data.clone();
    let write_task = exec::spawn(async move {
        tx.write_all(&data_clone).await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf.len(), size);
    assert_eq!(buf, data);
    assert_eq!(rx.size(), Some(size as u64));
}

// ============================================================================
// Multiple writes
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_multiple_writes() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(15);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        tx.write_all(b"hello").await.unwrap();
        tx.write_all(b" ").await.unwrap();
        tx.write_all(b"world").await.unwrap();
        tx.write_all(b"!!!!").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello world!!!!");
    assert_eq!(rx.bytes_received(), 15);
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_multiple_writes() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        tx.write_all(b"one ").await.unwrap();
        tx.write_all(b"two ").await.unwrap();
        tx.write_all(b"three").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"one two three");
}

// ============================================================================
// Bytes tracking
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn bytes_tracking() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    assert_eq!(tx.bytes_written(), 0);
    assert_eq!(rx.bytes_received(), 0);

    // Writer in background
    let write_task = exec::spawn(async move {
        tx.write_all(b"12345").await.unwrap();
        assert_eq!(tx.bytes_written(), 5);
        tx.write_all(b"67890").await.unwrap();
        assert_eq!(tx.bytes_written(), 10);
        tx.shutdown().await.unwrap();
    });

    let mut buf = [0u8; 5];
    rx.read_exact(&mut buf).await.unwrap();
    assert_eq!(rx.bytes_received(), 5);

    rx.read_exact(&mut buf).await.unwrap();
    assert_eq!(rx.bytes_received(), 10);

    write_task.await.unwrap();
}

// ============================================================================
// Forwarding
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_forward() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;
    let ((mut c_tx, _), (_, mut d_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(11);

    // Send to first remote
    a_tx.send(rx).await.unwrap();
    let rx = b_rx.recv().await.unwrap().unwrap();

    // Forward to second remote
    c_tx.send(rx).await.unwrap();
    let mut rx = d_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        tx.write_all(b"hello world").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello world");
}

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn unsized_forward() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;
    let ((mut c_tx, _), (_, mut d_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::channel();

    // Size unknown initially
    assert_eq!(rx.size(), None);

    // Send to first remote
    a_tx.send(rx).await.unwrap();
    let rx = b_rx.recv().await.unwrap().unwrap();

    // Forward to second remote
    c_tx.send(rx).await.unwrap();
    let mut rx = d_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        tx.write_all(b"hello world").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello world");
    // Size should now be known after EOF
    assert_eq!(rx.size(), Some(11));
}

// ============================================================================
// Empty write
// ============================================================================

#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn empty_write() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(5);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        // Empty write should be a no-op
        tx.write_all(b"").await.unwrap();
        tx.write_all(b"hello").await.unwrap();
        tx.write_all(b"").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    let mut buf = Vec::new();
    rx.read_to_end(&mut buf).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(buf, b"hello");
}

// ============================================================================
// Partial read
// ============================================================================

/// Test partial reads with sized channel using read_exact.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn sized_partial_reads() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let (mut tx, rx) = io::sized(10);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Check remaining before any reads
    assert_eq!(rx.remaining(), Some(10));

    let write_task = exec::spawn(async move {
        tx.write_all(b"0123456789").await.unwrap();
        tx.shutdown().await.unwrap();
    });

    // Read in small chunks
    let mut buf = [0u8; 3];
    rx.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"012");
    assert_eq!(rx.bytes_received(), 3);
    assert_eq!(rx.remaining(), Some(7));

    let mut buf = [0u8; 4];
    rx.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"3456");
    assert_eq!(rx.bytes_received(), 7);
    assert_eq!(rx.remaining(), Some(3));

    let mut buf = [0u8; 3];
    rx.read_exact(&mut buf).await.unwrap();
    assert_eq!(&buf, b"789");
    assert_eq!(rx.bytes_received(), 10);
    assert_eq!(rx.remaining(), Some(0));

    // Next read should return EOF (0 bytes)
    let mut buf = [0u8; 1];
    let n = rx.read(&mut buf).await.unwrap();
    assert_eq!(n, 0);

    write_task.await.unwrap();
}

// ============================================================================
// File transfer simulation
// ============================================================================

/// Simulates a file transfer use case where metadata and io::Receiver are sent together.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn file_transfer_simulation() {
    use serde::{Deserialize, Serialize};

    crate::init();

    /// File transfer request - demonstrates embedding io::Receiver in a struct.
    #[derive(Debug, Serialize, Deserialize)]
    struct FileTransfer {
        filename: String,
        size: u64,
        data: io::Receiver,
    }

    let ((mut client_tx, _), (_, mut server_rx)) = loop_channel::<FileTransfer>().await;

    // Simulate file content
    let file_content = b"This is the content of the file being transferred.\n".repeat(100);
    let file_size = file_content.len() as u64;

    // Create io channel with known size
    let (mut io_tx, io_rx) = io::sized(file_size);

    // Client sends transfer request with embedded receiver
    client_tx
        .send(FileTransfer { filename: "example.txt".to_string(), size: file_size, data: io_rx })
        .await
        .unwrap();

    // Client writes file content (in background to avoid deadlock)
    let file_content_clone = file_content.clone();
    let write_task = exec::spawn(async move {
        // Simulate chunked file reading
        for chunk in file_content_clone.chunks(1024) {
            io_tx.write_all(chunk).await.unwrap();
        }
        io_tx.shutdown().await.unwrap();
    });

    // Server receives transfer request
    let transfer = server_rx.recv().await.unwrap().unwrap();
    assert_eq!(transfer.filename, "example.txt");
    assert_eq!(transfer.size, file_size);

    // Server can check size from receiver too
    let mut data_rx = transfer.data;
    assert_eq!(data_rx.size(), Some(file_size));
    assert_eq!(data_rx.remaining(), Some(file_size));

    // Server reads file content
    let mut received = Vec::new();
    data_rx.read_to_end(&mut received).await.unwrap();

    // Verify
    assert_eq!(received.len() as u64, file_size);
    assert_eq!(received, file_content);
    assert_eq!(data_rx.bytes_received(), file_size);
    assert_eq!(data_rx.remaining(), Some(0));

    write_task.await.unwrap();
}

/// Test with unknown size - useful for streaming content of unknown length.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn streaming_transfer_unknown_size() {
    use serde::{Deserialize, Serialize};

    crate::init();

    /// Streaming data request - size unknown upfront.
    #[derive(Debug, Serialize, Deserialize)]
    struct StreamTransfer {
        name: String,
        data: io::Receiver,
    }

    let ((mut client_tx, _), (_, mut server_rx)) = loop_channel::<StreamTransfer>().await;

    // Create io channel with unknown size
    let (mut io_tx, io_rx) = io::channel();

    // Client sends transfer request
    client_tx.send(StreamTransfer { name: "live_stream".to_string(), data: io_rx }).await.unwrap();

    // Client writes data in chunks (simulating live data)
    let write_task = exec::spawn(async move {
        for i in 0..10 {
            let chunk = format!("Chunk {}\n", i);
            io_tx.write_all(chunk.as_bytes()).await.unwrap();
        }
        io_tx.shutdown().await.unwrap();
    });

    // Server receives
    let transfer = server_rx.recv().await.unwrap().unwrap();
    assert_eq!(transfer.name, "live_stream");

    let mut data_rx = transfer.data;
    // Size unknown initially
    assert_eq!(data_rx.size(), None);
    assert_eq!(data_rx.remaining(), None);

    // Read all data
    let mut received = Vec::new();
    data_rx.read_to_end(&mut received).await.unwrap();

    // After EOF, size becomes known
    assert!(data_rx.size().is_some());
    assert_eq!(data_rx.remaining(), Some(0));

    // Verify content
    let expected: String = (0..10).map(|i| format!("Chunk {}\n", i)).collect();
    assert_eq!(String::from_utf8(received).unwrap(), expected);

    write_task.await.unwrap();
}

// ============================================================================
// tokio::io::copy integration tests
// ============================================================================

/// Test that tokio::io::copy works with io channel.
/// Important: tokio::io::copy does NOT call shutdown - caller must do it.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn tokio_copy_integration() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let data = b"Hello from tokio::io::copy!".repeat(100);
    let size = data.len() as u64;

    let (mut tx, rx) = io::sized(size);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let data_clone = data.clone();
    let write_task = exec::spawn(async move {
        let mut reader = std::io::Cursor::new(data_clone);

        // tokio::io::copy just copies bytes, does NOT call shutdown
        let copied = tokio::io::copy(&mut reader, &mut tx).await.unwrap();
        assert_eq!(copied, size);

        // We MUST call shutdown ourselves
        tx.shutdown().await.unwrap();
    });

    // Read using tokio::io::copy to a Vec
    let mut output = Vec::new();
    let received = tokio::io::copy(&mut rx, &mut output).await.unwrap();

    write_task.await.unwrap();

    assert_eq!(received, size);
    assert_eq!(output, data);
}

/// Test sized channel behavior: receiver uses size as contract, not EOF.
/// With sized(N), once N bytes are received, transfer is complete.
/// Shutdown is still recommended for cleanup but receiver doesn't require it.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn tokio_copy_sized_no_shutdown_succeeds() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let data = b"data without explicit shutdown";
    let size = data.len() as u64;

    let (mut tx, rx) = io::sized(size);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        let mut reader = std::io::Cursor::new(data);
        tokio::io::copy(&mut reader, &mut tx).await.unwrap();
        // NOT calling shutdown - for sized channels this still works
        // because size IS the contract
        drop(tx);
    });

    // For sized channels, receiver succeeds once it reads the expected bytes
    let mut output = Vec::new();
    let result = tokio::io::copy(&mut rx, &mut output).await;
    assert!(result.is_ok());
    assert_eq!(output, data);

    write_task.await.unwrap();
}

/// Test unsized channel: NOT calling shutdown causes receiver error.
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn tokio_copy_unsized_no_shutdown_fails() {
    crate::init();
    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let data = b"data without proper shutdown";

    let (mut tx, rx) = io::channel(); // unsized!

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    let write_task = exec::spawn(async move {
        let mut reader = std::io::Cursor::new(data);
        tokio::io::copy(&mut reader, &mut tx).await.unwrap();
        // NOT calling shutdown - for unsized, this causes receiver error
        drop(tx);
    });

    // Receiver should fail because size was never sent
    let mut output = Vec::new();
    let result = tokio::io::copy(&mut rx, &mut output).await;
    assert!(result.is_err());
    assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::UnexpectedEof);

    write_task.await.unwrap();
}

/// Test behavior when read error occurs during copy.
/// Important: if read fails, shutdown must NOT be called!
#[cfg_attr(not(feature = "js"), tokio::test)]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn tokio_copy_read_error_no_shutdown() {
    use std::{
        pin::Pin,
        task::{Context, Poll},
    };
    use tokio::io::AsyncRead;

    crate::init();

    /// A reader that fails after reading some bytes.
    struct FailingReader {
        data: Vec<u8>,
        pos: usize,
        fail_at: usize,
    }

    impl AsyncRead for FailingReader {
        fn poll_read(
            mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut tokio::io::ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            if self.pos >= self.fail_at {
                return Poll::Ready(Err(std::io::Error::other("simulated read error")));
            }
            let remaining = self.data.len() - self.pos;
            let to_read = remaining.min(buf.remaining()).min(self.fail_at - self.pos);
            if to_read > 0 {
                buf.put_slice(&self.data[self.pos..self.pos + to_read]);
                self.pos += to_read;
            }
            Poll::Ready(Ok(()))
        }
    }

    let ((mut a_tx, _), (_, mut b_rx)) = loop_channel::<io::Receiver>().await;

    let full_data = b"0123456789".repeat(100); // 1000 bytes
    let size = full_data.len() as u64;

    let (mut tx, rx) = io::sized(size);

    a_tx.send(rx).await.unwrap();
    let mut rx = b_rx.recv().await.unwrap().unwrap();

    // Writer: read from failing source, DO NOT shutdown on error
    let write_task = exec::spawn(async move {
        let mut reader = FailingReader {
            data: full_data.clone(),
            pos: 0,
            fail_at: 500, // Fail after 500 bytes
        };

        let result = tokio::io::copy(&mut reader, &mut tx).await;

        // Read failed!
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Other);

        // IMPORTANT: We do NOT call shutdown because read failed.
        // Just drop the sender - this signals error to receiver.
        drop(tx);
    });

    // Receiver: should fail because not enough data was sent
    let mut output = Vec::new();
    let result = tokio::io::copy(&mut rx, &mut output).await;

    // Receiver gets error (channel closed with size mismatch)
    assert!(result.is_err());

    write_task.await.unwrap();
}