salvo_extra 0.91.1

Salvo is a powerful web framework that can make your work easier.
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
// Copyright (c) 2018-2020 Sean McArthur
// Licensed under the MIT license http://opensource.org/licenses/MIT
// port from https://github.com/seanmonstar/warp/blob/master/src/filters/ws.rs

//! WebSocket implementation.
//!
//! # Example
//!
//! ```no_run
//! use salvo_core::prelude::*;
//! use salvo_extra::websocket::WebSocketUpgrade;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! struct User {
//!     id: usize,
//!     name: String,
//! }
//! #[handler]
//! async fn connect(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
//!     let user = req.parse_queries::<User>();
//!     WebSocketUpgrade::new()
//!         .upgrade(req, res, |mut ws| async move {
//!             println!("{user:#?} ");
//!             while let Some(msg) = ws.recv().await {
//!                 let msg = if let Ok(msg) = msg {
//!                     msg
//!                 } else {
//!                     // client disconnected
//!                     return;
//!                 };
//!
//!                 if ws.send(msg).await.is_err() {
//!                     // client disconnected
//!                     return;
//!                 }
//!             }
//!         })
//!         .await
//! }
//!
//! #[handler]
//! async fn index(res: &mut Response) {
//!     res.render(Text::Html(INDEX_HTML));
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let router = Router::new().get(index).push(Router::with_path("ws").goal(connect));
//!
//!     let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
//!     Server::new(acceptor).serve(router).await;
//! }
//!
//! static INDEX_HTML: &str = r#"<!DOCTYPE html>
//! <html>
//!     <head>
//!         <title>WS</title>
//!     </head>
//!     <body>
//!         <h1>WS</h1>
//!         <div id="status">
//!             <p><em>Connecting...</em></p>
//!         </div>
//!         <script>
//!             const status = document.getElementById('status');
//!             const msg = document.getElementById('msg');
//!             const submit = document.getElementById('submit');
//!             const ws = new WebSocket(`ws://${location.host}/ws?id=123&name=chris`);
//!
//!             ws.onopen = function() {
//!                 status.innerHTML = '<p><em>Connected!</em></p>';
//!             };
//!         </script>
//!     </body>
//! </html>
//! "#;
//!```

use std::fmt::{self, Debug, Formatter};
use std::pin::Pin;
use std::task::{Context, Poll, ready};

use futures_util::sink::{Sink, SinkExt};
use futures_util::stream::{Stream, StreamExt};
use futures_util::{FutureExt, TryFutureExt, future};
use hyper::upgrade::OnUpgrade;
use salvo_core::http::header::{SEC_WEBSOCKET_PROTOCOL, SEC_WEBSOCKET_VERSION, UPGRADE};
use salvo_core::http::headers::{
    Connection, HeaderMapExt, SecWebsocketAccept, SecWebsocketKey, Upgrade,
};
use salvo_core::http::{StatusCode, StatusError};
use salvo_core::rt::tokio::TokioIo;
use salvo_core::{Error, Request, Response};
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Bytes;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use tokio_tungstenite::tungstenite::protocol::frame::{CloseFrame, Utf8Bytes};
use tokio_tungstenite::tungstenite::protocol::{self, WebSocketConfig};

/// Creates a WebSocket Handler.
/// Request:
/// - Method must be `GET`
/// - Header `connection` must be `upgrade`
/// - Header `upgrade` must be `websocket`
/// - Header `sec-websocket-version` must be `13`
/// - Header `sec-websocket-key` must be set.
///
/// Response:
/// - Status of `101 Switching Protocols`
/// - Header `connection: upgrade`
/// - Header `upgrade: websocket`
/// - Header `sec-websocket-accept` with the hash value of the received key.
#[allow(missing_debug_implementations)]
pub struct WebSocketUpgrade {
    config: Option<WebSocketConfig>,
    protocols: Vec<String>,
    accept_any: bool,
}

impl Default for WebSocketUpgrade {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl WebSocketUpgrade {
    /// Create new `WebSocketUpgrade`.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self { config: None, protocols: Vec::new(), accept_any: false }
    }

