openrtc 0.2.1

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
#![cfg(target_arch = "wasm32")]

use anyhow::Result;
use async_channel::Sender;
use futures::{future::Either, io::AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt};
use iroh::{
    endpoint::{Connection, RecvStream, SendStream},
    protocol::{AcceptError, ProtocolHandler, Router},
    Endpoint, EndpointAddr, EndpointId, Watcher as _,
};
use n0_future::{boxed::BoxStream, task};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::sync::RwLock;
use tokio_stream::wrappers::BroadcastStream;
use tokio_util::codec::{BytesCodec, FramedWrite};
use tokio_util::compat::TokioAsyncReadCompatExt;
use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue};
use wasm_streams::{
    readable::sys::ReadableStream as JsReadableStream,
    writable::sys::WritableStream as JsWritableStream, ReadableStream, WritableStream,
};

use crate::iroh_connection_policy::{
    decide_inbound_install, decide_outbound_install, should_redial_without_precheck,
    ExistingConnectionState, IrohConnectionInstallDecision,
};

const READABLE_STREAM_CHUNK_BYTES: usize = 256 * 1024;

// Define stream type
#[derive(Debug)]
pub enum IncomingStreamType {
    Bi(SendStream, RecvStream),
    Uni(RecvStream),
}

pub struct IncomingStream {
    pub endpoint_id: EndpointId,
    pub stream: IncomingStreamType,
}

/// Per-incoming-stream QUIC accept logging is extremely noisy (heartbeats and app
/// traffic each open uni streams). Enable only when debugging stream routing:
/// `globalThis.__OPENRTC_DEBUG_WASM_STREAMS__ = true` in the browser console.
fn wasm_debug_streams() -> bool {
    let global = js_sys::global();
    js_sys::Reflect::get(
        &global,
        &JsValue::from_str("__OPENRTC_DEBUG_WASM_STREAMS__"),
    )
    .ok()
    .map(|v| v == JsValue::TRUE)
    .unwrap_or(false)
}

fn is_manual_disconnect_close_reason(error: Option<&str>) -> bool {
    crate::lifecycle_reason::reason_is_manual_disconnect(error)
}

/// Wall-clock ms between low-rate WASM console summaries of accepted QUIC streams.
const STREAM_ACCEPT_SUMMARY_INTERVAL_MS: u64 = 30_000;

static WASM_ACCEPT_STREAM_UNI: AtomicU64 = AtomicU64::new(0);
static WASM_ACCEPT_STREAM_BI: AtomicU64 = AtomicU64::new(0);
static WASM_ACCEPT_STREAM_LAST_LOG_MS: AtomicU64 = AtomicU64::new(0);

fn record_stream_accepted(is_uni: bool) {
    if is_uni {
        WASM_ACCEPT_STREAM_UNI.fetch_add(1, Ordering::Relaxed);
    } else {
        WASM_ACCEPT_STREAM_BI.fetch_add(1, Ordering::Relaxed);
    }
    maybe_log_stream_accept_summary();
}

fn maybe_log_stream_accept_summary() {
    let now_ms = js_sys::Date::now() as u64;
    let prev_last = WASM_ACCEPT_STREAM_LAST_LOG_MS.load(Ordering::Relaxed);
    if now_ms.saturating_sub(prev_last) < STREAM_ACCEPT_SUMMARY_INTERVAL_MS {
        return;
    }
    let claimed = WASM_ACCEPT_STREAM_LAST_LOG_MS
        .fetch_update(Ordering::SeqCst, Ordering::Relaxed, |last| {
            if now_ms.saturating_sub(last) < STREAM_ACCEPT_SUMMARY_INTERVAL_MS {
                None
            } else {
                Some(now_ms)
            }
        })
        .is_ok();
    if !claimed {
        return;
    }
    let uni = WASM_ACCEPT_STREAM_UNI.swap(0, Ordering::Relaxed);
    let bi = WASM_ACCEPT_STREAM_BI.swap(0, Ordering::Relaxed);
    if uni == 0 && bi == 0 {
        return;
    }
    web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
        "[pluto-rtc][wasm-node] accepted QUIC streams (since last summary, min {}s apart): uni={} bi={}",
        STREAM_ACCEPT_SUMMARY_INTERVAL_MS / 1000,
        uni,
        bi
    )));
}

fn local_prefers_outbound(local_endpoint_id: EndpointId, remote_endpoint_id: EndpointId) -> bool {
    local_endpoint_id.to_string() > remote_endpoint_id.to_string()
}

