zenwave 0.5.3

Ergonomic HTTP client framework.
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
pub use http_kit::ws::*;

use http_kit::{HttpError, StatusCode};
use serde::Serialize;

/// Errors returned by websocket operations.
#[derive(Debug, thiserror::Error)]
pub enum WebSocketError {
    /// Failed to encode a payload for transmission.
    #[error("Fail to encode payload: {0}")]
    FailToEncodePayload(serde_json::Error),

    /// Unsupported websocket URI scheme encountered.
    #[error("Unsupported websocket scheme: {0}")]
    UnsupportedScheme(String),

    /// Provided websocket URI was invalid.
    #[error("Invalid URI: {0}")]
    InvalidUri(#[from] url::ParseError),

    /// Underlying websocket connection failed.
    #[error("Connection failed: {0}")]
    ConnectionFailed(#[source] Box<dyn std::error::Error + Send + Sync>),
}

impl HttpError for WebSocketError {
    fn status(&self) -> StatusCode {
        match self {
            Self::ConnectionFailed(_) => StatusCode::BAD_GATEWAY,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

// Convert WebSocketError to unified zenwave::Error
impl From<WebSocketError> for crate::Error {
    fn from(err: WebSocketError) -> Self {
        use crate::error::WebSocketErrorKind;

        match err {
            WebSocketError::FailToEncodePayload(e) => {
                Self::WebSocket(WebSocketErrorKind::EncodeFailed(e))
            }
            WebSocketError::UnsupportedScheme(s) => {
                Self::WebSocket(WebSocketErrorKind::UnsupportedScheme(s))
            }
            WebSocketError::InvalidUri(e) => Self::InvalidUri(e.to_string()),
            WebSocketError::ConnectionFailed(e) => {
                Self::WebSocket(WebSocketErrorKind::ConnectionFailed(e.to_string()))
            }
        }
    }
}

/// Configuration applied when establishing a websocket connection.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct WebSocketConfig {
    /// Maximum incoming websocket message size in bytes.
    /// `None` means no limit.
    pub max_message_size: Option<usize>,

    /// Maximum incoming websocket frame size in bytes.
    /// `None` means no limit.
    pub max_frame_size: Option<usize>,
}

const DEFAULT_MAX_MESSAGE_SIZE: Option<usize> = Some(64 << 20);
const DEFAULT_MAX_FRAME_SIZE: Option<usize> = Some(16 << 20);

impl Default for WebSocketConfig {
    fn default() -> Self {
        Self {
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            max_frame_size: DEFAULT_MAX_FRAME_SIZE,
        }
    }
}

impl WebSocketConfig {
    /// Override the maximum incoming websocket message size in bytes.
    ///
    /// `None` means no limit.
    ///
    /// Defaults to 64 MiB.
    #[must_use]
    pub const fn with_max_message_size(mut self, max_message_size: Option<usize>) -> Self {
        self.max_message_size = max_message_size;
        self
    }

    /// Override the maximum incoming websocket frame size in bytes.
    ///
    /// `None` means no limit.
    ///
    /// Defaults to 16 MiB.
    #[must_use]
    pub const fn with_max_frame_size(mut self, max_frame_size: Option<usize>) -> Self {
        self.max_frame_size = max_frame_size;
        self
    }
}

#[allow(clippy::result_large_err)]
fn serialize_payload<T>(value: &T) -> Result<String, WebSocketError>
where
    T: Serialize,
{
    serde_json::to_string(value).map_err(WebSocketError::FailToEncodePayload)
}

#[cfg(not(target_arch = "wasm32"))]
mod native {
    use async_lock::Mutex;
    use async_net::TcpStream;
    use async_tungstenite::{
        WebSocketReceiver as AsyncReceiver, WebSocketSender as AsyncSender, WebSocketStream,
        client_async_with_config,
        tungstenite::{
            Message as TungsteniteMessage, Utf8Bytes,
            protocol::WebSocketConfig as TungsteniteConfig,
        },
    };
    use futures_io::{AsyncRead, AsyncWrite};
    use futures_util::StreamExt;
    use http_kit::utils::{ByteStr, Bytes};
    #[cfg(feature = "rustls")]
    use rustls::pki_types::ServerName;
    use std::{
        fmt, io,
        pin::Pin,
        sync::Arc,
        task::{Context, Poll},
    };
    use url::Url;

    use super::{WebSocketConfig, WebSocketError, WebSocketMessage, serialize_payload};

    type NativeSocket = WebSocketStream<MaybeTlsStream>;
    type NativeSender = AsyncSender<MaybeTlsStream>;
    type NativeReceiver = AsyncReceiver<MaybeTlsStream>;

    #[derive(Debug)]
    enum MaybeTlsStream {
        Plain(TcpStream),
        #[cfg(feature = "rustls")]
        Rustls(Box<futures_rustls::client::TlsStream<TcpStream>>),
        #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
        Native(async_native_tls::TlsStream<TcpStream>),
    }

    impl Unpin for MaybeTlsStream {}

    impl AsyncRead for MaybeTlsStream {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<io::Result<usize>> {
            match &mut *self {
                Self::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
                #[cfg(feature = "rustls")]
                Self::Rustls(stream) => Pin::new(stream).poll_read(cx, buf),
                #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
                Self::Native(stream) => Pin::new(stream).poll_read(cx, buf),
            }
        }
    }

    impl AsyncWrite for MaybeTlsStream {
        fn poll_write(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<io::Result<usize>> {
            match &mut *self {
                Self::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
                #[cfg(feature = "rustls")]
                Self::Rustls(stream) => Pin::new(stream).poll_write(cx, buf),
                #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
                Self::Native(stream) => Pin::new(stream).poll_write(cx, buf),
            }
        }

        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            match &mut *self {
                Self::Plain(stream) => Pin::new(stream).poll_flush(cx),
                #[cfg(feature = "rustls")]
                Self::Rustls(stream) => Pin::new(stream).poll_flush(cx),
                #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
                Self::Native(stream) => Pin::new(stream).poll_flush(cx),
            }
        }

        fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            match &mut *self {
                Self::Plain(stream) => Pin::new(stream).poll_close(cx),
                #[cfg(feature = "rustls")]
                Self::Rustls(stream) => Pin::new(stream).poll_close(cx),
                #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
                Self::Native(stream) => Pin::new(stream).poll_close(cx),
            }
        }
    }

    #[derive(Debug)]
    struct SharedSocket {
        sender: Mutex<NativeSender>,
        receiver: Mutex<NativeReceiver>,
    }

    /// A websocket connection backed by async-io + Tungstenite.
    pub struct WebSocket {
        sender: WebSocketSender,
        receiver: WebSocketReceiver,
    }

    impl fmt::Debug for WebSocket {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocket").finish()
        }
    }

    /// Sending half of a websocket connection.
    pub struct WebSocketSender {
        inner: Arc<SharedSocket>,
    }

    impl fmt::Debug for WebSocketSender {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocketSender").finish()
        }
    }

    impl Clone for WebSocketSender {
        fn clone(&self) -> Self {
            Self {
                inner: Arc::clone(&self.inner),
            }
        }
    }

    /// Receiving half of a websocket connection.
    pub struct WebSocketReceiver {
        inner: Arc<SharedSocket>,
    }

    impl fmt::Debug for WebSocketReceiver {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocketReceiver").finish()
        }
    }