    /// Create new `WebSocketUpgrade` with config.
    #[inline]
    #[must_use]
    pub fn with_config(config: WebSocketConfig) -> Self {
        Self {
            config: Some(config),
            protocols: Vec::new(),
            accept_any: false,
        }
    }

    /// Set the list of supported `Sec-WebSocket-Protocol` values.
    ///
    /// During the upgrade handshake, the server will select the first protocol
    /// from the client's `Sec-WebSocket-Protocol` header that also appears in this
    /// list, and include it in the `101 Switching Protocols` response.
    ///
    /// If no overlap is found, no `Sec-WebSocket-Protocol` header is set in the response,
    /// and the connection still proceeds. This follows RFC 6455 §4.2.2.
    ///
    /// # Example
    ///
    /// ```ignore
    /// WebSocketUpgrade::new()
    ///     .protocols(&["graphql-ws", "graphql-transport-ws"])
    ///     .upgrade(req, res, |ws| async move { /* ... */ })
    ///     .await
    /// ```
    #[inline]
    #[must_use]
    pub fn protocols(mut self, protocols: &[&str]) -> Self {
        self.protocols = protocols.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Accept any `Sec-WebSocket-Protocol` offered by the client without validation.
    ///
    /// The first protocol value from the client's `Sec-WebSocket-Protocol` header will
    /// be echoed back in the `101 Switching Protocols` response as-is.
    ///
    /// This is useful when the server intentionally accepts any offered WebSocket
    /// subprotocol identifier without enforcing an allowlist.
    ///
    /// `Sec-WebSocket-Protocol` is intended for subprotocol negotiation. Do not use it
    /// to carry authentication tokens, secrets, or other sensitive/dynamic data, since
    /// the selected value is echoed in the handshake response and may be exposed in logs
    /// or telemetry.
    ///
    /// If the client does not send a `Sec-WebSocket-Protocol` header, no header is set
    /// in the response and the connection proceeds normally.
    ///
    /// **Note:** If both `protocols()` and `accept_any_protocol()` are called,
    /// `accept_any_protocol()` takes precedence and the protocols list is ignored.
    ///
    /// # Example
    ///
    /// ```ignore
    /// WebSocketUpgrade::new()
    ///     .accept_any_protocol()
    ///     .upgrade(req, res, |ws| async move { /* ... */ })
    ///     .await
    /// ```
    #[inline]
    #[must_use]
    pub fn accept_any_protocol(mut self) -> Self {
        self.accept_any = true;
        self
    }

    /// The target minimum size of the write buffer to reach before writing the data
    /// to the underlying stream.
    /// The default value is 128 KiB.
    ///
    /// If set to `0` each message will be eagerly written to the underlying stream.
    /// It is often more optimal to allow them to buffer a little, hence the default value.
    #[inline]
    #[must_use]
    pub fn write_buffer_size(mut self, max: usize) -> Self {
        self.config
            .get_or_insert_with(WebSocketConfig::default)
            .write_buffer_size = max;
        self
    }

    /// The max size of the write buffer in bytes. Setting this can provide backpressure
    /// in the case the write buffer is filling up due to write errors.
    /// The default value is unlimited.
    ///
    /// **Note**: The write buffer only builds up past [`write_buffer_size`](Self::write_buffer_size)
    /// when writes to the underlying stream are failing. So the **write buffer can not
    /// fill up if you are not observing write errors even if not flushing**.
    ///
    /// Should always be at least [`write_buffer_size + 1 message`](Self::write_buffer_size)
    /// and probably a little more depending on error handling strategy.
    #[inline]
    #[must_use]
    pub fn max_write_buffer_size(mut self, max: usize) -> Self {
        self.config
            .get_or_insert_with(WebSocketConfig::default)
            .max_write_buffer_size = max;
        self
    }

    /// The maximum size of a message. `None` means no size limit. The default value is 64 MiB
    /// which should be reasonably big for all normal use-cases but small enough to prevent
    /// memory eating by a malicious user.
    #[inline]
    #[must_use]
    pub fn max_message_size(mut self, max: usize) -> Self {
        self.config
            .get_or_insert_with(WebSocketConfig::default)
            .max_message_size = Some(max);
        self
    }

    /// The maximum size of a single message frame. `None` means no size limit. The limit is for
    /// frame payload NOT including the frame header. The default value is 16 MiB which should
    /// be reasonably big for all normal use-cases but small enough to prevent memory eating
    /// by a malicious user.
    #[inline]
    #[must_use]
    pub fn max_frame_size(mut self, max: usize) -> Self {
        self.config
            .get_or_insert_with(WebSocketConfig::default)
            .max_frame_size = Some(max);
        self
    }

    /// When set to `true`, the server will accept and handle unmasked frames
    /// from the client. According to the RFC 6455, the server must close the
    /// connection to the client in such cases, however it seems like there are
    /// some popular libraries that are sending unmasked frames, ignoring the RFC.
    /// By default this option is set to `false`, i.e. according to RFC 6455.
    #[inline]
    #[must_use]
    pub fn accept_unmasked_frames(mut self, accept: bool) -> Self {
        self.config
            .get_or_insert_with(WebSocketConfig::default)
            .accept_unmasked_frames = accept;
        self
    }

    /// Upgrade websocket request.
    pub async fn upgrade<F, Fut>(
        &self,
        req: &mut Request,
        res: &mut Response,
        callback: F,
    ) -> Result<(), StatusError>
    where
        F: FnOnce(WebSocket) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let req_headers = req.headers();
        let matched = req_headers
            .typed_get::<Connection>()
            .map(|conn| conn.contains(UPGRADE))
            .unwrap_or(false);
        if !matched {
            tracing::debug!("missing connection upgrade");
            return Err(StatusError::bad_request().brief("Missing connection upgrade."));
        }
        let matched = req_headers
            .get(UPGRADE)
            .and_then(|v| v.to_str().ok())
            .map(|v| v.to_lowercase() == "websocket")
            .unwrap_or(false);
        if !matched {
            tracing::debug!("missing upgrade header or it is not equal websocket");
            return Err(StatusError::bad_request()
                .brief("Missing upgrade header or it is not equal websocket."));
        }
        let matched = !req_headers
            .get(SEC_WEBSOCKET_VERSION)
            .and_then(|v| v.to_str().ok())
            .map(|v| v == "13")
            .unwrap_or(false);
        if matched {
            tracing::debug!("websocket version is not equal 13");
            return Err(StatusError::bad_request().brief("Websocket version is not equal 13."));
        }
        let Some(sec_ws_key) = req_headers.typed_get::<SecWebsocketKey>() else {
            tracing::debug!("sec_websocket_key is not exist in request headers");
            return Err(StatusError::bad_request()
                .brief("sec_websocket_key is not exist in request headers."));
        };

        res.status_code(StatusCode::SWITCHING_PROTOCOLS);

        res.headers_mut().typed_insert(Connection::upgrade());
        res.headers_mut().typed_insert(Upgrade::websocket());
        res.headers_mut()
            .typed_insert(SecWebsocketAccept::from(sec_ws_key));

        // Negotiate subprotocol
        let selected: Option<&str> = if self.accept_any {
            // Echo the first non-empty protocol from the client without validation
            find_first_client_protocol(req_headers)
        } else {
            select_protocol(req_headers, &self.protocols)
        };
        if let Some(selected) = selected {
            match selected.parse() {
                Ok(value) => {
                    res.headers_mut().insert(SEC_WEBSOCKET_PROTOCOL, value);
                }
                Err(error) => {
                    tracing::debug!(
                        protocol = selected,
                        ?error,
                        "skipping Sec-WebSocket-Protocol response header because the negotiated protocol is not a valid header value"
                    );
                }
            }
        }

        if let Some(on_upgrade) = req.extensions_mut().remove::<OnUpgrade>() {
            let config = self.config;
            tokio::spawn(async move {
                let socket = on_upgrade
                    .and_then(move |upgraded| {
                        tracing::debug!("websocket upgrade complete");
                        WebSocket::from_raw_socket(upgraded, protocol::Role::Server, config).map(Ok)
                    })
                    .await
                    .expect("connection upgrade failed");
                callback(socket).await;
            });
            Ok(())
        } else {
            tracing::debug!("websocket couldn't be upgraded since no upgrade state was present");
            Err(StatusError::bad_request()
                .brief("Websocket couldn't be upgraded since no upgrade state was present."))
        }
    }
}

