Skip to main content

ntex/ws/
client.rs

1//! WebSocket client.
2use std::{fmt, marker, pin};
3
4#[cfg(feature = "openssl")]
5use crate::connect::openssl;
6#[cfg(feature = "openssl")]
7use tls_openssl::ssl::SslConnector;
8
9#[cfg(feature = "rustls")]
10use crate::connect::rustls::{TlsClientFilter, TlsConnector};
11#[cfg(feature = "rustls")]
12use tls_rustls::ClientConfig as RustlsClientConfig;
13
14use base64::{Engine, engine::general_purpose::STANDARD as base64};
15use urly::Url;
16
17use crate::client::{ClientCodec, ClientConfig, ClientRawRequest, ClientResponse, host_header};
18use crate::connect::{Connect, ConnectError, Connector};
19use crate::error::{Error, ErrorMapping};
20use crate::http::body::BodySize;
21use crate::http::header::{self, HeaderMap, HeaderValue};
22use crate::http::{ConnectionType, Message, Method, RequestHead, StatusCode};
23use crate::io::{Base, DispatchItem, Dispatcher, Filter, Io, Layer, Reason, Sealed};
24use crate::service::{IntoService, Pipeline, apply_fn, fn_service};
25use crate::util::{Either, select};
26use crate::{Cfg, Service, SharedCfg, channel::mpsc, rt, time::timeout, ws};
27
28use super::cfg::is_token;
29use super::error::{WsClientError, WsConfigError, WsError};
30use super::proto::{CloseCode, CloseReason};
31use super::{WsClientConfig, handshake::header_contains_token, transport::WsTransport};
32
33thread_local! {
34    static CFG: SharedCfg = SharedCfg::new("WS-CLIENT").into();
35}
36
37/// Builder for establishing a WebSocket client connection.
38///
39/// The builder contains the target URI and a typed [`WsClientConfig`]. Use
40/// [`connect`](Self::connect) to perform the opening handshake.
41pub struct WsClient<F> {
42    uri: Url,
43    err: Option<WsConfigError>,
44    cfg: Cfg<WsClientConfig>,
45    http_cfg: Cfg<ClientConfig>,
46    connector: Pipeline<Connect<Url>, Io<F>, Error<ConnectError>>,
47    // the connector is the default plain tcp connector
48    plain: bool,
49    filter: marker::PhantomData<F>,
50}
51
52impl WsClient<Base> {
53    /// Creates a client for `uri` using the supplied configuration.
54    ///
55    /// ```rust
56    /// use ntex::{SharedCfg, time::Seconds};
57    /// use ntex::ws::{WsClient, WsClientConfig};
58    ///
59    /// #[ntex::main]
60    /// async fn main() {
61    ///     let cfg = SharedCfg::new("WS-CLIENT").add(
62    ///         WsClientConfig::new()
63    ///             .set_max_frame_size(128 * 1024)
64    ///             .set_handshake_timeout(Seconds(10))
65    ///     );
66    ///
67    ///     let _client = WsClient::new("ws://localhost/socket", cfg);
68    /// }
69    /// ```
70    ///
71    /// URI conversion and validation errors are stored and returned by
72    /// [`connect`](Self::connect).
73    ///
74    /// The default connector is plain TCP, so `wss` and `https` URIs fail with
75    /// [`WsConfigError::TlsRequired`] unless a TLS connector is installed
76    /// with `openssl()`, `rustls()` or [`connector`](WsClient::connector).
77    pub fn new<U>(uri: U, cfg: impl Into<Cfg<WsClientConfig>>) -> Self
78    where
79        Url: TryFrom<U>,
80        WsConfigError: From<<Url as TryFrom<U>>::Error>,
81    {
82        let (uri, err) = match Url::try_from(uri) {
83            Ok(uri) => {
84                let err = match uri.scheme_str() {
85                    _ if uri.host().is_none() => Some(WsConfigError::MissingHost),
86                    Some("http" | "ws" | "https" | "wss") => None,
87                    Some(_) => Some(WsConfigError::UnknownScheme),
88                    None => Some(WsConfigError::MissingScheme),
89                };
90                (uri, err)
91            }
92            Err(err) => (Url::new(), Some(WsConfigError::from(err))),
93        };
94
95        let cfg = cfg.into();
96        let shared = cfg.shared();
97
98        WsClient {
99            uri,
100            err,
101            cfg,
102            http_cfg: shared.get(),
103            connector: Pipeline::new(shared, Connector::<Url>::new()),
104            plain: true,
105            filter: marker::PhantomData,
106        }
107    }
108}
109
110impl<F> WsClient<F> {
111    /// Replaces the network connector used to establish the connection.
112    ///
113    /// The connector is used for every scheme; it is responsible for applying
114    /// TLS to `wss` and `https` URIs.
115    pub fn connector<U, S>(self, f: impl IntoService<S, SharedCfg, Connect<Url>>) -> WsClient<U>
116    where
117        U: Filter + 'static,
118        S: Service<SharedCfg, Connect<Url>, Res = Io<U>, Error = Error<ConnectError>> + 'static,
119    {
120        let shared = self.cfg.shared();
121        WsClient {
122            uri: self.uri,
123            err: self.err,
124            cfg: self.cfg,
125            http_cfg: self.http_cfg,
126            connector: Pipeline::new(shared, f.into_service()),
127            plain: false,
128            filter: marker::PhantomData,
129        }
130    }
131
132    #[cfg(feature = "openssl")]
133    /// Uses the supplied OpenSSL connector for secure connections.
134    pub fn openssl(self, config: SslConnector) -> WsClient<Layer<openssl::SslFilter>> {
135        self.connector(openssl::SslConnector::new(config))
136    }
137
138    #[cfg(feature = "rustls")]
139    /// Uses the supplied rustls connector for secure connections.
140    pub fn rustls(
141        self,
142        config: std::sync::Arc<RustlsClientConfig>,
143    ) -> WsClient<Layer<TlsClientFilter>> {
144        self.connector(TlsConnector::from(config))
145    }
146}
147
148impl<F> WsClient<F>
149where
150    F: Filter,
151{
152    /// Establishes the connection and performs the WebSocket opening handshake.
153    ///
154    /// # Errors
155    ///
156    /// Returns an error if connection establishment, HTTP encoding or decoding,
157    /// URI validation, timeout handling, or handshake validation fails.
158    pub async fn connect(&self) -> Result<WsConnection<F>, Error<WsClientError>> {
159        if let Some(err) = self.err.clone() {
160            return Err(Error::from(WsClientError::Config(err)).with_service(self.cfg.service()));
161        }
162        if self.plain && matches!(self.uri.scheme_str(), Some("https" | "wss")) {
163            return Err(
164                Error::from(WsClientError::Config(WsConfigError::TlsRequired))
165                    .with_service(self.cfg.service()),
166            );
167        }
168
169        let mut head = self.request_head();
170
171        // Generate a random key for the `Sec-WebSocket-Key` header.
172        // a base64-encoded (see Section 4 of [RFC4648]) value that,
173        // when decoded, is 16 bytes in length (RFC 6455)
174        let mut sec_key: [u8; 16] = [0; 16];
175        fastrand::fill(&mut sec_key);
176        let key = base64.encode(sec_key);
177
178        head.headers.insert(
179            header::SEC_WEBSOCKET_KEY,
180            HeaderValue::try_from(key.as_str()).unwrap(),
181        );
182
183        let msg = Connect::new(self.uri.clone()).set_addr(self.cfg.addr);
184        log::trace!(
185            "{}: Open ws connection to {:?} addr: {:?}",
186            self.cfg.tag(),
187            self.uri,
188            self.cfg.addr
189        );
190
191        // the connector attributes its own errors
192        let io = self.connector.call(msg).await.into_error()?;
193        self.handshake(io, head, &key)
194            .await
195            .map_err(|e| e.with_service(self.cfg.service()))
196    }
197
198    /// Sends the handshake request and validates the response.
199    async fn handshake(
200        &self,
201        io: Io<F>,
202        head: Message<RequestHead>,
203        key: &str,
204    ) -> Result<WsConnection<F>, Error<WsClientError>> {
205        let tag = io.tag();
206
207        // create Framed and send request
208        let codec = ClientCodec::new(true, io.shared().get());
209
210        // send request and read response
211        let fut = async {
212            log::trace!("{tag}: Sending ws handshake http message");
213            io.send(
214                ClientRawRequest {
215                    head,
216                    headers: None,
217                    size: BodySize::None,
218                }
219                .into(),
220                &codec,
221            )
222            .await?;
223            log::trace!("{tag}: Waiting for ws handshake response");
224            io.recv(&codec)
225                .await?
226                .ok_or(WsClientError::Disconnected(None))
227        };
228
229        // set request timeout
230        let response = if self.cfg.timeout.non_zero() {
231            timeout(self.cfg.timeout, fut)
232                .await
233                .map_err(|()| WsClientError::Timeout)
234                .and_then(|res| res)?
235        } else {
236            fut.await?
237        };
238        log::trace!("{tag}: Ws handshake response is received {response:?}");
239
240        // verify response
241        if response.status != StatusCode::SWITCHING_PROTOCOLS {
242            return Err(Error::from(WsClientError::InvalidResponseStatus(
243                response.status,
244            )));
245        }
246
247        // Check for "UPGRADE" to websocket header
248        if !header_contains_token(&response.headers, &header::UPGRADE, "websocket") {
249            log::trace!("{tag}: Invalid upgrade header");
250            return Err(Error::from(WsClientError::InvalidUpgradeHeader));
251        }
252
253        // Check for "CONNECTION" header
254        if let Some(conn) = response.headers.get(&header::CONNECTION) {
255            if !header_contains_token(&response.headers, &header::CONNECTION, "upgrade") {
256                log::trace!("{tag}: Invalid connection header: {conn:?}");
257                return Err(Error::from(WsClientError::InvalidConnectionHeader(
258                    conn.clone(),
259                )));
260            }
261        } else {
262            log::trace!("{tag}: Missing connection header");
263            return Err(Error::from(WsClientError::MissingConnectionHeader));
264        }
265
266        if let Some(hdr_key) = response.headers.get(&header::SEC_WEBSOCKET_ACCEPT) {
267            let encoded = ws::hash_key(key.as_ref()).map_err(|_| {
268                Error::from(WsClientError::InvalidChallengeResponse(
269                    String::new(),
270                    hdr_key.clone(),
271                ))
272            })?;
273            if hdr_key.as_bytes() != encoded.as_bytes() {
274                log::trace!(
275                    "{tag}: Invalid challenge response: expected: {encoded} received: {hdr_key:?}"
276                );
277                return Err(Error::from(WsClientError::InvalidChallengeResponse(
278                    encoded,
279                    hdr_key.clone(),
280                )));
281            }
282        } else {
283            log::trace!("{tag}: Missing SEC-WEBSOCKET-ACCEPT header");
284            return Err(Error::from(WsClientError::MissingWebSocketAcceptHeader));
285        }
286
287        validate_protocol(&response.headers, &self.cfg.headers).map_err(Error::from)?;
288        let codec = self
289            .negotiate_extensions(&response.headers)
290            .map_err(Error::from)?;
291        log::trace!("{tag}: Ws handshake response verification is completed");
292
293        // response and ws io
294        Ok(WsConnection::new(
295            io,
296            ClientResponse::with_empty_payload(response, self.http_cfg.clone()),
297            codec,
298        ))
299    }
300
301    /// Validates the accepted extensions, creates the connection's codec.
302    fn negotiate_extensions(&self, response: &HeaderMap) -> Result<ws::Codec, WsClientError> {
303        let mut codec = ws::Codec::new()
304            .max_size(self.cfg.max_size)
305            .max_message_size(self.cfg.max_message_size)
306            .validate_utf8(self.cfg.validate_utf8);
307        if !self.cfg.server_mode {
308            codec = codec.set_client_mode();
309        }
310
311        #[cfg(feature = "compress")]
312        if let Some(offer) = &self.cfg.deflate {
313            if let Some(agreed) = offer.accept(response)? {
314                log::trace!(
315                    "{}: Ws permessage-deflate is accepted {agreed:?}",
316                    self.cfg.tag()
317                );
318                codec = codec.set_deflate(agreed);
319            }
320            return Ok(codec);
321        }
322
323        if let Some(extensions) = response.get(header::SEC_WEBSOCKET_EXTENSIONS) {
324            return Err(WsClientError::UnexpectedWebSocketExtensions(
325                extensions.clone(),
326            ));
327        }
328        Ok(codec)
329    }
330}
331
332impl<F> WsClient<F> {
333    /// Creates the handshake request head without the `Sec-WebSocket-Key`.
334    fn request_head(&self) -> Message<RequestHead> {
335        let mut head = Message::<RequestHead>::new();
336        // the message pool may return a recycled head whose method is not GET
337        // (e.g. previously used by the HTTP/1 server dispatcher for a POST request)
338        head.method = Method::GET;
339        head.uri = self.uri.clone();
340        head.set_connection_type(ConnectionType::Upgrade);
341
342        // copy headers, the head is empty
343        for (key, value) in &self.cfg.headers {
344            head.headers_mut().append(key.clone(), value.clone());
345        }
346
347        #[cfg(feature = "compress")]
348        if let Some(deflate) = &self.cfg.deflate {
349            head.headers
350                .insert(header::SEC_WEBSOCKET_EXTENSIONS, deflate.offer());
351        }
352
353        // host header, without userinfo and the scheme's default port
354        if !head.headers.contains_key(header::HOST)
355            && let Some(val) = host_header(&self.uri)
356        {
357            head.headers.insert(header::HOST, val);
358        }
359
360        #[cfg(feature = "cookie")]
361        {
362            // set cookies, appended to a configured `Cookie` header
363            if let Some(ref jar) = self.cfg.cookies {
364                let mut cookie = Vec::new();
365                for value in head.headers.get_all(header::COOKIE) {
366                    if !cookie.is_empty() {
367                        cookie.extend_from_slice(b"; ");
368                    }
369                    cookie.extend_from_slice(value.as_bytes());
370                }
371                for c in jar.iter() {
372                    crate::http::helpers::push_cookie(&mut cookie, c.name(), c.value());
373                }
374                if let Ok(val) = HeaderValue::from_bytes(&cookie) {
375                    head.headers.insert(header::COOKIE, val);
376                }
377            }
378        }
379
380        head
381    }
382}
383
384fn validate_protocol(response: &HeaderMap, offered: &HeaderMap) -> Result<(), WsClientError> {
385    let mut protocols = response.get_all(header::SEC_WEBSOCKET_PROTOCOL);
386    if let Some(protocol) = protocols.next() {
387        let selected = protocol.to_str().ok();
388        let valid = protocols.next().is_none()
389            && selected.is_some_and(|selected| {
390                is_token(selected)
391                    && offered
392                        .get(header::SEC_WEBSOCKET_PROTOCOL)
393                        .and_then(|offered| offered.to_str().ok())
394                        .is_some_and(|offered| {
395                            offered.split(',').any(|item| item.trim() == selected)
396                        })
397            });
398        if !valid {
399            return Err(WsClientError::InvalidWebSocketProtocol(protocol.clone()));
400        }
401    }
402    Ok(())
403}
404
405impl<F> fmt::Debug for WsClient<F> {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        f.debug_struct("WsClient").field("cfg", &self.cfg).finish()
408    }
409}
410
411/// An established WebSocket client connection.
412///
413/// This value retains the opening-handshake response, the WebSocket codec, and
414/// the underlying I/O stream.
415pub struct WsConnection<F> {
416    io: Io<F>,
417    sink: ws::WsSink,
418    res: ClientResponse,
419}
420
421impl<F> WsConnection<F> {
422    fn new(io: Io<F>, res: ClientResponse, codec: ws::Codec) -> Self {
423        // the sink is also the dispatcher's codec, they share the codec state
424        let sink = ws::WsSink::new(io.get_ref(), codec, io.shared().get());
425        Self { io, sink, res }
426    }
427
428    /// Returns the connection's WebSocket codec.
429    pub fn codec(&self) -> &ws::Codec {
430        self.sink.codec()
431    }
432
433    /// Returns the opening-handshake response.
434    pub fn response(&self) -> &ClientResponse {
435        &self.res
436    }
437}
438
439impl<F> WsConnection<F> {
440    /// Returns a sink for sending messages over this connection.
441    ///
442    /// All sinks of a connection share the same state, so a message cannot be
443    /// sent through any of them once one has sent a close message.
444    pub fn sink(&self) -> ws::WsSink {
445        self.sink.clone()
446    }
447
448    /// Consumes the connection and returns its I/O stream, codec, and
449    /// opening-handshake response.
450    pub fn into_inner(self) -> (Io<F>, ws::Codec, ClientResponse) {
451        (self.io, self.sink.codec().clone(), self.res)
452    }
453}
454
455impl WsConnection<Sealed> {
456    /// Starts the WebSocket dispatcher and returns a channel of received frames.
457    ///
458    /// The dispatcher runs in a spawned task. Protocol and connection errors
459    /// are delivered through the returned channel. Pings and the peer's close
460    /// frame are answered automatically, see [`WsConnection::start()`].
461    /// Dropping the receiver sends a close frame and closes the connection
462    /// once the peer responds or the closing-handshake timeout expires.
463    pub fn receiver(self) -> mpsc::Receiver<Result<ws::Frame, WsError<()>>> {
464        let (tx, rx): (_, mpsc::Receiver<Result<ws::Frame, WsError<()>>>) = mpsc::channel();
465
466        rt::spawn_detached(async move {
467            let tx2 = tx.clone();
468            let io = self.io.get_ref();
469            let sink = self.sink();
470
471            // `start()` answers pings and the peer's close frame
472            let fut = self.start(fn_service(async move |item: ws::Frame| {
473                match tx.send(Ok(item)) {
474                    Ok(()) => (),
475                    Err(_) => io.close(),
476                }
477                Ok::<Option<ws::Message>, ()>(None)
478            }));
479            let mut fut = pin::pin!(fut);
480
481            let result = match select(fut.as_mut(), tx2.closed()).await {
482                Either::Left(result) => result,
483                Either::Right(()) => {
484                    // the receiver is dropped, start the closing handshake
485                    let _ = sink
486                        .send(ws::Message::Close(Some(CloseCode::Normal.into())))
487                        .await;
488                    fut.await
489                }
490            };
491
492            if let Err(e) = result {
493                let _ = tx2.send(Err(e));
494            }
495        });
496
497        rx
498    }
499
500    /// Runs the WebSocket dispatcher with `svc` handling received frames.
501    ///
502    /// The service may return a message to send to the peer or [`None`] when no
503    /// response is required.
504    ///
505    /// Control frames are passed to the service too. If it returns [`None`]
506    /// for a ping and hasn't sent a pong through a sink meanwhile, a pong with
507    /// the same payload is sent. If it returns [`None`] for the peer's close
508    /// frame, a close echoing the peer's code is sent. No automatic reply is
509    /// sent once a close message has been sent through a sink of this
510    /// connection. After the peer's close frame is handled, the connection is
511    /// closed.
512    pub async fn start<T>(
513        self,
514        svc: impl IntoService<T, (), ws::Frame>,
515    ) -> Result<(), WsError<T::Error>>
516    where
517        T: Service<(), ws::Frame, Res = Option<ws::Message>> + 'static,
518    {
519        let io = self.io.get_ref();
520        let sink = self.sink();
521        let service = apply_fn(
522            svc.into_service().map_err(WsError::Service),
523            async move |req, svc| match req {
524                DispatchItem::<ws::WsSink>::Item(item) => {
525                    let close = matches!(item, ws::Frame::Close(_));
526                    let reply = sink.codec().auto_reply(&item);
527                    let result = svc
528                        .call(item)
529                        .await
530                        .map(|res| sink.codec().unanswered(res, reply));
531                    if matches!(&result, Ok(Some(ws::Message::Close(_)))) {
532                        sink.start_close_timeout();
533                    }
534                    if close {
535                        let io = io.clone();
536                        rt::spawn_detached(async move { io.close() });
537                    }
538                    result
539                }
540                // a clean disconnect is not an error
541                DispatchItem::Control(_) | DispatchItem::Stop(Reason::Io(None)) => Ok(None),
542                DispatchItem::Stop(Reason::Service) => {
543                    Ok(Some(ws::Message::Close(Some(CloseReason {
544                        code: CloseCode::Away,
545                        description: None,
546                    }))))
547                }
548                DispatchItem::Stop(Reason::KeepAlive) => Err(WsError::KeepAlive),
549                DispatchItem::Stop(Reason::ReadTimeout) => Err(WsError::ReadTimeout),
550                DispatchItem::Stop(Reason::WriteTimeout) => Err(WsError::WriteTimeout),
551                DispatchItem::Stop(Reason::Decoder(e)) => {
552                    if !sink.is_closed() {
553                        let reason = CloseReason::from(CloseCode::Protocol);
554                        let _ = sink.send(ws::Message::Close(Some(reason))).await;
555                    }
556                    Err(WsError::Protocol(e))
557                }
558                DispatchItem::Stop(Reason::Encoder(e)) => Err(WsError::Protocol(e)),
559                DispatchItem::Stop(Reason::Io(e)) => Err(WsError::Disconnected(e)),
560            },
561        );
562
563        Dispatcher::new(self.io, self.sink, Pipeline::new((), service)).await
564    }
565}
566
567impl<F: Filter> WsConnection<F> {
568    /// Erases the concrete I/O filter type.
569    pub fn seal(self) -> WsConnection<Sealed> {
570        WsConnection {
571            io: self.io.seal(),
572            sink: self.sink,
573            res: self.res,
574        }
575    }
576
577    /// Converts the connection into a binary WebSocket transport.
578    pub fn into_transport(self) -> Io<Layer<WsTransport, F>> {
579        WsTransport::create(self.io, self.sink.codec().clone())
580    }
581}
582
583impl<F> fmt::Debug for WsConnection<F> {
584    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
585        f.debug_struct("WsConnection")
586            .field("response", &self.res)
587            .finish()
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    /// STATEMENT: WebSocket client debug output identifies the client type.
596    ///
597    /// HOW:
598    /// - Construct and format a client and inspect the type label.
599    #[crate::rt_test]
600    async fn test_debug() {
601        let client = WsClient::new("http://localhost", SharedCfg::default());
602        assert!(format!("{client:?}").contains("WsClient"));
603    }
604
605    /// STATEMENT: Handshake request construction preserves repeated headers and joins configured cookies.
606    ///
607    /// HOW:
608    /// - Configure repeated accept/cookie values plus a cookie object and inspect the generated request head.
609    #[crate::rt_test]
610    async fn request_head_keeps_all_header_values() {
611        let mut cfg = WsClientConfig::new();
612        cfg.headers
613            .append(header::ACCEPT, HeaderValue::from_static("a"));
614        cfg.headers
615            .append(header::ACCEPT, HeaderValue::from_static("b"));
616        #[cfg(feature = "cookie")]
617        {
618            cfg.headers
619                .append(header::COOKIE, HeaderValue::from_static("x=1"));
620            cfg.headers
621                .append(header::COOKIE, HeaderValue::from_static("y=2"));
622            cfg = cfg.set_cookie(coo_kie::Cookie::new("z", "3"));
623        }
624        let client = WsClient::new("http://localhost", SharedCfg::new("WS").add(cfg));
625
626        let head = client.request_head();
627        let values: Vec<_> = head.headers.get_all(header::ACCEPT).collect();
628        assert_eq!(values, ["a", "b"]);
629        #[cfg(feature = "cookie")]
630        assert_eq!(head.headers.get(header::COOKIE).unwrap(), "x=1; y=2; z=3");
631    }
632
633    /// STATEMENT: Setting a WebSocket client header again replaces its previous value.
634    ///
635    /// HOW:
636    /// - Set content type twice and inspect the final configured header.
637    #[crate::rt_test]
638    async fn header_override() {
639        let cfg = WsClientConfig::new()
640            .set_header(header::CONTENT_TYPE, "111")
641            .unwrap()
642            .set_header(header::CONTENT_TYPE, "222")
643            .unwrap();
644
645        assert_eq!(
646            cfg.headers
647                .get(header::CONTENT_TYPE)
648                .unwrap()
649                .to_str()
650                .unwrap(),
651            "222"
652        );
653    }
654
655    /// STATEMENT: Subprotocol configuration serializes valid tokens, removes empty offers, and rejects invalid tokens.
656    ///
657    /// HOW:
658    /// - Configure two protocols, clear them, and reject newline, whitespace, and comma-containing protocol names.
659    #[test]
660    fn protocols() {
661        let cfg = WsClientConfig::new()
662            .set_protocols(["chat", "superchat"])
663            .unwrap();
664        assert_eq!(
665            cfg.headers
666                .get(header::SEC_WEBSOCKET_PROTOCOL)
667                .unwrap()
668                .to_str()
669                .unwrap(),
670            "chat,superchat"
671        );
672
673        let cfg = cfg.set_protocols([] as [&str; 0]).unwrap();
674        assert!(!cfg.headers.contains_key(header::SEC_WEBSOCKET_PROTOCOL));
675        assert!(WsClientConfig::new().set_protocols(["bad\n"]).is_err());
676        assert!(
677            WsClientConfig::new()
678                .set_protocols(["bad protocol"])
679                .is_err()
680        );
681        assert!(
682            WsClientConfig::new()
683                .set_protocols(["first,second"])
684                .is_err()
685        );
686    }
687
688    /// STATEMENT: Subprotocol negotiation accepts one offered token and rejects unoffered or multiple selections.
689    ///
690    /// HOW:
691    /// - Validate selections against compact and spaced offers.
692    /// - Reject unknown tokens, comma-separated selections, and repeated selection headers.
693    #[test]
694    fn negotiation() {
695        let configured = WsClientConfig::new()
696            .set_protocols(["chat", "superchat"])
697            .unwrap();
698        let mut response = HeaderMap::new();
699
700        response.insert(
701            header::SEC_WEBSOCKET_PROTOCOL,
702            HeaderValue::from_static("chat"),
703        );
704        validate_protocol(&response, &configured.headers).unwrap();
705
706        let mut offered_headers = HeaderMap::new();
707        offered_headers.insert(
708            header::SEC_WEBSOCKET_PROTOCOL,
709            HeaderValue::from_static("chat, superchat"),
710        );
711        response.insert(
712            header::SEC_WEBSOCKET_PROTOCOL,
713            HeaderValue::from_static("superchat"),
714        );
715        validate_protocol(&response, &offered_headers).unwrap();
716
717        response.insert(
718            header::SEC_WEBSOCKET_PROTOCOL,
719            HeaderValue::from_static("other"),
720        );
721        assert!(matches!(
722            validate_protocol(&response, &configured.headers),
723            Err(WsClientError::InvalidWebSocketProtocol(_))
724        ));
725
726        response.insert(
727            header::SEC_WEBSOCKET_PROTOCOL,
728            HeaderValue::from_static("chat,superchat"),
729        );
730        assert!(matches!(
731            validate_protocol(&response, &configured.headers),
732            Err(WsClientError::InvalidWebSocketProtocol(_))
733        ));
734
735        response.remove(header::SEC_WEBSOCKET_PROTOCOL);
736        response.append(
737            header::SEC_WEBSOCKET_PROTOCOL,
738            HeaderValue::from_static("chat"),
739        );
740        response.append(
741            header::SEC_WEBSOCKET_PROTOCOL,
742            HeaderValue::from_static("superchat"),
743        );
744        assert!(matches!(
745            validate_protocol(&response, &configured.headers),
746            Err(WsClientError::InvalidWebSocketProtocol(_))
747        ));
748    }
749
750    /// STATEMENT: A client without extension configuration accepts no extensions and rejects unsolicited deflate.
751    ///
752    /// HOW:
753    /// - Negotiate empty headers, then add a deflate response and inspect the unexpected-extension error.
754    #[crate::rt_test]
755    async fn unexpected_extensions() {
756        let client = WsClient::new("ws://localhost", SharedCfg::default());
757        let mut response = HeaderMap::new();
758        assert!(!client.negotiate_extensions(&response).unwrap().is_closed());
759
760        response.insert(
761            header::SEC_WEBSOCKET_EXTENSIONS,
762            HeaderValue::from_static("permessage-deflate"),
763        );
764        assert!(matches!(
765            client.negotiate_extensions(&response),
766            Err(WsClientError::UnexpectedWebSocketExtensions(_))
767        ));
768    }
769
770    /// STATEMENT: The negotiated codec uses the configured message size limit and UTF-8 validation setting.
771    ///
772    /// HOW:
773    /// - Negotiate with `set_max_message_size(2)` and expect `Overflow` when a second fragment takes the message to 3 bytes.
774    /// - Expect the default configuration to reject a text frame holding `0xff`, and `set_validate_utf8(false)` to return it.
775    #[crate::rt_test]
776    async fn message_limits_apply_to_codec() {
777        use crate::codec::Decoder;
778        use crate::util::BytesMut;
779
780        let response = HeaderMap::new();
781        let codec = |cfg: WsClientConfig| {
782            WsClient::new("ws://localhost", SharedCfg::new("T").add(cfg))
783                .negotiate_extensions(&response)
784                .unwrap()
785        };
786
787        let limited = codec(WsClientConfig::new().set_max_message_size(2));
788        let mut src = BytesMut::from(&b"\x02\x02ab\x80\x01c"[..]);
789        assert!(limited.decode(&mut src).unwrap().is_some());
790        assert!(matches!(
791            limited.decode(&mut src),
792            Err(ws::error::ProtocolError::Overflow)
793        ));
794
795        let text = || BytesMut::from(&b"\x81\x01\xff"[..]);
796        assert!(matches!(
797            codec(WsClientConfig::new()).decode(&mut text()),
798            Err(ws::error::ProtocolError::InvalidUtf8)
799        ));
800        let unchecked = codec(WsClientConfig::new().set_validate_utf8(false));
801        assert!(matches!(
802            unchecked.decode(&mut text()),
803            Ok(Some(ws::Frame::Text(_)))
804        ));
805    }
806
807    /// STATEMENT: Invalid WebSocket URLs report specific configuration errors before connecting.
808    ///
809    /// HOW:
810    /// - Attempt connections with missing scheme, unsupported scheme, and missing host and compare error variants.
811    #[crate::rt_test]
812    async fn basic_errs() {
813        let err = WsClient::new("//localhost", SharedCfg::default())
814            .connect()
815            .await
816            .err()
817            .unwrap();
818        assert!(matches!(
819            err.into_error(),
820            WsClientError::Config(WsConfigError::MissingScheme)
821        ));
822
823        let err = WsClient::new("unknown://localhost", SharedCfg::default())
824            .connect()
825            .await
826            .err()
827            .unwrap();
828        assert!(matches!(
829            err.into_error(),
830            WsClientError::Config(WsConfigError::UnknownScheme)
831        ));
832
833        let err = WsClient::new("/", SharedCfg::default())
834            .connect()
835            .await
836            .err()
837            .unwrap();
838        assert!(matches!(
839            err.into_error(),
840            WsClientError::Config(WsConfigError::MissingHost)
841        ));
842    }
843
844    /// STATEMENT: Secure schemes are rejected over the default plain connector,
845    /// but are passed to a replacement connector.
846    ///
847    /// HOW:
848    /// - Connect to `wss` and `https` URIs with the default connector and check for
849    ///   `WsConfigError::TlsRequired`.
850    /// - Install a custom connector and check that it receives the `wss` request.
851    #[crate::rt_test]
852    async fn secure_scheme_requires_tls_connector() {
853        for uri in ["wss://localhost/", "https://localhost/"] {
854            let err = WsClient::new(uri, SharedCfg::new("WS"))
855                .connect()
856                .await
857                .err()
858                .unwrap();
859            assert!(matches!(
860                err.into_error(),
861                WsClientError::Config(WsConfigError::TlsRequired)
862            ));
863        }
864
865        let called = std::rc::Rc::new(std::cell::Cell::new(false));
866        let called2 = called.clone();
867        let err = WsClient::new("wss://localhost/", SharedCfg::new("WS"))
868            .connector(fn_service(async move |req: Connect<Url>| {
869                assert_eq!(req.host(), "localhost");
870                called2.set(true);
871                Err::<Io<Base>, _>(Error::from(ConnectError::Unresolved))
872            }))
873            .connect()
874            .await
875            .err()
876            .unwrap();
877        assert!(called.get());
878        assert!(matches!(
879            err.into_error(),
880            WsClientError::Connect(ConnectError::Unresolved)
881        ));
882    }
883
884    /// STATEMENT: Basic authentication encodes credentials correctly and replaces earlier authorization.
885    ///
886    /// HOW:
887    /// - Configure credentials with and without a password, update them, and compare complete authorization values.
888    #[crate::rt_test]
889    async fn basic_auth() {
890        let cfg = WsClientConfig::new()
891            .set_basic_auth("username", Some("password"))
892            .unwrap();
893        assert_eq!(
894            cfg.headers
895                .get(header::AUTHORIZATION)
896                .unwrap()
897                .to_str()
898                .unwrap(),
899            "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
900        );
901
902        let cfg = WsClientConfig::new()
903            .set_basic_auth("username", None)
904            .unwrap();
905        assert_eq!(
906            cfg.headers
907                .get(header::AUTHORIZATION)
908                .unwrap()
909                .to_str()
910                .unwrap(),
911            "Basic dXNlcm5hbWU6"
912        );
913
914        let cfg = cfg.set_basic_auth("username", Some("password")).unwrap();
915        assert_eq!(
916            cfg.headers
917                .get(header::AUTHORIZATION)
918                .unwrap()
919                .to_str()
920                .unwrap(),
921            "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
922        );
923    }
924
925    /// STATEMENT: Bearer authorization is stored as a sensitive header whose textual view is redacted.
926    ///
927    /// HOW:
928    /// - Configure a bearer token and verify its header text is masked.
929    #[crate::rt_test]
930    async fn bearer_auth() {
931        let cfg = WsClientConfig::new()
932            .set_bearer_auth("someS3cr3tAutht0k3n")
933            .unwrap();
934        assert_eq!(
935            cfg.headers
936                .get(header::AUTHORIZATION)
937                .unwrap()
938                .to_str()
939                .unwrap(),
940            "Bearer someS3cr3tAutht0k3n"
941        );
942    }
943
944    /// STATEMENT: Client options retain server mode and frame limits, and malformed URLs record construction errors.
945    ///
946    /// HOW:
947    /// - Build a configuration with origin, protocols, headers, cookie, mode, and size settings.
948    /// - Check mode/size and inspect error state for missing or invalid URL components.
949    #[cfg(feature = "cookie")]
950    #[crate::rt_test]
951    async fn basics() {
952        use coo_kie::Cookie;
953
954        let cfg = WsClientConfig::new()
955            .set_origin("test-origin")
956            .unwrap()
957            .set_max_frame_size(100)
958            .set_server_mode()
959            .set_protocols(["v1", "v2"])
960            .unwrap()
961            .set_header_if_none(header::CONTENT_TYPE, "json")
962            .unwrap()
963            .set_header_if_none(header::CONTENT_TYPE, "text")
964            .unwrap()
965            .set_cookie(Cookie::build(("cookie1", "value1")));
966
967        assert!(cfg.server_mode);
968        assert_eq!(cfg.max_size, 100);
969
970        assert!(WsClient::new("/", SharedCfg::default()).err.is_some());
971        assert!(
972            WsClient::new("http:///test", SharedCfg::default())
973                .err
974                .is_some()
975        );
976        assert!(
977            WsClient::new("hmm://test.com/", SharedCfg::default())
978                .err
979                .is_some()
980        );
981    }
982
983    /// Runs `connect()` over an in-memory stream, returns the handshake request.
984    async fn handshake_request(uri: &str, cfg: WsClientConfig) -> String {
985        use crate::{testing::IoTest, util::Bytes};
986        use std::cell::RefCell;
987
988        let (client, server) = IoTest::create();
989        client.remote_buffer_cap(4096);
990        let io = RefCell::new(Some(Io::new(server, SharedCfg::default())));
991        let ws = WsClient::new(uri, cfg).connector(fn_service(async move |_: Connect<Url>| {
992            Ok::<_, Error<ConnectError>>(io.borrow_mut().take().unwrap())
993        }));
994        let fut = rt::spawn(async move { ws.connect().await.map(drop) });
995
996        let mut req = Vec::new();
997        while !req.ends_with(b"\r\n\r\n") {
998            let buf: Bytes = client.read().await.unwrap();
999            req.extend_from_slice(&buf);
1000        }
1001        client.close().await;
1002        let _ = fut.await;
1003        String::from_utf8(req).unwrap()
1004    }
1005
1006    /// STATEMENT: Recycling an HTTP request head does not change the WebSocket handshake method from GET.
1007    ///
1008    /// HOW:
1009    /// - Return a POST head to the pool, perform an in-memory handshake, and inspect its wire request line.
1010    #[crate::rt_test]
1011    async fn pooled_request_head_method_is_get() {
1012        // a request head released back to the thread-local message pool keeps its
1013        // method (e.g. POST from the HTTP/1 server dispatcher); a ws client built
1014        // from such a recycled head must still send a GET handshake
1015        let mut head = Message::<RequestHead>::new();
1016        head.method = Method::POST;
1017        drop(head);
1018
1019        let req = handshake_request("ws://localhost/", WsClientConfig::new()).await;
1020        assert!(req.starts_with("GET / HTTP/1.1\r\n"), "{req}");
1021    }
1022
1023    /// STATEMENT: Deflate is offered only when configured and replaces an existing extension header.
1024    ///
1025    /// HOW:
1026    /// - Capture default and deflate-enabled handshake requests and compare their extension lines.
1027    #[cfg(feature = "compress")]
1028    #[crate::rt_test]
1029    async fn deflate_offer() {
1030        let req = handshake_request("ws://localhost/", WsClientConfig::new()).await;
1031        assert!(!req.contains("sec-websocket-extensions"), "{req}");
1032
1033        // the offer replaces a configured header
1034        let cfg = WsClientConfig::new()
1035            .set_header(header::SEC_WEBSOCKET_EXTENSIONS, "x-ext")
1036            .unwrap()
1037            .set_deflate(ws::DeflateConfig::new().set_server_no_context_takeover(true));
1038        let req = handshake_request("ws://localhost/", cfg).await;
1039        let offers: Vec<_> = req
1040            .lines()
1041            .filter_map(|l| l.strip_prefix("sec-websocket-extensions: "))
1042            .collect();
1043        assert_eq!(
1044            offers,
1045            ["permessage-deflate; server_no_context_takeover; client_max_window_bits"]
1046        );
1047    }
1048
1049    /// STATEMENT: Successful deflate negotiation configures frame decoding, while a declined offer leaves compression disabled.
1050    ///
1051    /// HOW:
1052    /// - Complete an in-memory compressed handshake, inspect agreed options, and receive a compressed message.
1053    /// - Drop the receiver and check normal close, then verify a declined offer yields no deflate configuration.
1054    #[cfg(feature = "compress")]
1055    #[crate::rt_test]
1056    async fn deflate_connection() {
1057        let cfg = WsClientConfig::new().set_deflate(ws::DeflateConfig::new());
1058        let (res, client) = connect_with(cfg, SharedCfg::default(), |accept| {
1059            switching(&format!(
1060                "upgrade: websocket\r\nconnection: upgrade\r\nsec-websocket-accept: {accept}\r\n\
1061                 sec-websocket-extensions: permessage-deflate; client_no_context_takeover\r\n"
1062            ))
1063        })
1064        .await;
1065        let conn = res.unwrap();
1066        let agreed = ws::DeflateConfig::new().set_client_no_context_takeover(true);
1067        assert_eq!(conn.codec().deflate(), Some(&agreed));
1068
1069        // a compressed message from the peer
1070        let peer = ws::Codec::new().set_deflate(agreed);
1071        let rx = conn.seal().receiver();
1072        client.write(peer_frame(&peer, ws::Message::Text("Hello".into())));
1073        let item = rx.recv().await.unwrap().unwrap();
1074        assert_eq!(item, ws::Frame::Text("Hello".into()));
1075        drop(rx);
1076        crate::time::sleep(crate::time::Millis(50)).await;
1077        assert_eq!(
1078            read_frame(&client, &peer),
1079            ws::Frame::Close(Some(CloseCode::Normal.into()))
1080        );
1081
1082        // the server declines the offer
1083        let cfg = WsClientConfig::new().set_deflate(ws::DeflateConfig::new());
1084        let (res, _client) = connected(cfg, SharedCfg::default()).await;
1085        assert_eq!(res.unwrap().codec().deflate(), None);
1086    }
1087
1088    /// STATEMENT: Cookie objects extend an explicitly configured cookie header rather than replacing it.
1089    ///
1090    /// HOW:
1091    /// - Capture handshakes with cookie objects alone and with an existing cookie header.
1092    /// - Compare all cookie pairs and verify the original header value remains first.
1093    #[cfg(feature = "cookie")]
1094    #[crate::rt_test]
1095    async fn cookies_extend_configured_header() {
1096        use coo_kie::Cookie;
1097
1098        let cfg = || {
1099            WsClientConfig::new()
1100                .set_cookie(Cookie::build(("c1", "v1")))
1101                .set_cookie(Cookie::build(("c2", "v2")))
1102        };
1103        let req = handshake_request("ws://localhost/", cfg()).await;
1104        let cookie = req
1105            .lines()
1106            .find_map(|l| l.strip_prefix("cookie: "))
1107            .unwrap();
1108        let mut cookies: Vec<_> = cookie.split("; ").collect();
1109        cookies.sort_unstable();
1110        assert_eq!(cookies, ["c1=v1", "c2=v2"]);
1111
1112        let cfg = cfg().set_header(header::COOKIE, "c0=v0").unwrap();
1113        let req = handshake_request("ws://localhost/", cfg).await;
1114        let cookie = req
1115            .lines()
1116            .find_map(|l| l.strip_prefix("cookie: "))
1117            .unwrap();
1118        assert!(cookie.starts_with("c0=v0; "), "{cookie}");
1119        let mut cookies: Vec<_> = cookie.split("; ").collect();
1120        cookies.sort_unstable();
1121        assert_eq!(cookies, ["c0=v0", "c1=v1", "c2=v2"]);
1122    }
1123
1124    type Connected = (
1125        Result<WsConnection<Base>, Error<WsClientError>>,
1126        crate::testing::IoTest,
1127    );
1128
1129    /// Runs `connect()` against an in-memory peer that answers the handshake
1130    /// with the response produced by `response`.
1131    async fn connect_with(
1132        cfg: WsClientConfig,
1133        io_cfg: SharedCfg,
1134        response: impl FnOnce(String) -> String,
1135    ) -> Connected {
1136        use crate::{testing::IoTest, util::Bytes};
1137        use std::cell::RefCell;
1138
1139        let (client, server) = IoTest::create();
1140        client.remote_buffer_cap(4096);
1141        let io = RefCell::new(Some(Io::new(server, io_cfg)));
1142        let ws = WsClient::new("ws://localhost/", SharedCfg::new("WS").add(cfg)).connector(
1143            fn_service(async move |_: Connect<Url>| {
1144                Ok::<_, Error<ConnectError>>(io.borrow_mut().take().unwrap())
1145            }),
1146        );
1147        let fut = rt::spawn(async move { ws.connect().await });
1148
1149        let mut req = Vec::new();
1150        while !req.ends_with(b"\r\n\r\n") {
1151            let buf: Bytes = client.read().await.unwrap();
1152            req.extend_from_slice(&buf);
1153        }
1154        let req = String::from_utf8(req).unwrap();
1155        let key = req
1156            .lines()
1157            .find_map(|l| l.strip_prefix("sec-websocket-key: "))
1158            .unwrap();
1159        let accept = ws::hash_key(key.as_bytes()).unwrap();
1160        client.write(response(accept));
1161        (fut.await.unwrap(), client)
1162    }
1163
1164    fn switching(headers: &str) -> String {
1165        format!("HTTP/1.1 101 Switching Protocols\r\n{headers}\r\n")
1166    }
1167
1168    fn valid(accept: &str) -> String {
1169        switching(&format!(
1170            "upgrade: websocket\r\nconnection: upgrade\r\nsec-websocket-accept: {accept}\r\n"
1171        ))
1172    }
1173
1174    async fn connected(cfg: WsClientConfig, io_cfg: SharedCfg) -> Connected {
1175        connect_with(cfg, io_cfg, |accept| valid(&accept)).await
1176    }
1177
1178    /// STATEMENT: Invalid upgrade responses produce component-specific WebSocket client errors.
1179    ///
1180    /// HOW:
1181    /// - Answer in-memory handshakes with invalid/missing upgrade, connection, and accept headers.
1182    /// - Compare error variants and retained invalid header values.
1183    #[crate::rt_test]
1184    async fn handshake_response_errors() {
1185        async fn err(response: impl FnOnce(String) -> String) -> WsClientError {
1186            let cfg = WsClientConfig::new().set_handshake_timeout(0);
1187            let (res, _client) = connect_with(cfg, SharedCfg::default(), response).await;
1188            res.unwrap_err().into_error()
1189        }
1190
1191        assert!(matches!(
1192            err(|_| switching("upgrade: h2c\r\nconnection: upgrade\r\n")).await,
1193            WsClientError::InvalidUpgradeHeader
1194        ));
1195        assert!(matches!(
1196            err(|_| switching("upgrade: websocket\r\nconnection: close\r\n")).await,
1197            WsClientError::InvalidConnectionHeader(val) if val == "close"
1198        ));
1199        assert!(matches!(
1200            err(|_| switching("upgrade: websocket\r\n")).await,
1201            WsClientError::MissingConnectionHeader
1202        ));
1203        assert!(matches!(
1204            err(|_| switching("upgrade: websocket\r\nconnection: upgrade\r\n")).await,
1205            WsClientError::MissingWebSocketAcceptHeader
1206        ));
1207        assert!(matches!(
1208            err(|_| valid("aW52YWxpZA==")).await,
1209            WsClientError::InvalidChallengeResponse(_, val) if val == "aW52YWxpZA=="
1210        ));
1211    }
1212
1213    fn peer_frame(codec: &ws::Codec, msg: ws::Message) -> crate::util::Bytes {
1214        let mut dst = crate::util::BytePages::default();
1215        crate::codec::Encoder::encode(codec, msg, &mut dst).unwrap();
1216        dst.into()
1217    }
1218
1219    fn read_frame(client: &crate::testing::IoTest, codec: &ws::Codec) -> ws::Frame {
1220        let mut data = crate::util::BytesMut::from(&client.read_any()[..]);
1221        crate::codec::Decoder::decode(codec, &mut data)
1222            .unwrap()
1223            .unwrap()
1224    }
1225
1226    /// STATEMENT: Server-mode connections accept extension close codes but reply with a server-valid normal close.
1227    ///
1228    /// HOW:
1229    /// - Complete a handshake, inspect response/codec state, and send a masked client extension close.
1230    /// - Check the delivered reason and decode the normal-close reply.
1231    #[crate::rt_test]
1232    async fn server_mode_connection() {
1233        let cfg = WsClientConfig::new().set_server_mode();
1234        let (res, client) = connected(cfg, SharedCfg::default()).await;
1235        let conn = res.unwrap();
1236        assert!(format!("{conn:?}").contains("WsConnection"));
1237        assert_eq!(conn.response().status(), StatusCode::SWITCHING_PROTOCOLS);
1238        assert!(!conn.codec().is_closed());
1239
1240        // servers cannot send 1010, the peer's close is answered with 1000
1241        let rx = conn.seal().receiver();
1242        client.write(peer_frame(
1243            &ws::Codec::new().set_client_mode(),
1244            ws::Message::Close(Some(CloseCode::Extension.into())),
1245        ));
1246        let item = rx.recv().await.unwrap().unwrap();
1247        assert_eq!(item, ws::Frame::Close(Some(CloseCode::Extension.into())));
1248        crate::time::sleep(crate::time::Millis(50)).await;
1249        assert_eq!(
1250            read_frame(&client, &ws::Codec::new().set_client_mode()),
1251            ws::Frame::Close(Some(CloseCode::Normal.into()))
1252        );
1253    }
1254
1255    /// STATEMENT: The client receiver answers pings with a pong carrying the same payload and still delivers the ping.
1256    ///
1257    /// HOW:
1258    /// - Write a ping from the in-memory server, receive it from `receiver()`, and decode the client's pong reply.
1259    /// - Then write a raw close with the extension code and expect the client to echo it.
1260    #[crate::rt_test]
1261    async fn receiver_answers_ping() {
1262        let (res, client) = connected(WsClientConfig::new(), SharedCfg::default()).await;
1263        let rx = res.unwrap().seal().receiver();
1264        let peer = ws::Codec::new();
1265
1266        client.write(peer_frame(&peer, ws::Message::Ping("hb".into())));
1267        let item = rx.recv().await.unwrap().unwrap();
1268        assert_eq!(item, ws::Frame::Ping("hb".into()));
1269        crate::time::sleep(crate::time::Millis(50)).await;
1270        assert_eq!(read_frame(&client, &peer), ws::Frame::Pong("hb".into()));
1271
1272        // clients may send the extension code, servers cannot encode it
1273        client.write(&[0x88, 0x02, 0x03, 0xf2][..]);
1274        let item = rx.recv().await.unwrap().unwrap();
1275        assert_eq!(item, ws::Frame::Close(Some(CloseCode::Extension.into())));
1276        crate::time::sleep(crate::time::Millis(50)).await;
1277        assert_eq!(
1278            read_frame(&client, &peer),
1279            ws::Frame::Close(Some(CloseCode::Extension.into()))
1280        );
1281    }
1282
1283    /// STATEMENT: A WebSocket application service failure sends an away close and returns the service error.
1284    ///
1285    /// HOW:
1286    /// - Deliver text to a failing service and compare the returned error and peer-visible close reason.
1287    #[crate::rt_test]
1288    async fn start_service_error_sends_away_close() {
1289        let (res, client) = connected(WsClientConfig::new(), SharedCfg::default()).await;
1290        let conn = res.unwrap().seal();
1291
1292        client.write(peer_frame(
1293            &ws::Codec::new(),
1294            ws::Message::Text("text".into()),
1295        ));
1296        let err = conn
1297            .start(fn_service(async |_: ws::Frame| {
1298                Err::<Option<ws::Message>, _>("err")
1299            }))
1300            .await
1301            .unwrap_err();
1302        assert!(matches!(err, WsError::Service("err")));
1303        assert_eq!(
1304            read_frame(&client, &ws::Codec::new()),
1305            ws::Frame::Close(Some(CloseCode::Away.into()))
1306        );
1307    }
1308
1309    /// STATEMENT: Invalid messages returned by a WebSocket service surface as protocol encoding errors.
1310    ///
1311    /// HOW:
1312    /// - Return an oversized ping after receiving text and verify the invalid-length error.
1313    #[crate::rt_test]
1314    async fn start_encoder_error() {
1315        let (res, client) = connected(WsClientConfig::new(), SharedCfg::default()).await;
1316        let conn = res.unwrap().seal();
1317
1318        client.write(peer_frame(
1319            &ws::Codec::new(),
1320            ws::Message::Text("text".into()),
1321        ));
1322        let err = conn
1323            .start(fn_service(async |_: ws::Frame| {
1324                Ok::<_, ()>(Some(ws::Message::Ping(vec![0; 126].into())))
1325            }))
1326            .await
1327            .unwrap_err();
1328        assert!(matches!(
1329            err,
1330            WsError::Protocol(ws::error::ProtocolError::InvalidLength(126))
1331        ));
1332    }
1333
1334    /// STATEMENT: WebSocket dispatch preserves transport failures as disconnect errors.
1335    ///
1336    /// HOW:
1337    /// - Inject a read error into a connected transport and inspect the dispatch result.
1338    #[crate::rt_test]
1339    async fn start_io_error() {
1340        let (res, client) = connected(WsClientConfig::new(), SharedCfg::default()).await;
1341        let conn = res.unwrap().seal();
1342
1343        client.read_error(std::io::Error::other("failed"));
1344        let err = conn
1345            .start(fn_service(async |_: ws::Frame| Ok::<_, ()>(None)))
1346            .await
1347            .unwrap_err();
1348        assert!(matches!(err, WsError::Disconnected(Some(_))));
1349    }
1350
1351    /// STATEMENT: An idle WebSocket dispatcher terminates on its configured keepalive deadline.
1352    ///
1353    /// HOW:
1354    /// - Start a connection with a short keepalive timeout and no peer frames and verify the keepalive error.
1355    #[crate::rt_test]
1356    async fn start_keepalive() {
1357        let io_cfg = SharedCfg::new("KA")
1358            .add(crate::io::IoConfig::new().set_keepalive_timeout(crate::time::Seconds(1)));
1359        let (res, _client) = connected(WsClientConfig::new(), io_cfg.into()).await;
1360        let err = res
1361            .unwrap()
1362            .seal()
1363            .start(fn_service(async |_: ws::Frame| Ok::<_, ()>(None)))
1364            .await
1365            .unwrap_err();
1366        assert!(matches!(err, WsError::KeepAlive));
1367    }
1368}