    /// Establish a websocket connection to the provided URI.
    ///
    /// # Errors
    ///
    /// Returns an error if the URI is invalid or the connection attempt fails.
    pub async fn connect(uri: impl AsRef<str>) -> Result<WebSocket, WebSocketError> {
        connect_with_config(uri, WebSocketConfig::default()).await
    }

    /// Establish a websocket connection to the provided URI with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the URI is invalid or the connection attempt fails.
    pub async fn connect_with_config(
        uri: impl AsRef<str>,
        websocket_config: WebSocketConfig,
    ) -> Result<WebSocket, WebSocketError> {
        let url = Url::parse(uri.as_ref())?;
        match url.scheme() {
            "ws" | "wss" => {}
            other => return Err(WebSocketError::UnsupportedScheme(other.to_string())),
        }
        let request: String = url.into();
        let mut config = TungsteniteConfig::default();
        config.max_message_size = websocket_config.max_message_size;
        config.max_frame_size = websocket_config.max_frame_size;
        let stream = connect_stream(uri.as_ref()).await?;
        let (ws_stream, _) = client_async_with_config(request, stream, Some(config))
            .await
            .map_err(|e| WebSocketError::ConnectionFailed(Box::new(e)))?;

        Ok(WebSocket::from_socket(ws_stream))
    }