#[derive(Debug, Clone)]
pub struct IrohWasmNode {
    router: Router,
    accept_events: broadcast::Sender<AcceptEvent>,
    connections: Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: Arc<RwLock<HashMap<EndpointId, f64>>>,
    connect_addr_waiters: Arc<RwLock<HashMap<EndpointId, Vec<Sender<ConnectEvent>>>>>,
    incoming_streams: async_channel::Sender<IncomingStream>,
    incoming_streams_receiver: async_channel::Receiver<IncomingStream>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ConnectEvent {
    Connected,
    Closed { error: Option<String> },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum AcceptEvent {
    Accepted {
        endpoint_id: EndpointId,
    },
    Closed {
        endpoint_id: EndpointId,
        error: Option<String>,
        /// True when the local side initiated the close (e.g. `disconnect()`
        /// after auth rejection). The replacement-wait polling loop must NOT
        /// run for locally-closed connections — there is no replacement coming
        /// and polling burns the WASM event loop indefinitely.
        was_locally_closed: bool,
    },
}

#[derive(Debug, Clone)]
pub struct PlutoniumProtocol {
    event_sender: broadcast::Sender<AcceptEvent>,
    stream_sender: async_channel::Sender<IncomingStream>,
    connections: Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: Arc<RwLock<HashMap<EndpointId, f64>>>,
    local_endpoint_id: EndpointId,
}

struct WasmConnectionLoopOutcome {
    close_reason: Option<String>,
    was_locally_closed: bool,
}

async fn run_connection_loop(
    source: &'static str,
    connection: &Connection,
    stream_sender: async_channel::Sender<IncomingStream>,
) -> WasmConnectionLoopOutcome {
    let endpoint_id = connection.remote_id();
    let stable_id = connection.stable_id();

    loop {
        tokio::select! {
            biased;
            res = connection.accept_bi() => {
                match res {
                    Ok((send, recv)) => {
                        record_stream_accepted(false);
                        if wasm_debug_streams() {
                            web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                                "[pluto-rtc][wasm-node][{}] accept_bi got stream endpoint_id={}",
                                source,
                                endpoint_id
                            )));
                        }
                        if let Err(e) = stream_sender.send(IncomingStream {
                            endpoint_id,
                            stream: IncomingStreamType::Bi(send, recv),
                        }).await {
                            web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                                "[pluto-rtc][wasm-node][{}] FAILED to forward bi stream endpoint_id={} error={}",
                                source,
                                endpoint_id,
                                e
                            )));
                        }
                    }
                    Err(e) => {
                        web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                            "[pluto-rtc][wasm-node][{}] accept_bi error endpoint_id={} error={:?}",
                            source,
                            endpoint_id,
                            e
                        )));
                        break;
                    }
                }
            }
            res = connection.accept_uni() => {
                match res {
                    Ok(recv) => {
                        record_stream_accepted(true);
                        if wasm_debug_streams() {
                            web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                                "[pluto-rtc][wasm-node][{}] accept_uni got stream endpoint_id={}",
                                source,
                                endpoint_id
                            )));
                        }
                        if let Err(e) = stream_sender.send(IncomingStream {
                            endpoint_id,
                            stream: IncomingStreamType::Uni(recv),
                        }).await {
                            web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                                "[pluto-rtc][wasm-node][{}] FAILED to forward uni stream endpoint_id={} error={}",
                                source,
                                endpoint_id,
                                e
                            )));
                        }
                    }
                    Err(e) => {
                        web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                            "[pluto-rtc][wasm-node][{}] accept_uni error endpoint_id={} error={:?}",
                            source,
                            endpoint_id,
                            e
                        )));
                        break;
                    }
                }
            }
            _ = connection.closed() => {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][{}] connection.closed() fired endpoint_id={}",
                    source,
                    endpoint_id
                )));
                break;
            }
        }
    }

    let close_reason_native = connection.close_reason();
    let close_reason = close_reason_native
        .as_ref()
        .map(|reason| format!("{:?}", reason));
    let was_locally_closed = matches!(
        close_reason_native,
        Some(iroh::endpoint::ConnectionError::LocallyClosed)
    );
    web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
        "[pluto-rtc][wasm-node][{}] connection loop exited endpoint_id={} stable_id={} close_reason={:?} was_locally_closed={}",
        source,
        endpoint_id,
        stable_id,
        close_reason_native,
        was_locally_closed
    )));

    WasmConnectionLoopOutcome {
        close_reason,
        was_locally_closed,
    }
}

async fn remove_connection_if_current(
    endpoint_id: EndpointId,
    stable_id: usize,
    connections: &Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: &Arc<RwLock<HashMap<EndpointId, f64>>>,
) {
    let mut conns = connections.write().await;
    let should_remove = conns
        .get(&endpoint_id)
        .map(|current| current.stable_id() == stable_id)
        .unwrap_or(false);
    if should_remove {
        conns.remove(&endpoint_id);
        connection_insert_at_ms.write().await.remove(&endpoint_id);
    }
}

impl PlutoniumProtocol {
    pub const ALPN: &[u8] = b"plutonium/p2p/1";

    pub fn new(
        event_sender: broadcast::Sender<AcceptEvent>,
        stream_sender: async_channel::Sender<IncomingStream>,
        connections: Arc<RwLock<HashMap<EndpointId, Connection>>>,
        connection_insert_at_ms: Arc<RwLock<HashMap<EndpointId, f64>>>,
        local_endpoint_id: EndpointId,
    ) -> Self {
        Self {
            event_sender,
            stream_sender,
            connections,
            connection_insert_at_ms,
            local_endpoint_id,
        }
    }