/// A websocket `Stream` and `Sink`, provided to `ws` filters.
///
/// Ping messages sent from the client will be handled internally by replying with a Pong message.
/// Close messages need to be handled explicitly: usually by closing the `Sink` end of the
/// `WebSocket`.
pub struct WebSocket {
    inner: WebSocketStream<TokioIo<hyper::upgrade::Upgraded>>,
}

impl WebSocket {
    #[inline]
    pub(crate) async fn from_raw_socket(
        upgraded: hyper::upgrade::Upgraded,
        role: protocol::Role,
        config: Option<protocol::WebSocketConfig>,
    ) -> Self {
        WebSocketStream::from_raw_socket(TokioIo::new(upgraded), role, config)
            .map(|inner| Self { inner })
            .await
    }

    /// Receive another message.
    ///
    /// Returns `None` if the stream has closed.
    pub async fn recv(&mut self) -> Option<Result<Message, Error>> {
        self.next().await
    }

    /// Send a message.
    pub async fn send(&mut self, msg: Message) -> Result<(), Error> {
        self.inner.send(msg.inner).await.map_err(Error::other)
    }

    /// Gracefully close this websocket.
    #[inline]
    pub async fn close(mut self) -> Result<(), Error> {
        future::poll_fn(|cx| Pin::new(&mut self).poll_close(cx)).await
    }
}