    async fn connect_stream(uri: &str) -> Result<MaybeTlsStream, WebSocketError> {
        let url = Url::parse(uri)?;
        let host = url.host_str().ok_or_else(|| {
            WebSocketError::ConnectionFailed(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "websocket URI is missing a host",
            )))
        })?;
        let port = url.port_or_known_default().ok_or_else(|| {
            WebSocketError::ConnectionFailed(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "websocket URI does not imply a port",
            )))
        })?;
        let stream = TcpStream::connect((host, port))
            .await
            .map_err(|error| WebSocketError::ConnectionFailed(Box::new(error)))?;

        match url.scheme() {
            "ws" => Ok(MaybeTlsStream::Plain(stream)),
            "wss" => connect_secure(host, stream).await,
            other => Err(WebSocketError::UnsupportedScheme(other.to_string())),
        }
    }

    async fn connect_secure(
        host: &str,
        stream: TcpStream,
    ) -> Result<MaybeTlsStream, WebSocketError> {
        #[cfg(feature = "rustls")]
        {
            return connect_rustls(host, stream).await;
        }

        #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
        {
            return connect_native_tls(host, stream).await;
        }

        #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
        {
            let _ = host;
            let _ = stream;
            Err(WebSocketError::ConnectionFailed(Box::new(
                io::Error::other("wss requires either the `rustls` or `native-tls` feature"),
            )))
        }
    }

    #[cfg(feature = "rustls")]
    async fn connect_rustls(
        host: &str,
        stream: TcpStream,
    ) -> Result<MaybeTlsStream, WebSocketError> {
        use std::sync::Arc as SyncArc;

        use futures_rustls::TlsConnector;

        let mut root_store = rustls::RootCertStore::empty();
        let cert_result = rustls_native_certs::load_native_certs();
        for cert in cert_result.certs {
            let _ = root_store.add(cert);
        }

        if root_store.is_empty() {
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        }

        let config = rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();
        let connector = TlsConnector::from(SyncArc::new(config));
        let server_name = ServerName::try_from(host.to_string())
            .map_err(|error| WebSocketError::ConnectionFailed(Box::new(io::Error::other(error))))?;
        let stream = connector
            .connect(server_name, stream)
            .await
            .map_err(|error| WebSocketError::ConnectionFailed(Box::new(io::Error::other(error))))?;
        Ok(MaybeTlsStream::Rustls(Box::new(stream)))
    }

    #[cfg(all(not(feature = "rustls"), feature = "native-tls"))]
    async fn connect_native_tls(
        host: &str,
        stream: TcpStream,
    ) -> Result<MaybeTlsStream, WebSocketError> {
        let connector = async_native_tls::TlsConnector::new();
        let stream = connector
            .connect(host, stream)
            .await
            .map_err(|error| WebSocketError::ConnectionFailed(Box::new(io::Error::other(error))))?;
        Ok(MaybeTlsStream::Native(stream))
    }

    impl WebSocket {
        fn from_socket(socket: NativeSocket) -> Self {
            let (sender, receiver) = socket.split();
            let shared = Arc::new(SharedSocket {
                sender: Mutex::new(sender),
                receiver: Mutex::new(receiver),
            });

            Self {
                sender: WebSocketSender {
                    inner: Arc::clone(&shared),
                },
                receiver: WebSocketReceiver { inner: shared },
            }
        }

        /// Send a websocket message serialized as JSON.
        ///
        /// # Errors
        ///
        /// Returns an error if serialization fails or when the underlying socket cannot
        /// write the resulting frame.
        pub async fn send<T>(&self, value: T) -> Result<(), WebSocketError>
        where
            T: serde::Serialize,
        {
            let payload = serialize_payload(&value)?;
            self.send_text(payload).await
        }

        /// Send a text websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot write the frame.
        pub async fn send_text(&self, text: impl Into<ByteStr>) -> Result<(), WebSocketError> {
            self.sender.send_text(text).await
        }

        /// Send a binary websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot write the frame.
        pub async fn send_binary(&self, bytes: impl Into<Bytes>) -> Result<(), WebSocketError> {
            self.sender.send_binary(bytes).await
        }

        /// Receive the next websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot read the next frame.
        pub async fn recv(&self) -> Result<Option<WebSocketMessage>, WebSocketError> {
            self.receiver.recv().await
        }

        /// Close the websocket connection gracefully.
        ///
        /// # Errors
        ///
        /// Returns an error when the close frame cannot be sent.
        pub async fn close(self) -> Result<(), WebSocketError> {
            self.sender.close().await
        }

        /// Split the websocket into sending and receiving halves.
        #[must_use]
        pub fn split(self) -> (WebSocketSender, WebSocketReceiver) {
            (self.sender, self.receiver)
        }
    }

    impl WebSocketSender {
        /// Send a websocket message serialized as JSON.
        ///
        /// # Errors
        ///
        /// Returns an error if serialization fails or when the underlying socket cannot
        /// write the resulting frame.
        pub async fn send<T>(&self, value: T) -> Result<(), WebSocketError>
        where
            T: serde::Serialize,
        {
            let payload = serialize_payload(&value)?;
            self.send_text(payload).await
        }

        /// Send a text websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot write the frame.
        pub async fn send_text(&self, text: impl Into<ByteStr>) -> Result<(), WebSocketError> {
            self.send_message(WebSocketMessage::text(text)).await
        }

        /// Send a binary websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot write the frame.
        pub async fn send_binary(&self, bytes: impl Into<Bytes>) -> Result<(), WebSocketError> {
            self.send_message(WebSocketMessage::binary(bytes)).await
        }

        async fn send_message(&self, message: WebSocketMessage) -> Result<(), WebSocketError> {
            let mut sender = self.inner.sender.lock().await;
            sender
                .send(to_tungstenite_message(message))
                .await
                .map_err(|e| WebSocketError::ConnectionFailed(Box::new(e)))
        }

        /// Close the websocket connection gracefully.
        ///
        /// # Errors
        ///
        /// Returns an error when the close frame cannot be sent.
        pub async fn close(&self) -> Result<(), WebSocketError> {
            let mut sender = self.inner.sender.lock().await;
            sender
                .close(None)
                .await
                .map_err(|e| WebSocketError::ConnectionFailed(Box::new(e)))
        }
    }

    impl WebSocketReceiver {
        /// Receive the next websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error when the underlying socket cannot read the next frame.
        pub async fn recv(&self) -> Result<Option<WebSocketMessage>, WebSocketError> {
            loop {
                let message = {
                    let mut receiver = self.inner.receiver.lock().await;
                    receiver.next().await
                };

                let Some(message) = message else {
                    return Ok(None);
                };

                let message = message.map_err(|e| WebSocketError::ConnectionFailed(Box::new(e)))?;

                match message {
                    TungsteniteMessage::Text(text) => {
                        return Ok(Some(WebSocketMessage::Text(unsafe {
                            ByteStr::from_utf8_unchecked(text.into())
                        })));
                    }
                    TungsteniteMessage::Binary(bytes) => {
                        return Ok(Some(WebSocketMessage::Binary(bytes)));
                    }
                    TungsteniteMessage::Close(_) => return Ok(None),
                    TungsteniteMessage::Ping(payload) => {
                        self.respond_pong(payload).await?;
                    }
                    TungsteniteMessage::Pong(_) | TungsteniteMessage::Frame(_) => {}
                }
            }
        }

        async fn respond_pong(&self, payload: Bytes) -> Result<(), WebSocketError> {
            let mut sender = self.inner.sender.lock().await;
            sender
                .send(TungsteniteMessage::Pong(payload))
                .await
                .map_err(|e| WebSocketError::ConnectionFailed(Box::new(e)))
        }
    }

    fn to_tungstenite_message(value: WebSocketMessage) -> TungsteniteMessage {
        match value {
            WebSocketMessage::Text(text) => TungsteniteMessage::Text(unsafe {
                Utf8Bytes::from_bytes_unchecked(text.into_bytes())
            }),
            WebSocketMessage::Binary(bytes) => TungsteniteMessage::Binary(bytes),
            WebSocketMessage::Ping(bytes) => TungsteniteMessage::Ping(bytes),
            WebSocketMessage::Pong(bytes) => TungsteniteMessage::Pong(bytes),
            WebSocketMessage::Close => TungsteniteMessage::Close(None),
        }
    }
}