    async fn handle_connection(
        self,
        connection: Connection,
    ) -> std::result::Result<(), AcceptError> {
        let endpoint_id = connection.remote_id();
        let stable_id = connection.stable_id();
        web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[pluto-rtc][wasm-node][accept] ENTER endpoint_id={} stable_id={}",
            endpoint_id, stable_id
        )));
        println!("[PlutoniumWasm] Accepting connection from: {}", endpoint_id);

        // Sticky first-alive policy: if we already have a live connection
        // for this endpoint (either an earlier accept or our own completed
        // dial), close this duplicate accept and keep the existing one. Both
        // peers applying this rule converge on the same underlying QUIC
        // connection (the one that completed first on both sides), which
        // eliminates the "wrong transport" blackhole caused by symmetric
        // dialing. We only replace when the existing connection is already
        // closed (dead leg), so we never tear down a working transport.
        //
        // Zombie-replace exception: after a peer restart, the remote has new
        // local state and dials fresh (new stable_id), but our side still has
        // the old connection object which iroh's QUIC layer believes is alive
        // until keep-alive timeout (~27 s). If the stored connection is older
        // than ZOMBIE_REPLACE_AGE_MS it cannot be a symmetric-dial race
        // (those settle within a few RTTs), so we replace it eagerly rather
        // than wait for QUIC to discover the deadness.
        {
            let now_ms = js_sys::Date::now();
            let mut conns = self.connections.write().await;
            let mut insert_times = self.connection_insert_at_ms.write().await;
            if let Some(previous) = conns.get(&endpoint_id).cloned() {
                let previous_inserted_at =
                    insert_times.get(&endpoint_id).copied().unwrap_or(now_ms);
                let previous_age_ms = (now_ms - previous_inserted_at).max(0.0) as u64;
                match decide_inbound_install(Some(ExistingConnectionState {
                    same_stable_id: previous.stable_id() == stable_id,
                    alive: previous.close_reason().is_none(),
                    age_ms: previous_age_ms,
                    prefer_fresh_duplicate: !local_prefers_outbound(
                        self.local_endpoint_id,
                        endpoint_id,
                    ),
                })) {
                    IrohConnectionInstallDecision::Install => {
                        if previous.stable_id() != stable_id {
                            web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                                "[pluto-rtc][wasm-node][accept] replacing dead stored connection endpoint_id={} previous_stable_id={} incoming_stable_id={}",
                                endpoint_id,
                                previous.stable_id(),
                                stable_id
                            )));
                        }
                    }
                    IrohConnectionInstallDecision::KeepExisting { close_fresh_reason } => {
                        web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                            "[pluto-rtc][wasm-node][accept] existing live connection present; closing duplicate accept endpoint_id={} existing_stable_id={} accept_stable_id={} previous_age_ms={}",
                            endpoint_id,
                            previous.stable_id(),
                            stable_id,
                            previous_age_ms,
                        )));
                        drop(insert_times);
                        drop(conns);
                        connection.close(0u8.into(), close_fresh_reason.as_bytes());
                        return Ok(());
                    }
                    IrohConnectionInstallDecision::ReplaceExisting {
                        close_previous_reason,
                    } => {
                        web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                            "[pluto-rtc][wasm-node][accept] replacing zombie stored connection (remote likely restarted) endpoint_id={} previous_stable_id={} incoming_stable_id={} previous_age_ms={}",
                            endpoint_id,
                            previous.stable_id(),
                            stable_id,
                            previous_age_ms,
                        )));
                        // Force-close the zombie so iroh drops its half of
                        // the QUIC connection immediately and the peer's
                        // read/write loops unwind without waiting for the
                        // 120 s idle timeout.
                        previous.close(0u8.into(), close_previous_reason.as_bytes());
                    }
                }
            }
            conns.insert(endpoint_id, connection.clone());
            insert_times.insert(endpoint_id, now_ms);
        }

        match self
            .event_sender
            .send(AcceptEvent::Accepted { endpoint_id })
        {
            Ok(receivers) => {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][accept] Accepted event dispatched endpoint_id={} receivers={}",
                    endpoint_id, receivers
                )));
            }
            Err(e) => {
                web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][accept] FAILED to send Accepted event endpoint_id={} error={}",
                    endpoint_id, e
                )));
            }
        }

        let outcome = run_connection_loop("accept", &connection, self.stream_sender.clone()).await;

        self.event_sender
            .send(AcceptEvent::Closed {
                endpoint_id,
                error: outcome.close_reason,
                was_locally_closed: outcome.was_locally_closed,
            })
            .ok();

        remove_connection_if_current(
            endpoint_id,
            stable_id,
            &self.connections,
            &self.connection_insert_at_ms,
        )
        .await;

        Ok(())
    }
}

impl ProtocolHandler for PlutoniumProtocol {
    #[allow(refining_impl_trait)]
    fn accept(
        &self,
        connection: Connection,
    ) -> impl n0_future::Future<Output = std::result::Result<(), AcceptError>> + std::marker::Send
    {
        let proto = self.clone();
        async move { proto.handle_connection(connection).await }
    }
}

/// Install a freshly-dialed outbound connection into the shared map using
/// the sticky first-alive policy. If a live connection already exists (an
/// earlier accept from the peer's own dial, or a previous successful dial),
/// we close this duplicate dial and keep the existing one. Both sides
/// applying this rule converge on a single underlying QUIC connection.
/// Returns `true` if this connection was installed and should be tracked as
/// the active transport; `false` if we deferred to an existing live leg
/// (caller should close the freshly-dialed `connection` and drop it).
async fn install_outbound_connection(
    endpoint_id: EndpointId,
    connection: &Connection,
    connections: &Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: &Arc<RwLock<HashMap<EndpointId, f64>>>,
    local_endpoint_id: EndpointId,
    source: &str,
) -> bool {
    let stable_id = connection.stable_id();
    let now_ms = js_sys::Date::now();
    let mut conns = connections.write().await;
    let mut insert_times = connection_insert_at_ms.write().await;
    if let Some(previous) = conns.get(&endpoint_id).cloned() {
        let previous_inserted_at = insert_times.get(&endpoint_id).copied().unwrap_or(now_ms);
        let previous_age_ms = (now_ms - previous_inserted_at).max(0.0) as u64;
        match decide_outbound_install(Some(ExistingConnectionState {
            same_stable_id: previous.stable_id() == stable_id,
            alive: previous.close_reason().is_none(),
            age_ms: previous_age_ms,
            prefer_fresh_duplicate: local_prefers_outbound(local_endpoint_id, endpoint_id),
        })) {
            IrohConnectionInstallDecision::Install => {
                if previous.stable_id() != stable_id {
                    web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                        "[pluto-rtc][wasm-node][{}] replacing dead stored connection endpoint_id={} previous_stable_id={} outgoing_stable_id={}",
                        source,
                        endpoint_id,
                        previous.stable_id(),
                        stable_id
                    )));
                }
            }
            IrohConnectionInstallDecision::KeepExisting { .. } => {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][{}] existing live connection present; deferring to existing endpoint_id={} existing_stable_id={} dialed_stable_id={} previous_age_ms={}",
                    source,
                    endpoint_id,
                    previous.stable_id(),
                    stable_id,
                    previous_age_ms,
                )));
                return false;
            }
            IrohConnectionInstallDecision::ReplaceExisting {
                close_previous_reason,
            } => {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][{}] replacing zombie stored connection (local dial fresh) endpoint_id={} previous_stable_id={} outgoing_stable_id={} previous_age_ms={}",
                    source,
                    endpoint_id,
                    previous.stable_id(),
                    stable_id,
                    previous_age_ms,
                )));
                previous.close(0u8.into(), close_previous_reason.as_bytes());
            }
        }
    }
    conns.insert(endpoint_id, connection.clone());
    insert_times.insert(endpoint_id, now_ms);
    true
}