impl Stream for WebSocket {
    type Item = Result<Message, Error>;

    #[inline]
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        match ready!(Pin::new(&mut self.inner).poll_next(cx)) {
            Some(Ok(item)) => Poll::Ready(Some(Ok(Message { inner: item }))),
            Some(Err(e)) => {
                tracing::debug!("websocket poll error: {}", e);
                Poll::Ready(Some(Err(Error::other(e))))
            }
            None => {
                tracing::debug!("websocket closed");
                Poll::Ready(None)
            }
        }
    }
}

impl Sink<Message> for WebSocket {
    type Error = Error;

    #[inline]
    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_ready(cx)
            .map_err(Error::other)
    }

    #[inline]
    fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
        Pin::new(&mut self.inner)
            .start_send(item.inner)
            .map_err(Error::other)
    }

    #[inline]
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_flush(cx)
            .map_err(Error::other)
    }

    #[inline]
    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Pin::new(&mut self.inner)
            .poll_close(cx)
            .map_err(Error::other)
    }
}

impl Debug for WebSocket {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("WebSocket").finish()
    }
}

/// A WebSocket message.
///
/// This will likely become a `non-exhaustive` enum in the future, once that
/// language feature has stabilized.
#[derive(Eq, PartialEq, Clone)]
pub struct Message {
    inner: protocol::Message,
}

impl Message {
    /// Construct a new Text `Message`.
    #[inline]
    pub fn text<S: Into<Utf8Bytes>>(s: S) -> Self {
        Self {
            inner: protocol::Message::text(s),
        }
    }

    /// Construct a new Binary `Message`.
    #[inline]
    pub fn binary<V: Into<Bytes>>(v: V) -> Self {
        Self {
            inner: protocol::Message::binary(v),
        }
    }

    /// Construct a new Ping `Message`.
    #[inline]
    pub fn ping<V: Into<Bytes>>(v: V) -> Self {
        Self {
            inner: protocol::Message::Ping(v.into()),
        }
    }

    /// Construct a new Pong `Message`.
    #[inline]
    pub fn pong<V: Into<Bytes>>(v: V) -> Self {
        Self {
            inner: protocol::Message::Pong(v.into()),
        }
    }

    /// Construct the default Close `Message`.
    #[inline]
    pub fn close() -> Self {
        Self {
            inner: protocol::Message::Close(None),
        }
    }