#[cfg(target_arch = "wasm32")]
mod wasm {
    use std::{cell::RefCell, fmt, rc::Rc, sync::Arc};

    use async_lock::Mutex;
    use futures_channel::{mpsc, oneshot};
    use futures_util::StreamExt;
    use http_kit::utils::{ByteStr, Bytes};
    use std::io;
    use wasm_bindgen::{JsCast, JsValue, closure::Closure};
    use web_sys::{
        BinaryType, CloseEvent, ErrorEvent, MessageEvent, WebSocket as BrowserWebSocket,
    };

    use super::{WebSocketConfig, WebSocketError, WebSocketMessage, serialize_payload};

    type Result<T> = core::result::Result<T, WebSocketError>;

    enum WsEvent {
        Message(WebSocketMessage),
        Error(String),
        Closed,
    }

    /// Browser/wasm websocket connection backed by `web_sys`.
    pub struct WebSocket {
        sender: WebSocketSender,
        receiver: WebSocketReceiver,
    }

    impl fmt::Debug for WebSocket {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocket").finish()
        }
    }

    #[derive(Debug)]
    struct SharedSocket {
        socket: BrowserWebSocket,
        receiver: Mutex<mpsc::UnboundedReceiver<WsEvent>>,
        _on_message: Closure<dyn FnMut(MessageEvent)>,
        _on_error: Closure<dyn FnMut(ErrorEvent)>,
        _on_close: Closure<dyn FnMut(CloseEvent)>,
    }

    /// Sending half of a websocket connection.
    pub struct WebSocketSender {
        inner: Arc<SharedSocket>,
    }

    impl fmt::Debug for WebSocketSender {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocketSender").finish()
        }
    }

    impl Clone for WebSocketSender {
        fn clone(&self) -> Self {
            Self {
                inner: Arc::clone(&self.inner),
            }
        }
    }

    /// Receiving half of a websocket connection.
    pub struct WebSocketReceiver {
        inner: Arc<SharedSocket>,
    }

    impl fmt::Debug for WebSocketReceiver {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("WebSocketReceiver").finish()
        }
    }

    /// Establish a websocket connection from the browser environment.
    ///
    /// # Errors
    ///
    /// Returns an error if the browser reports an error or the connection fails.
    pub async fn connect(uri: impl AsRef<str>) -> Result<WebSocket> {
        connect_with_config(uri, WebSocketConfig::default()).await
    }

    /// Establish a websocket connection from the browser environment using the provided config.
    ///
    /// # Errors
    ///
    /// Returns an error if the browser reports an error or the connection fails.
    pub async fn connect_with_config(
        uri: impl AsRef<str>,
        _config: WebSocketConfig,
    ) -> Result<WebSocket> {
        let socket = BrowserWebSocket::new(uri.as_ref())
            .map_err(|e| connection_failed(format_js_value(&e)))?;
        socket.set_binary_type(BinaryType::Arraybuffer);

        let (event_tx, event_rx) = mpsc::unbounded::<WsEvent>();
        let (ready_tx, ready_rx) = oneshot::channel::<core::result::Result<(), String>>();
        let pending = Rc::new(RefCell::new(Some(ready_tx)));

        let onopen_pending = Rc::clone(&pending);
        let on_open = Closure::wrap(Box::new(move || {
            if let Some(sender) = onopen_pending.borrow_mut().take() {
                let _ = sender.send(Ok(()));
            }
        }) as Box<dyn FnMut()>);
        socket.set_onopen(Some(on_open.as_ref().unchecked_ref()));

        let on_message_tx = event_tx.clone();
        let on_message = Closure::wrap(Box::new(move |event: MessageEvent| {
            let data = event.data();
            if let Some(text) = data.as_string() {
                let _ =
                    on_message_tx.unbounded_send(WsEvent::Message(WebSocketMessage::from(text)));
                return;
            }

            if let Ok(array) = data.clone().dyn_into::<js_sys::ArrayBuffer>() {
                let view = js_sys::Uint8Array::new(&array);
                let mut bytes = vec![0; view.length() as usize];
                view.copy_to(&mut bytes[..]);
                let _ =
                    on_message_tx.unbounded_send(WsEvent::Message(WebSocketMessage::from(bytes)));
                return;
            }

            if let Ok(view) = data.dyn_into::<js_sys::Uint8Array>() {
                let mut bytes = vec![0; view.length() as usize];
                view.copy_to(&mut bytes[..]);
                let _ =
                    on_message_tx.unbounded_send(WsEvent::Message(WebSocketMessage::from(bytes)));
                return;
            }

            let _ = on_message_tx.unbounded_send(WsEvent::Error(
                "Unsupported websocket message type".to_string(),
            ));
        }) as Box<dyn FnMut(MessageEvent)>);
        socket.set_onmessage(Some(on_message.as_ref().unchecked_ref()));

        let on_error_pending = Rc::clone(&pending);
        let on_error_tx = event_tx.clone();
        let on_error = Closure::wrap(Box::new(move |event: ErrorEvent| {
            let message = event.message();
            if let Some(sender) = on_error_pending.borrow_mut().take() {
                let _ = sender.send(Err(message.clone()));
            }
            let _ = on_error_tx.unbounded_send(WsEvent::Error(message));
        }) as Box<dyn FnMut(ErrorEvent)>);
        socket.set_onerror(Some(on_error.as_ref().unchecked_ref()));

        let on_close_pending = Rc::clone(&pending);
        let on_close_tx = event_tx.clone();
        let on_close = Closure::wrap(Box::new(move |event: CloseEvent| {
            if let Some(sender) = on_close_pending.borrow_mut().take() {
                let reason = event.reason();
                let message = if reason.is_empty() {
                    format!("Connection closed (code {})", event.code())
                } else {
                    reason
                };
                let _ = sender.send(Err(message));
            }
            let _ = on_close_tx.unbounded_send(WsEvent::Closed);
        }) as Box<dyn FnMut(CloseEvent)>);
        socket.set_onclose(Some(on_close.as_ref().unchecked_ref()));

        match ready_rx.await {
            Ok(Ok(())) => {
                socket.set_onopen(None);
                drop(on_open);
            }
            Ok(Err(message)) => {
                return Err(connection_failed(message));
            }
            Err(_) => {
                return Err(connection_failed("WebSocket connection cancelled"));
            }
        }

        let shared = Arc::new(SharedSocket {
            socket,
            receiver: Mutex::new(event_rx),
            _on_message: on_message,
            _on_error: on_error,
            _on_close: on_close,
        });

        Ok(WebSocket {
            sender: WebSocketSender {
                inner: Arc::clone(&shared),
            },
            receiver: WebSocketReceiver { inner: shared },
        })
    }

    impl WebSocket {
        /// Send a websocket message serialized as JSON.
        ///
        /// # Errors
        ///
        /// Returns an error if serialization fails or the browser cannot queue the frame.
        pub async fn send<T>(&self, value: T) -> Result<()>
        where
            T: serde::Serialize,
        {
            let payload = serialize_payload(&value)?;
            self.send_text(payload).await
        }

        /// Send a text websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser fails to queue the frame.
        pub async fn send_text(&self, text: impl Into<ByteStr>) -> Result<()> {
            self.sender.send_text(text).await
        }

        /// Send a binary websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser fails to queue the frame.
        pub async fn send_binary(&self, bytes: impl Into<Bytes>) -> Result<()> {
            self.sender.send_binary(bytes).await
        }

        /// Receive the next websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the websocket reports an error event.
        pub async fn recv(&self) -> Result<Option<WebSocketMessage>> {
            self.receiver.recv().await
        }

        /// Close the websocket connection gracefully.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser refuses to close the socket.
        pub async fn close(self) -> Result<()> {
            self.sender.close().await
        }

        /// Split the websocket into sending and receiving halves.
        #[must_use]
        pub fn split(self) -> (WebSocketSender, WebSocketReceiver) {
            (self.sender, self.receiver)
        }
    }

    impl WebSocketSender {
        /// Send a websocket message serialized as JSON.
        ///
        /// # Errors
        ///
        /// Returns an error if serialization fails or the browser cannot queue the frame.
        pub async fn send<T>(&self, value: T) -> Result<()>
        where
            T: serde::Serialize,
        {
            let payload = serialize_payload(&value)?;
            self.send_text(payload).await
        }

        /// Send a text websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser fails to queue the frame.
        pub async fn send_text(&self, text: impl Into<ByteStr>) -> Result<()> {
            self.send_message(WebSocketMessage::text(text)).await
        }

        /// Send a binary websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser fails to queue the frame.
        pub async fn send_binary(&self, bytes: impl Into<Bytes>) -> Result<()> {
            self.send_message(WebSocketMessage::binary(bytes)).await
        }

        async fn send_message(&self, message: WebSocketMessage) -> Result<()> {
            match message {
                WebSocketMessage::Text(text) => self
                    .inner
                    .socket
                    .send_with_str(&text)
                    .map_err(|e| connection_failed(format_js_value(&e)))?,
                WebSocketMessage::Binary(bytes) => self
                    .inner
                    .socket
                    .send_with_u8_array(&bytes)
                    .map_err(|e| connection_failed(format_js_value(&e)))?,
                WebSocketMessage::Ping(_) | WebSocketMessage::Pong(_) => {
                    // Browser WebSocket API doesn't expose ping/pong frames
                    // They are handled automatically by the browser
                }
                WebSocketMessage::Close => {
                    self.inner
                        .socket
                        .close()
                        .map_err(|e| connection_failed(format_js_value(&e)))?;
                }
            }
            Ok(())
        }

        /// Close the websocket connection gracefully.
        ///
        /// # Errors
        ///
        /// Returns an error if the browser refuses to close the socket.
        pub async fn close(&self) -> Result<()> {
            self.inner
                .socket
                .close()
                .map_err(|e| connection_failed(format_js_value(&e)))
        }
    }

    impl WebSocketReceiver {
        /// Receive the next websocket message.
        ///
        /// # Errors
        ///
        /// Returns an error if the websocket reports an error event.
        pub async fn recv(&self) -> Result<Option<WebSocketMessage>> {
            let mut receiver = self.inner.receiver.lock().await;
            match receiver.next().await {
                Some(WsEvent::Message(message)) => Ok(Some(message)),
                Some(WsEvent::Closed) | None => Ok(None),
                Some(WsEvent::Error(message)) => Err(connection_failed(message)),
            }
        }
    }

    fn connection_failed(message: impl Into<ByteStr>) -> WebSocketError {
        WebSocketError::ConnectionFailed(Box::new(io::Error::new(
            io::ErrorKind::Other,
            message.into().to_string(),
        )))
    }

    fn format_js_value(value: &JsValue) -> String {
        value.as_string().unwrap_or_else(|| format!("{value:?}"))
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub use native::{WebSocket, WebSocketReceiver, WebSocketSender, connect, connect_with_config};

#[cfg(target_arch = "wasm32")]
pub use wasm::{WebSocket, WebSocketReceiver, WebSocketSender, connect, connect_with_config};