async fn connect(
    endpoint: &Endpoint,
    endpoint_id: EndpointId,
    event_sender: Sender<ConnectEvent>,
    accept_events: Option<broadcast::Sender<AcceptEvent>>,
    connections: Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: Arc<RwLock<HashMap<EndpointId, f64>>>,
    stream_sender: async_channel::Sender<IncomingStream>,
) -> Result<()> {
    // Sticky first-alive precheck. See `connect_addr` for the rationale —
    // dialing on top of a live connection causes the peer's
    // newest-inbound-wins policy to evict the existing good transport.
    {
        let conns = connections.read().await;
        if let Some(existing) = conns.get(&endpoint_id) {
            if !local_prefers_outbound(endpoint.id(), endpoint_id)
                && !should_redial_without_precheck(existing.close_reason().is_none())
            {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][connect] live connection already present; reusing without redial endpoint_id={} existing_stable_id={}",
                    endpoint_id,
                    existing.stable_id()
                )));
                drop(conns);
                let _ = event_sender.send(ConnectEvent::Connected).await;
                return Ok(());
            }
        }
    }

    let connection = endpoint
        .connect(endpoint_id, PlutoniumProtocol::ALPN)
        .await?;
    let stable_id = connection.stable_id();

    let installed = install_outbound_connection(
        endpoint_id,
        &connection,
        &connections,
        &connection_insert_at_ms,
        endpoint.id(),
        "connect",
    )
    .await;

    if !installed {
        // A live connection already exists for this endpoint (the sticky
        // first-alive rule). Close this duplicate dial so the remote drops
        // its half of this QUIC connection, but still notify the TS side
        // that the transport is connected — it will use the existing entry
        // in the connections map.
        connection.close(
            0u8.into(),
            crate::lifecycle_reason::REASON_DUPLICATE_DIAL_SUPERSEDED.as_bytes(),
        );
        if let Err(e) = event_sender.send(ConnectEvent::Connected).await {
            web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[pluto-rtc][wasm-node][connect] event_sender.send(Connected) FAILED after superseded dial endpoint_id={} stable_id={} error={}",
                endpoint_id, stable_id, e
            )));
        }
        let _ = event_sender
            .send(ConnectEvent::Closed { error: None })
            .await;
        return Ok(());
    }

    if let Err(e) = event_sender.send(ConnectEvent::Connected).await {
        web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[pluto-rtc][wasm-node][connect] event_sender.send(Connected) FAILED (channel closed — TS side gave up?) endpoint_id={} stable_id={} error={}",
            endpoint_id, stable_id, e
        )));
        return Err(anyhow::anyhow!("event channel closed"));
    }

    let outcome = run_connection_loop("connect", &connection, stream_sender).await;

    if let Err(e) = event_sender
        .send(ConnectEvent::Closed {
            error: outcome.close_reason.clone(),
        })
        .await
    {
        web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[pluto-rtc][wasm-node][connect] event_sender.send(Closed) FAILED (TS already torn down) endpoint_id={} error={}",
            endpoint_id, e
        )));
    }

    if is_manual_disconnect_close_reason(outcome.close_reason.as_deref()) {
        if let Some(sender) = accept_events {
            let _ = sender.send(AcceptEvent::Closed {
                endpoint_id,
                error: outcome.close_reason.clone(),
                was_locally_closed: outcome.was_locally_closed,
            });
        }
    }

    // Keep the endpoint mapping visible until the close event has been
    // processed by the runtime bridge. This mirrors the accept-side ordering
    // and avoids a transient "no live transport" gap while duplicate-close
    // recovery is deciding whether to preserve or replace the connection.
    remove_connection_if_current(
        endpoint_id,
        stable_id,
        &connections,
        &connection_insert_at_ms,
    )
    .await;

    Ok(())
}