    /// Construct a Close `Message` with a code and reason.
    #[inline]
    pub fn close_with(code: impl Into<u16>, reason: impl Into<Utf8Bytes>) -> Self {
        Self {
            inner: protocol::Message::Close(Some(CloseFrame {
                code: CloseCode::from(code.into()),
                reason: reason.into(),
            })),
        }
    }

    /// Returns true if this message is a Text message.
    #[inline]
    pub fn is_text(&self) -> bool {
        self.inner.is_text()
    }

    /// Returns true if this message is a Binary message.
    #[inline]
    pub fn is_binary(&self) -> bool {
        self.inner.is_binary()
    }

    /// Returns true if this message a is a Close message.
    #[inline]
    pub fn is_close(&self) -> bool {
        self.inner.is_close()
    }

    /// Returns true if this message is a Ping message.
    #[inline]
    pub fn is_ping(&self) -> bool {
        self.inner.is_ping()
    }

    /// Returns true if this message is a Pong message.
    #[inline]
    pub fn is_pong(&self) -> bool {
        self.inner.is_pong()
    }

    /// Try to get the close frame (close code and reason).
    #[inline]
    pub fn close_frame(&self) -> Option<(u16, &str)> {
        if let protocol::Message::Close(Some(ref close_frame)) = self.inner {
            Some((close_frame.code.into(), close_frame.reason.as_ref()))
        } else {
            None
        }
    }

    /// Try to get a reference to the string text, if this is a Text message.
    #[inline]
    pub fn as_str(&self) -> Result<&str, Error> {
        match &self.inner {
            protocol::Message::Text(s) => Ok(s.as_str()),
            _ => Err(Error::Other("not a text message".into())),
        }
    }

    /// Returns the bytes of this message, if the message can contain data.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        match &self.inner {
            protocol::Message::Text(s) => s.as_bytes(),
            protocol::Message::Binary(v)
            | protocol::Message::Ping(v)
            | protocol::Message::Pong(v) => v.as_ref(),
            protocol::Message::Close(_) => &[],
            protocol::Message::Frame(v) => v.payload(),
        }
    }
}

impl Debug for Message {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, f)
    }
}

#[allow(clippy::from_over_into)]
impl Into<Vec<u8>> for Message {
    #[inline]
    fn into(self) -> Vec<u8> {
        self.as_bytes().into()
    }
}

/// Find the first non-empty protocol token from the client's `Sec-WebSocket-Protocol` header(s).
///
/// Handles both comma-separated values in a single header and multiple headers.
fn find_first_client_protocol(req_headers: &salvo_core::http::HeaderMap) -> Option<&str> {
    for value in req_headers.get_all(SEC_WEBSOCKET_PROTOCOL) {
        let Ok(value) = value.to_str() else {
            continue;
        };
        for token in value.split(',').map(str::trim) {
            if !token.is_empty() {
                return Some(token);
            }
        }
    }
    None
}