async fn connect_addr(
    endpoint: &Endpoint,
    endpoint_id: EndpointId,
    endpoint_addr: EndpointAddr,
    connect_addr_waiters: Arc<RwLock<HashMap<EndpointId, Vec<Sender<ConnectEvent>>>>>,
    accept_events: Option<broadcast::Sender<AcceptEvent>>,
    connections: Arc<RwLock<HashMap<EndpointId, Connection>>>,
    connection_insert_at_ms: Arc<RwLock<HashMap<EndpointId, f64>>>,
    stream_sender: async_channel::Sender<IncomingStream>,
) -> Result<()> {
    // Sticky first-alive precheck: if a live outbound or accepted connection
    // already exists for this endpoint, do NOT initiate a fresh QUIC dial.
    // The previous behaviour dialed first and closed the duplicate after the
    // fact, but `endpoint.connect()` always reaches the peer — and the peer's
    // newest-inbound-wins policy then closes the EXISTING good connection
    // with `replaced-by-new-inbound`, leaving both sides without a working
    // transport. Short-circuiting here keeps the existing live connection
    // authoritative and lets racing callers (e.g. WasmBridge.connectToDevice
    // → connect_device + Client.connect) converge on it.
    {
        let conns = connections.read().await;
        if let Some(existing) = conns.get(&endpoint_id) {
            if !local_prefers_outbound(endpoint.id(), endpoint_id)
                && !should_redial_without_precheck(existing.close_reason().is_none())
            {
                web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node][connect_addr] live connection already present; reusing without redial endpoint_id={} existing_stable_id={}",
                    endpoint_id,
                    existing.stable_id()
                )));
                drop(conns);
                publish_connect_addr_event(
                    &connect_addr_waiters,
                    endpoint_id,
                    ConnectEvent::Connected,
                )
                .await;
                return Ok(());
            }
        }
    }

    web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
        "[pluto-rtc][wasm-node][connect_addr] dialing endpoint_id={} addr={:?}",
        endpoint_id, endpoint_addr
    )));
    let connection = match endpoint
        .connect(endpoint_addr, PlutoniumProtocol::ALPN)
        .await
    {
        Ok(conn) => {
            web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[pluto-rtc][wasm-node][connect_addr] connected! endpoint_id={} stable_id={}",
                endpoint_id,
                conn.stable_id()
            )));
            conn
        }
        Err(e) => {
            web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[pluto-rtc][wasm-node][connect_addr] connect FAILED endpoint_id={} error={}",
                endpoint_id, e
            )));
            publish_connect_addr_event(
                &connect_addr_waiters,
                endpoint_id,
                ConnectEvent::Closed {
                    error: Some(e.to_string()),
                },
            )
            .await;
            return Err(e.into());
        }
    };
    let stable_id = connection.stable_id();

    let installed = install_outbound_connection(
        endpoint_id,
        &connection,
        &connections,
        &connection_insert_at_ms,
        endpoint.id(),
        "connect_addr",
    )
    .await;

    if !installed {
        // A live connection slipped in between the precheck and our
        // `endpoint.connect()` completing. Close this duplicate locally so
        // the remote drops its half of the QUIC connection promptly. We
        // can't avoid the brief peer-side accept here, but we also don't
        // want to keep the duplicate around — the sticky first-alive rule
        // has already locked in an authoritative transport.
        connection.close(
            0u8.into(),
            crate::lifecycle_reason::REASON_DUPLICATE_DIAL_SUPERSEDED.as_bytes(),
        );
        let delivered =
            publish_connect_addr_event(&connect_addr_waiters, endpoint_id, ConnectEvent::Connected)
                .await;
        if delivered == 0 {
            web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[pluto-rtc][wasm-node][connect_addr] no live waiters after superseded dial endpoint_id={} stable_id={}",
                endpoint_id, stable_id
            )));
        }
        publish_connect_addr_event(
            &connect_addr_waiters,
            endpoint_id,
            ConnectEvent::Closed { error: None },
        )
        .await;
        return Ok(());
    }

    let delivered =
        publish_connect_addr_event(&connect_addr_waiters, endpoint_id, ConnectEvent::Connected)
            .await;
    if delivered == 0 {
        web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[pluto-rtc][wasm-node][connect_addr] no live waiters after connect; closing unobserved transport endpoint_id={} stable_id={}",
            endpoint_id, stable_id
        )));
        // TS side has already torn down the receiver — closing the connection
        // so we don't leak a half-attached QUIC conn that nothing observes.
        connection.close(0u8.into(), b"ts-channel-closed");
        return Err(anyhow::anyhow!("event channel closed"));
    }

    let outcome = run_connection_loop("connect_addr", &connection, stream_sender).await;

    let delivered = publish_connect_addr_event(
        &connect_addr_waiters,
        endpoint_id,
        ConnectEvent::Closed {
            error: outcome.close_reason.clone(),
        },
    )
    .await;
    if delivered == 0 {
        web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
            "[pluto-rtc][wasm-node][connect_addr] no live waiters for Closed event endpoint_id={}",
            endpoint_id
        )));
    }

    // Only manual disconnects need the global accept-event bridge fallback.
    // Ordinary replacement churn (`replaced-by-new-inbound`,
    // `duplicate-dial-superseded`, etc.) belongs to the per-dial ConnectEvent
    // bridge; sending it through AcceptEvent makes the accept state machine
    // mark healthy replacement traffic as broken.
    if is_manual_disconnect_close_reason(outcome.close_reason.as_deref()) {
        if let Some(sender) = accept_events {
            let _ = sender.send(AcceptEvent::Closed {
                endpoint_id,
                error: outcome.close_reason.clone(),
                was_locally_closed: outcome.was_locally_closed,
            });
        }
    }

    // Keep the endpoint mapping visible until the close event has been
    // processed by the runtime bridge. This mirrors the accept-side ordering
    // and avoids a transient "no live transport" gap while duplicate-close
    // recovery is deciding whether to preserve or replace the connection.
    remove_connection_if_current(
        endpoint_id,
        stable_id,
        &connections,
        &connection_insert_at_ms,
    )
    .await;

    Ok(())
}

async fn publish_connect_addr_event(
    connect_addr_waiters: &Arc<RwLock<HashMap<EndpointId, Vec<Sender<ConnectEvent>>>>>,
    endpoint_id: EndpointId,
    event: ConnectEvent,
) -> usize {
    let waiters = {
        let waiters = connect_addr_waiters.read().await;
        waiters.get(&endpoint_id).cloned().unwrap_or_default()
    };

    let mut delivered = 0usize;
    for waiter in waiters {
        if waiter.send(event.clone()).await.is_ok() {
            delivered += 1;
        }
    }
    delivered
}

async fn clear_connect_addr_waiters(
    connect_addr_waiters: &Arc<RwLock<HashMap<EndpointId, Vec<Sender<ConnectEvent>>>>>,
    endpoint_id: EndpointId,
) {
    connect_addr_waiters.write().await.remove(&endpoint_id);
}

impl IrohWasmNode {
    pub async fn spawn_with_endpoint(endpoint: Endpoint) -> Result<Self> {
        let (event_sender, _event_receiver) = broadcast::channel(128);
        let (stream_sender, stream_receiver) = async_channel::bounded(64);
        let connections = Arc::new(RwLock::new(HashMap::new()));
        let connection_insert_at_ms = Arc::new(RwLock::new(HashMap::new()));
        let connect_addr_waiters = Arc::new(RwLock::new(HashMap::new()));

        let proto = PlutoniumProtocol::new(
            event_sender.clone(),
            stream_sender.clone(),
            connections.clone(),
            connection_insert_at_ms.clone(),
            endpoint.id(),
        );
        let router = Router::builder(endpoint)
            .accept(PlutoniumProtocol::ALPN, proto)
            .spawn();

        Ok(Self {
            router,
            accept_events: event_sender,
            connections,
            connection_insert_at_ms,
            connect_addr_waiters,
            incoming_streams: stream_sender,
            incoming_streams_receiver: stream_receiver,
        })
    }

    pub fn endpoint(&self) -> &Endpoint {
        self.router.endpoint()
    }

    pub async fn is_connected(&self, endpoint_id: EndpointId) -> bool {
        let conns = self.connections.read().await;
        if let Some(conn) = conns.get(&endpoint_id) {
            conn.close_reason().is_none()
        } else {
            false
        }
    }

    pub fn secret_key(&self) -> Vec<u8> {
        self.router.endpoint().secret_key().to_bytes().to_vec()
    }

    pub async fn node_addr(&self) -> Result<iroh::EndpointAddr> {
        let endpoint = self.router.endpoint();
        // Ticket minting is a UI-facing operation for browser apps (share links,
        // QR codes, drive grants). Do not let a slow or stale relay-online future
        // monopolize that path while another dial/reconnect is active. The
        // watched address is iroh's current best view; wait briefly for relay
        // readiness, then use the current address so callers can fail/retry at
        // the application boundary instead of hanging the page for minutes.
        let online = endpoint.online().fuse();
        let deadline = gloo_timers::future::sleep(std::time::Duration::from_millis(1_500)).fuse();
        futures::pin_mut!(online, deadline);
        if matches!(
            futures::future::select(online, deadline).await,
            Either::Right(_)
        ) {
            web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(
                "[pluto-rtc][wasm-node] node_addr relay online wait timed out; using current watched address",
            ));
        }
        Ok(endpoint.watch_addr().get())
    }

    pub fn accept_events(&self) -> BoxStream<AcceptEvent> {
        let receiver = self.accept_events.subscribe();
        Box::pin(
            BroadcastStream::new(receiver).filter_map(|event| futures::future::ready(event.ok())),
        )
    }

    pub fn connect(&self, endpoint_id: EndpointId) -> impl Stream<Item = ConnectEvent> + Unpin {
        let (event_sender, event_receiver) = async_channel::bounded(16);
        let endpoint = self.router.endpoint().clone();
        let connections = self.connections.clone();
        let connection_insert_at_ms = self.connection_insert_at_ms.clone();
        let stream_sender = self.incoming_streams.clone();
        let accept_events = self.accept_events.clone();

        task::spawn(async move {
            let res = connect(
                &endpoint,
                endpoint_id,
                event_sender.clone(),
                Some(accept_events),
                connections,
                connection_insert_at_ms,
                stream_sender,
            )
            .await;
            if let Err(e) = res {
                let error = Some(e.to_string());
                event_sender.send(ConnectEvent::Closed { error }).await.ok();
            }
        });

        Box::pin(event_receiver)
    }

    pub fn connect_addr(
        &self,
        endpoint_id: EndpointId,
        endpoint_addr: EndpointAddr,
    ) -> impl Stream<Item = ConnectEvent> + Unpin {
        let (event_sender, event_receiver) = async_channel::bounded(16);
        let endpoint = self.router.endpoint().clone();
        let connections = self.connections.clone();
        let connection_insert_at_ms = self.connection_insert_at_ms.clone();
        let connect_addr_waiters = self.connect_addr_waiters.clone();
        let stream_sender = self.incoming_streams.clone();
        let accept_events = self.accept_events.clone();

        task::spawn(async move {
            {
                let mut waiters = connect_addr_waiters.write().await;
                if let Some(existing_waiters) = waiters.get_mut(&endpoint_id) {
                    existing_waiters.push(event_sender);
                    web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                        "[pluto-rtc][wasm-node] connect_addr joined in-flight dial endpoint_id={} waiter_count={}",
                        endpoint_id,
                        existing_waiters.len()
                    )));
                    return;
                }
                waiters.insert(endpoint_id, vec![event_sender.clone()]);
            }

            web_sys::console::log_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[pluto-rtc][wasm-node] connect_addr task spawned endpoint_id={}",
                endpoint_id
            )));
            let res = connect_addr(
                &endpoint,
                endpoint_id,
                endpoint_addr,
                connect_addr_waiters.clone(),
                Some(accept_events),
                connections,
                connection_insert_at_ms,
                stream_sender,
            )
            .await;
            if let Err(e) = res {
                web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
                    "[pluto-rtc][wasm-node] connect_addr task FAILED endpoint_id={} error={}",
                    endpoint_id, e
                )));
            }
            clear_connect_addr_waiters(&connect_addr_waiters, endpoint_id).await;
        });

        Box::pin(event_receiver)
    }

    pub async fn disconnect(&self, endpoint_id: EndpointId) -> Result<()> {
        self.disconnect_with_reason(
            endpoint_id,
            crate::lifecycle_reason::REASON_DISCONNECTED_BY_USER,
        )
        .await
    }

    pub async fn disconnect_with_reason(
        &self,
        endpoint_id: EndpointId,
        reason: &str,
    ) -> Result<()> {
        let connection = {
            let mut conns = self.connections.write().await;
            let removed = conns.remove(&endpoint_id);
            self.connection_insert_at_ms
                .write()
                .await
                .remove(&endpoint_id);
            removed
        };

        if let Some(conn) = connection {
            web_sys::console::info_1(&wasm_bindgen::JsValue::from_str(&format!(
                "[PlutoRTC][teardown-trace] WasmNode::disconnect endpoint_id={endpoint_id} (QUIC reason: {reason})"
            )));
            conn.close(1u8.into(), reason.as_bytes());
        }
        Ok(())
    }

    pub async fn open_bi(&self, endpoint_id: EndpointId) -> Result<(SendStream, RecvStream)> {
        let connection = {
            let conns = self.connections.read().await;
            conns.get(&endpoint_id).cloned()
        };

        if let Some(conn) = connection {
            let (send, recv) = conn.open_bi().await?;
            Ok((send, recv))
        } else {
            Err(anyhow::anyhow!("No active connection to {}", endpoint_id))
        }
    }

    pub async fn open_uni(&self, endpoint_id: EndpointId) -> Result<SendStream> {
        let connection = {
            let conns = self.connections.read().await;
            conns.get(&endpoint_id).cloned()
        };

        if let Some(conn) = connection {
            let send = conn.open_uni().await?;
            Ok(send)
        } else {
            Err(anyhow::anyhow!("No active connection to {}", endpoint_id))
        }
    }

    pub fn incoming_streams_stream(&self) -> impl Stream<Item = IncomingStream> {
        self.incoming_streams_receiver.clone()
    }

    pub async fn active_endpoint_ids(&self) -> Vec<EndpointId> {
        let conns = self.connections.read().await;
        conns.keys().cloned().collect()
    }

    pub async fn get_connection(&self, endpoint_id: EndpointId) -> Option<Connection> {
        let conns = self.connections.read().await;
        conns.get(&endpoint_id).cloned()
    }

    pub async fn add_node_addr(
        &self,
        node_id: EndpointId,
        _relay_url: Option<String>,
        _direct_addresses: Vec<String>,
    ) -> Result<()> {
        let _ = self
            .router
            .endpoint()
            .connect(node_id, PlutoniumProtocol::ALPN)
            .await;
        Ok(())
    }
}