/// Select the first protocol from the client's `Sec-WebSocket-Protocol` header(s) that also
/// appears in the server's supported `protocols` list.
///
/// Returns `None` if there is no overlap (per RFC 6455 §4.2.2, the server may proceed
/// without a subprotocol header in the response).
fn select_protocol<'a>(
    req_headers: &'a salvo_core::http::HeaderMap,
    protocols: &[String],
) -> Option<&'a str> {
    if protocols.is_empty() {
        return None;
    }
    for value in req_headers.get_all(SEC_WEBSOCKET_PROTOCOL) {
        let Ok(value) = value.to_str() else {
            continue;
        };
        for requested in value.split(',').map(str::trim) {
            if requested.is_empty() {
                continue;
            }
            if protocols.iter().any(|supported| supported == requested) {
                return Some(requested);
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use salvo_core::conn::{Acceptor, Listener};
    use salvo_core::http::header::*;
    use salvo_core::prelude::*;
    use salvo_core::rt::tokio::TokioIo;

    use super::*;

    #[handler]
    async fn connect(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
        WebSocketUpgrade::new()
            .upgrade(req, res, |mut ws| async move {
                while let Some(msg) = ws.recv().await {
                    let Ok(msg) = msg else {
                        return;
                    };

                    if ws.send(msg).await.is_err() {
                        return;
                    }
                }
            })
            .await
    }

    #[handler]
    async fn connect_with_protocols(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
        WebSocketUpgrade::new()
            .protocols(&["chat.v1", "chat.v2"])
            .upgrade(req, res, |mut ws| async move {
                while let Some(msg) = ws.recv().await {
                    let Ok(msg) = msg else {
                        return;
                    };

                    if ws.send(msg).await.is_err() {
                        return;
                    }
                }
            })
            .await
    }

    #[handler]
    async fn connect_accept_any(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
        WebSocketUpgrade::new()
            .accept_any_protocol()
            .upgrade(req, res, |mut ws| async move {
                while let Some(msg) = ws.recv().await {
                    let Ok(msg) = msg else {
                        return;
                    };

                    if ws.send(msg).await.is_err() {
                        return;
                    }
                }
            })
            .await
    }

    #[tokio::test]
    async fn test_websocket() {
        let router = Router::new().goal(connect);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        // Fetch the url...
        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
    }

    #[tokio::test]
    async fn test_websocket_with_protocol_match() {
        let router = Router::new().goal(connect_with_protocols);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .header(SEC_WEBSOCKET_PROTOCOL, "chat.v2, chat.v1")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
        // Should select "chat.v2" — first supported protocol in client's list
        assert_eq!(
            res.headers().get(SEC_WEBSOCKET_PROTOCOL),
            Some(&HeaderValue::from_static("chat.v2")),
        );
    }

    #[tokio::test]
    async fn test_websocket_with_protocol_no_match() {
        let router = Router::new().goal(connect_with_protocols);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .header(SEC_WEBSOCKET_PROTOCOL, "unknown-protocol")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
        // No overlap — response should not contain Sec-WebSocket-Protocol
        assert!(res.headers().get(SEC_WEBSOCKET_PROTOCOL).is_none());
    }

    #[tokio::test]
    async fn test_websocket_without_protocol() {
        let router = Router::new().goal(connect_with_protocols);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
        // Client didn't send any protocol — response should not contain one
        assert!(res.headers().get(SEC_WEBSOCKET_PROTOCOL).is_none());
    }

    #[tokio::test]
    async fn test_websocket_accept_any_protocol() {
        let router = Router::new().goal(connect_accept_any);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .header(SEC_WEBSOCKET_PROTOCOL, "any-custom-protocol, fallback")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
        // accept_any should echo the first protocol from the client
        assert_eq!(
            res.headers().get(SEC_WEBSOCKET_PROTOCOL),
            Some(&HeaderValue::from_static("any-custom-protocol")),
        );
    }

    #[tokio::test]
    async fn test_websocket_accept_any_protocol_leading_comma() {
        let router = Router::new().goal(connect_accept_any);
        let acceptor = TcpListener::new("127.0.0.1:0").bind().await;
        let addr = acceptor.holdings()[0]
            .local_addr
            .clone()
            .into_std()
            .unwrap();

        tokio::spawn(async move {
            Server::new(acceptor).serve(router).await;
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();

        let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream))
            .await
            .unwrap();
        tokio::task::spawn(async move {
            if let Err(err) = conn.await {
                println!("Connection failed: {err:?}");
            }
        });

        let req = hyper::Request::builder()
            .uri(format!("http://{addr}"))
            .header(UPGRADE, "websocket")
            .header(CONNECTION, "Upgrade")
            .header(SEC_WEBSOCKET_KEY, "6D69KGBOr4Re+Nj6zx9aQA==")
            .header(SEC_WEBSOCKET_VERSION, "13")
            .header(SEC_WEBSOCKET_PROTOCOL, ", chat.v1")
            .body(http_body_util::Empty::<hyper::body::Bytes>::new())
            .unwrap();

        let res = sender.send_request(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::SWITCHING_PROTOCOLS);
        // Should skip the empty leading entry and select "chat.v1"
        assert_eq!(
            res.headers().get(SEC_WEBSOCKET_PROTOCOL),
            Some(&HeaderValue::from_static("chat.v1")),
        );
    }
}