#[wasm_bindgen]
pub struct BiStream {
    recv: JsReadableStream,
    send: JsWritableStream,
    endpoint_id: String,
    application_crypto_wrapped: bool,
}

#[wasm_bindgen]
pub struct PeerUniStream {
    writable: JsWritableStream,
    application_crypto_wrapped: bool,
}

#[wasm_bindgen]
impl PeerUniStream {
    #[wasm_bindgen(getter)]
    pub fn writable(&self) -> JsWritableStream {
        self.writable.clone()
    }

    #[wasm_bindgen(getter, js_name = applicationCryptoWrapped)]
    pub fn application_crypto_wrapped(&self) -> bool {
        self.application_crypto_wrapped
    }
}

#[wasm_bindgen]
impl BiStream {
    #[wasm_bindgen(getter)]
    pub fn recv(&self) -> JsReadableStream {
        self.recv.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn send(&self) -> JsWritableStream {
        self.send.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn endpoint_id(&self) -> String {
        self.endpoint_id.clone()
    }

    #[wasm_bindgen(getter, js_name = applicationCryptoWrapped)]
    pub fn application_crypto_wrapped(&self) -> bool {
        self.application_crypto_wrapped
    }
}

// Helpers for stream conversion
pub fn peer_send_stream_to_writable(
    send: crate::application_crypto_streams::PeerSendStream,
) -> JsWritableStream {
    match send {
        crate::application_crypto_streams::PeerSendStream::Plain(inner) => {
            send_stream_to_writable(inner)
        }
        crate::application_crypto_streams::PeerSendStream::Encrypted(encrypted) => {
            let sink = futures::sink::unfold(encrypted, |mut encrypted, val: JsValue| async move {
                let bytes = js_sys::Uint8Array::new(&val).to_vec();
                encrypted
                    .write_all(&bytes)
                    .await
                    .map_err(|error| JsError::new(&error.to_string()))?;
                Ok(encrypted)
            });
            WritableStream::from_sink(sink).into_raw()
        }
    }
}

pub fn peer_recv_stream_to_readable(
    recv: crate::application_crypto_streams::PeerRecvStream,
) -> JsReadableStream {
    match recv {
        crate::application_crypto_streams::PeerRecvStream::Plain(inner) => {
            recv_stream_to_readable(inner)
        }
        crate::application_crypto_streams::PeerRecvStream::Encrypted(encrypted) => {
            let stream = futures::stream::unfold(encrypted, |mut encrypted| async move {
                let mut buffer = vec![0u8; READABLE_STREAM_CHUNK_BYTES];
                match encrypted.read(&mut buffer).await {
                    Ok(0) => None,
                    Ok(read_bytes) => {
                        buffer.truncate(read_bytes);
                        Some((
                            Ok(JsValue::from(js_sys::Uint8Array::from(buffer.as_slice()))),
                            encrypted,
                        ))
                    }
                    Err(error) => Some((
                        Err(JsValue::from(JsError::new(&error.to_string()))),
                        encrypted,
                    )),
                }
            });
            ReadableStream::from_stream(stream).into_raw()
        }
    }
}

pub fn send_stream_to_writable(send: SendStream) -> JsWritableStream {
    let writer = FramedWrite::new(send, BytesCodec::new());
    let writer =
        <FramedWrite<_, _> as SinkExt<bytes::Bytes>>::sink_map_err(writer, |e: std::io::Error| {
            JsError::new(&e.to_string())
        });
    let writer = writer.with(|val: JsValue| {
        let data = js_sys::Uint8Array::new(&val);
        let vec = data.to_vec();
        futures::future::ready(Ok(bytes::Bytes::from(vec)))
    });
    WritableStream::from_sink(writer).into_raw()
}

fn recv_stream_to_readable(recv: RecvStream) -> JsReadableStream {
    // Use 256KB buffer to match sender chunk size and avoid QUIC flow-control stalls.
    // The previous 1KB buffer caused the receiver to consume data too slowly, filling
    // the sender's flow-control window and deadlocking large transfers.
    //
    // Note: We use unfolding + `from_stream` instead of `from_async_read` to avoid
    // a known bug in `wasm_streams` 0.4.0 where `from_async_read` can panic with
    // `Option::unwrap_throw` on a None value when the stream is cancelled or drops
    // on certain mobile environments (like WebKit/Safari).
    let recv = recv.compat();
    let stream = futures::stream::unfold(recv, |mut recv| async move {
        let mut buffer = vec![0u8; READABLE_STREAM_CHUNK_BYTES];
        match recv.read(&mut buffer).await {
            Ok(0) => None,
            Ok(read_bytes) => {
                buffer.truncate(read_bytes);
                Some((
                    Ok(JsValue::from(js_sys::Uint8Array::from(buffer.as_slice()))),
                    recv,
                ))
            }
            Err(error) => Some((Err(JsValue::from(JsError::new(&error.to_string()))), recv)),
        }
    });

    ReadableStream::from_stream(stream).into_raw()
}

impl BiStream {
    fn set_object_property(
        object: &js_sys::Object,
        key: &str,
        value: &JsValue,
    ) -> std::result::Result<(), JsValue> {
        let did_set = js_sys::Reflect::set(object, &JsValue::from_str(key), value)?;
        if did_set {
            Ok(())
        } else {
            Err(JsValue::from_str(&format!(
                "Failed to set incoming stream property `{}`",
                key
            )))
        }
    }

    fn incoming_stream_value(
        incoming: IncomingStream,
    ) -> std::result::Result<(String, JsValue, String, JsValue, JsValue), JsValue> {
        let endpoint_id = incoming.endpoint_id.to_string();
        match incoming.stream {
            IncomingStreamType::Bi(send, recv) => {
                // `incoming_streams` is an ordered source. Do not read from an incoming
                // stream to classify it here: a quiet stream would otherwise prevent every
                // later control/application stream from reaching the JS dispatcher. The
                // dispatcher classifies each stream independently after delivery.
                let stream = js_sys::Object::new();
                let send = send_stream_to_writable(send);
                let recv = recv_stream_to_readable(recv);
                Self::set_object_property(&stream, "send", &JsValue::from(send))?;
                Self::set_object_property(&stream, "recv", &JsValue::from(recv))?;
                Self::set_object_property(
                    &stream,
                    "endpoint_id",
                    &JsValue::from_str(&endpoint_id),
                )?;
                let protocol_hint = serde_wasm_bindgen::to_value(
                    &crate::stream_metadata::IncomingProtocolHint::Unknown,
                )
                .map_err(|error| JsValue::from_str(&error.to_string()))?;
                Ok((
                    "bi".to_string(),
                    JsValue::from(stream),
                    endpoint_id,
                    protocol_hint,
                    JsValue::NULL,
                ))
            }
            IncomingStreamType::Uni(recv) => {
                // Web/mobile share flows can receive probe-style uni streams that the
                // TS client intentionally ignores. Building a JS ReadableStream wrapper
                // for these unhandled streams has triggered wasm-stream callback
                // lifecycle panics on mobile browsers. Drop the Rust recv stream and
                // surface a null payload so TS can treat it as intentionally dropped.
                drop(recv);
                Ok((
                    "uni".to_string(),
                    JsValue::NULL,
                    endpoint_id,
                    serde_wasm_bindgen::to_value(
                        &crate::stream_metadata::IncomingProtocolHint::Unknown,
                    )
                    .map_err(|error| JsValue::from_str(&error.to_string()))?,
                    JsValue::NULL,
                ))
            }
        }
    }

    pub fn incoming_to_js_value(incoming: IncomingStream) -> std::result::Result<JsValue, JsValue> {
        let (ty, stream, endpoint_id, protocol_hint, channel) =
            Self::incoming_stream_value(incoming)?;

        let object = js_sys::Object::new();
        Self::set_object_property(&object, "type", &JsValue::from_str(&ty))?;
        Self::set_object_property(&object, "stream", &stream)?;
        Self::set_object_property(&object, "endpointId", &JsValue::from_str(&endpoint_id))?;
        Self::set_object_property(&object, "protocolHint", &protocol_hint)?;
        Self::set_object_property(&object, "channel", &channel)?;

        Ok(JsValue::from(object))
    }

    pub fn from_parts(
        send_stream: SendStream,
        recv_stream: RecvStream,
        endpoint_id: String,
    ) -> Self {
        let send = send_stream_to_writable(send_stream);
        let recv = recv_stream_to_readable(recv_stream);
        Self {
            recv,
            send,
            endpoint_id,
            application_crypto_wrapped: false,
        }
    }

    pub fn from_peer_parts(
        send_stream: crate::application_crypto_streams::PeerSendStream,
        recv_stream: crate::application_crypto_streams::PeerRecvStream,
        endpoint_id: String,
    ) -> Self {
        let application_crypto_wrapped = send_stream.is_encrypted() || recv_stream.is_encrypted();
        let send = peer_send_stream_to_writable(send_stream);
        let recv = peer_recv_stream_to_readable(recv_stream);
        Self {
            recv,
            send,
            endpoint_id,
            application_crypto_wrapped,
        }
    }
}

pub fn peer_uni_stream_from_send(
    send: crate::application_crypto_streams::PeerSendStream,
) -> PeerUniStream {
    let application_crypto_wrapped = send.is_encrypted();
    PeerUniStream {
        writable: peer_send_stream_to_writable(send),
        application_crypto_wrapped,
    }
}

pub fn to_js_err(err: impl Into<anyhow::Error>) -> JsError {
    let err: anyhow::Error = err.into();
    JsError::new(&err.to_string())
}

pub fn into_js_readable_stream<T: Serialize>(
    stream: impl Stream<Item = T> + 'static,
) -> wasm_streams::readable::sys::ReadableStream {
    let stream = stream.map(|event| Ok(serde_wasm_bindgen::to_value(&event).unwrap()));
    ReadableStream::from_stream(stream).into_raw()
}