Skip to main content

jsonrpsee_server/transport/
ws.rs

1use std::{
2    io,
3    pin::Pin,
4    sync::{
5        atomic::{AtomicBool, Ordering},
6        Arc,
7    },
8    task::{Context, Poll},
9    time::Duration,
10};
11
12use crate::{
13    server::{handle_rpc_call, ConnectionState, ServerConfig},
14    HttpBody, HttpResponse, LOG_TARGET,
15};
16
17use futures_util::{
18    future::{self, Either},
19    Future, StreamExt, TryStreamExt,
20};
21use http::{
22    header::{CONNECTION, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_VERSION, UPGRADE},
23    Method, StatusCode, Version,
24};
25use hyper::{body::Bytes, upgrade::Upgraded};
26use hyper_util::rt::TokioIo;
27use jsonrpsee_core::{classify_message, middleware::RpcServiceT, server::MethodSink};
28use jsonrpsee_types::{
29    error::{reject_too_big_request, ErrorCode},
30    Id,
31};
32use parking_lot::Mutex;
33use tokio::{
34    io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter, ReadBuf, ReadHalf, WriteHalf},
35    sync::{mpsc, oneshot, Notify, Semaphore},
36    time::{interval_at, timeout, timeout_at, Instant},
37};
38use tokio_stream::wrappers::ReceiverStream;
39use tokio_tungstenite::{
40    tungstenite::{
41        self,
42        error::{CapacityError, ProtocolError},
43        handshake::derive_accept_key,
44        protocol::{
45            frame::{
46                coding::{CloseCode, Control, Data, OpCode},
47                Frame,
48            },
49            Role, WebSocketConfig,
50        },
51        Message,
52    },
53    WebSocketStream,
54};
55
56pub(crate) type Receiver = WebSocketStream<ReadIo>;
57
58/// Returns whether the request asks for an upgrade to the WebSocket protocol.
59pub fn is_upgrade_request<B>(request: &http::Request<B>) -> bool {
60    let has_token = |name, token: &[u8]| {
61        request.headers().get_all(name).iter().any(|value| {
62            value
63                .as_bytes()
64                .split(|&b| b == b',')
65                .any(|listed| listed.trim_ascii().eq_ignore_ascii_case(token))
66        })
67    };
68    has_token(CONNECTION, b"upgrade") && has_token(UPGRADE, b"websocket")
69}
70
71/// Returns the response that accepts `request`, for which [`is_upgrade_request`] holds.
72///
73/// `tungstenite` would only read the first `Connection` header and want an `Upgrade` header of
74/// exactly `websocket`, which refuses requests that [`is_upgrade_request`] accepts.
75pub(crate) fn upgrade_response<B>(
76    request: &http::Request<B>,
77) -> Result<HttpResponse, tungstenite::Error> {
78    if request.method() != Method::GET {
79        return Err(ProtocolError::WrongHttpMethod.into());
80    }
81    if request.version() < Version::HTTP_11 {
82        return Err(ProtocolError::WrongHttpVersion.into());
83    }
84    if request.headers().get(SEC_WEBSOCKET_VERSION).is_none_or(|version| version != "13") {
85        return Err(ProtocolError::MissingSecWebSocketVersionHeader.into());
86    }
87    let key =
88        request.headers().get(SEC_WEBSOCKET_KEY).ok_or(ProtocolError::MissingSecWebSocketKey)?;
89
90    Ok(http::Response::builder()
91        .status(StatusCode::SWITCHING_PROTOCOLS)
92        .version(request.version())
93        .header(CONNECTION, "Upgrade")
94        .header(UPGRADE, "websocket")
95        .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(key.as_bytes()))
96        .body(HttpBody::empty())?)
97}
98
99/// Most queued messages written before a flush, which bounds how long written messages wait in
100/// the buffer.
101const MAX_MESSAGES_PER_FLUSH: usize = 64;
102
103pub(crate) struct BackgroundTaskParams<S> {
104    pub(crate) server_cfg: ServerConfig,
105    pub(crate) conn: ConnectionState,
106    pub(crate) ws_sender: Sender,
107    pub(crate) ws_receiver: Receiver,
108    pub(crate) rpc_service: S,
109    pub(crate) sink: MethodSink,
110    pub(crate) rx: mpsc::Receiver<String>,
111    /// Held by every running call, so that a graceful shutdown can wait for them.
112    pub(crate) pending_calls: mpsc::Sender<()>,
113    pub(crate) pending_calls_completed: mpsc::Receiver<()>,
114}
115
116pub(crate) async fn background_task<S>(params: BackgroundTaskParams<S>)
117where
118    S: RpcServiceT + Send + Sync + 'static,
119{
120    let BackgroundTaskParams {
121        server_cfg,
122        conn,
123        ws_sender,
124        ws_receiver,
125        rpc_service,
126        sink,
127        rx,
128        pending_calls,
129        pending_calls_completed,
130    } = params;
131    let ServerConfig {
132        batch_requests_config,
133        max_request_body_size,
134        write_timeout,
135        message_buffer_capacity,
136        ping_interval,
137        ..
138    } = server_cfg;
139
140    let (conn_tx, conn_rx) = oneshot::channel();
141    let control = ws_sender.control.clone();
142    let call_permits = Arc::new(Semaphore::new(message_buffer_capacity as usize));
143
144    // Spawn another task that sends out the responses on the Websocket.
145    let send_task_handle = tokio::spawn(send_task(
146        rx,
147        ws_sender,
148        write_timeout,
149        ping_interval,
150        CallsInFlight { permits: call_permits.clone(), max: message_buffer_capacity as usize },
151        conn_rx,
152    ));
153
154    let stopped = conn.stop_handle.clone().shutdown();
155    let rpc_service = Arc::new(rpc_service);
156
157    tokio::pin!(stopped);
158
159    // `tungstenite` reserves a frame's announced length before its payload arrives, so a frame that
160    // never completes would hold that buffer for good. A pong can't arrive inside a frame, so a
161    // read that yields neither a message nor a pong to the pings within two intervals is stuck.
162    let read_timeout = ping_interval * 2;
163    let ws_stream = futures_util::stream::unfold(Some(ws_receiver), move |receiver| {
164        let control = control.clone();
165        async move {
166            let mut receiver = receiver?;
167            let mut deadline = Instant::now() + read_timeout;
168            loop {
169                let Ok(received) = timeout_at(deadline, receiver.next()).await else {
170                    return Some((
171                        Err(tungstenite::Error::Io(io::ErrorKind::TimedOut.into())),
172                        Some(receiver),
173                    ));
174                };
175                match received? {
176                    // A payload is a slice of `tungstenite`'s read buffer, so a call that held it
177                    // would keep the whole buffer allocated once the next frame needs a new one.
178                    Ok(Message::Text(text)) => {
179                        return Some((Ok(Bytes::copy_from_slice(text.as_bytes())), Some(receiver)))
180                    }
181                    Ok(Message::Binary(data)) => {
182                        return Some((Ok(Bytes::copy_from_slice(&data)), Some(receiver)))
183                    }
184                    // Pongs only answer the server's pings, which restarts the read timeout.
185                    Ok(Message::Pong(_)) => deadline = Instant::now() + read_timeout,
186                    // `tungstenite` has queued the pong and writes it with the next read, into
187                    // the control frames that the send task writes out. The read waits for the
188                    // previous pong to be written, so that pongs can't pile up for a client that
189                    // isn't reading.
190                    Ok(Message::Ping(_)) => {
191                        // The send task has ended, and the connection with it.
192                        if !control.written().await {
193                            return None;
194                        }
195                    }
196                    Ok(Message::Close(close)) => {
197                        // Preserve tungstenite's validated reply before dropping its queued close.
198                        *control.close_reply.lock() = Some(Frame::close(close).into_payload());
199                        return None;
200                    }
201                    // Raw frames are only written, never read.
202                    Ok(Message::Frame(_)) => {}
203                    // `tungstenite` reads nothing more after an error, so the stream ends with it.
204                    Err(e) => return Some((Err(e), None)),
205                }
206            }
207        }
208    })
209    .fuse();
210
211    tokio::pin!(ws_stream);
212
213    let result = loop {
214        let receive = tokio::select! {
215            receive = try_recv(&mut ws_stream, stopped) => receive,
216            // The send task has terminated, e.g. because a write timed out, so nothing can be sent
217            // back to the client anymore.
218            _ = sink.closed() => break Ok(Shutdown::ConnectionClosed),
219        };
220        let data = match receive {
221            Receive::ConnectionClosed => break Ok(Shutdown::ConnectionClosed),
222            Receive::Stopped => break Ok(Shutdown::Stopped),
223            Receive::Ok(data, stop) => {
224                stopped = stop;
225                data
226            }
227            Receive::Err(err, stop) => {
228                stopped = stop;
229
230                match err {
231                    tungstenite::Error::Capacity(CapacityError::MessageTooLong {
232                        size: current,
233                        max_size: maximum,
234                    }) => {
235                        tracing::debug!(
236                            target: LOG_TARGET,
237                            "WS recv error: message too large current={}/max={}",
238                            current,
239                            maximum
240                        );
241                        if sink
242                            .send_error(Id::Null, reject_too_big_request(max_request_body_size))
243                            .await
244                            .is_err()
245                        {
246                            break Ok(Shutdown::ConnectionClosed);
247                        }
248
249                        // The stream has ended, so the next read closes the connection after the
250                        // rejection is written.
251                        continue;
252                    }
253                    err => {
254                        tracing::debug!(target: LOG_TARGET, "WS error: {}; terminate connection: {}", err, conn.conn_id);
255                        break Err(err);
256                    }
257                };
258            }
259        };
260
261        // A connection runs at most `message_buffer_capacity` calls at once. While waiting for a
262        // permit no further messages are read, which pushes back on the client, and the message
263        // that is waiting is the only one held. The permit is acquired after the read so that a
264        // connection at the limit that sends nothing more is still read and its close is noticed.
265        // Every call ends once the sink is closed, which frees the permits, so this wait ends
266        // when the connection closes.
267        let permit = tokio::select! {
268            permit = call_permits.clone().acquire_owned() => permit,
269            _ = &mut stopped => break Ok(Shutdown::Stopped),
270        };
271        // The semaphore is never closed.
272        let Ok(permit) = permit else { break Ok(Shutdown::ConnectionClosed) };
273
274        let rpc_service = rpc_service.clone();
275        let sink = sink.clone();
276        let pending_calls = pending_calls.clone();
277
278        tokio::spawn(async move {
279            let _pending_calls = pending_calls;
280            let _permit = permit;
281            let Some((data, is_single)) = classify_message(&data) else {
282                _ = sink.send_error(Id::Null, ErrorCode::ParseError.into()).await;
283                return;
284            };
285
286            // Calls are not tied to the connection task, so stop them once the connection is closed
287            // instead of running them to completion without anyone to send the response to.
288            let rp = tokio::select! {
289                // The call is polled first, so one that answers at once doesn't have to register
290                // for the close of the connection.
291                biased;
292                // WebSocket sends a response as one message, so a streamed one is buffered.
293                rp = async {
294                    handle_rpc_call(
295                        data,
296                        is_single,
297                        batch_requests_config,
298                        max_request_body_size,
299                        &*rpc_service,
300                    )
301                    .await
302                    .buffer()
303                    .await
304                } => rp,
305                _ = sink.closed() => return,
306            };
307
308            // Subscriptions are handled by the subscription callback and
309            // "ordinary notifications" should not be sent back to the client.
310            if rp.is_method_call() || rp.is_batch() {
311                // An error means the connection is closed, so there is nothing left to do.
312                let _ = sink.send(rp.into_json()).await;
313            }
314        });
315    };
316
317    // Drive all running methods to completion.
318    // **NOTE** Do not return early in this function. This `await` needs to run to guarantee
319    // proper drop behaviour.
320    drop(rpc_service);
321    drop(pending_calls);
322    graceful_shutdown(result, pending_calls_completed, ws_stream, conn_tx, send_task_handle).await;
323
324    drop(conn);
325}
326
327/// A task that waits for new messages via the `rx channel` and sends them out on the `WebSocket`,
328/// and pings the client every `ping_interval`.
329async fn send_task(
330    mut rx: mpsc::Receiver<String>,
331    mut ws_sender: Sender,
332    write_timeout: Duration,
333    ping_interval: Duration,
334    calls: CallsInFlight,
335    mut stop: oneshot::Receiver<()>,
336) {
337    let control = ws_sender.control.clone();
338    let mut write_timed_out = false;
339    let mut ping_timer = interval_at(Instant::now() + ping_interval, ping_interval);
340    // Whether a yield before the flush is worth its wait: cleared by one that queued nothing, and
341    // set again once a message is found queued behind another.
342    let mut batching = true;
343
344    loop {
345        let mut result = tokio::select! {
346            // Stop is polled first: a subscription that queues messages faster than the client
347            // reads them keeps `rx.recv()` ready, which would never let a stopped server end the
348            // session.
349            biased;
350            _ = &mut stop, if !rx.is_closed() => {
351                // Take nothing new but write out what is queued: answers to calls this server has
352                // run, which a graceful shutdown owes its clients. `rx.recv()` returns `None` once
353                // the closed queue is drained.
354                rx.close();
355                continue;
356            }
357            // Pings go before queued messages, so that a subscription that keeps the queue full
358            // can't hold them back until the read timeout closes the connection.
359            _ = ping_timer.tick() => {
360                timeout(write_timeout, ws_sender.write_frame(OpCode::Control(Control::Ping), &[])).await
361            }
362            // Pongs go before queued messages too, as the receive stream waits for them.
363            () = control.queued.notified() => {
364                timeout(write_timeout, ws_sender.write_control()).await
365            }
366            response = rx.recv() => {
367                // Nothing else to receive.
368                let Some(response) = response else { break };
369                timeout(write_timeout, ws_sender.write_frame(OpCode::Data(Data::Text), response.as_bytes())).await
370            }
371        };
372        // Write the messages that are already queued too, and flush them together.
373        let mut written = 1;
374        let mut yielded = false;
375        while matches!(result, Ok(Ok(()))) && written < MAX_MESSAGES_PER_FLUSH {
376            let Ok(response) = rx.try_recv() else {
377                if yielded || !batching || !calls.any() || ws_sender.io.buffer().is_empty() {
378                    break
379                }
380                // Running calls get to queue their responses first, so that a busy connection
381                // writes many small messages with one flush instead of one each. A yield waits
382                // for the next poll of the IO driver, so it is skipped when no call is running
383                // or a large payload has already been written past the buffer. It is also
384                // skipped after one that queued nothing: a call that outlasts many others would
385                // delay each of their responses otherwise.
386                tokio::task::yield_now().await;
387                yielded = true;
388                batching = false;
389                continue
390            };
391            batching = true;
392            result = timeout(
393                write_timeout,
394                ws_sender.write_frame(OpCode::Data(Data::Text), response.as_bytes()),
395            )
396            .await;
397            written += 1;
398        }
399        if matches!(result, Ok(Ok(()))) {
400            result = timeout(write_timeout, ws_sender.io.flush()).await;
401        }
402
403        // If websocket message send fail then terminate the connection.
404        match result {
405            Ok(Ok(())) => {}
406            Ok(Err(err)) => {
407                tracing::debug!(target: LOG_TARGET, "WS send error: {}", err);
408                break;
409            }
410            Err(_) => {
411                tracing::debug!(target: LOG_TARGET, "WS send timed out after {write_timeout:?}");
412                write_timed_out = true;
413                break;
414            }
415        }
416    }
417
418    // Closing `rx` makes `MethodSink::closed` resolve, which stops the receive loop, pending calls
419    // and subscriptions of this connection. Messages still queued are dropped with this task.
420    rx.close();
421
422    // Send the close message, unless a write already timed out: the client isn't reading, so the
423    // close frame would block on the same full socket. The receive half is dropped by the
424    // connection task, which closes the socket.
425    // Use tungstenite's validated reply to a client close, or initiate a normal close.
426    if !write_timed_out {
427        let _ = timeout(write_timeout, async {
428            let close_reply = control.close_reply.lock().take();
429            let code = u16::from(CloseCode::Normal).to_be_bytes();
430            ws_sender
431                .write_frame(
432                    OpCode::Control(Control::Close),
433                    close_reply.as_deref().unwrap_or(&code),
434                )
435                .await?;
436            ws_sender.io.shutdown().await
437        })
438        .await;
439    }
440}
441
442/// Splits an upgraded connection into the halves that write and read its WebSocket frames.
443///
444/// `tungstenite` only reads: it copies every frame it writes into its write buffer, which costs a
445/// copy of each response and, when the socket takes part of a write, a move of the rest.
446pub(crate) async fn split(io: TokioIo<Upgraded>, config: WebSocketConfig) -> (Sender, Receiver) {
447    let (read, write) = tokio::io::split(io);
448    let control = Arc::new(ControlFrames::default());
449    let receiver = WebSocketStream::from_raw_socket(
450        ReadIo { read, control: control.clone() },
451        Role::Server,
452        Some(config),
453    )
454    .await;
455    (Sender { io: BufWriter::new(write), control }, receiver)
456}
457
458/// Writes the frames of a connection, which a server sends unmasked and unfragmented.
459pub(crate) struct Sender {
460    /// Collects small frames until a flush, and writes a payload larger than its buffer directly.
461    io: BufWriter<WriteHalf<TokioIo<Upgraded>>>,
462    control: Arc<ControlFrames>,
463}
464
465impl Sender {
466    /// Writes one final frame with `payload`, which isn't flushed.
467    async fn write_frame(&mut self, opcode: OpCode, payload: &[u8]) -> io::Result<()> {
468        let mut header = [0; 10];
469        header[0] = 0x80 | u8::from(opcode);
470        let len = payload.len();
471        let header_len = if len < 126 {
472            header[1] = len as u8;
473            2
474        } else if let Ok(len) = u16::try_from(len) {
475            header[1] = 126;
476            header[2..4].copy_from_slice(&len.to_be_bytes());
477            4
478        } else {
479            header[1] = 127;
480            header[2..].copy_from_slice(&(len as u64).to_be_bytes());
481            10
482        };
483        self.io.write_all(&header[..header_len]).await?;
484        self.io.write_all(payload).await
485    }
486
487    /// Writes the control frames that `tungstenite` has queued, which aren't flushed.
488    async fn write_control(&mut self) -> io::Result<()> {
489        let frames = std::mem::take(&mut *self.control.frames.lock());
490        self.io.write_all(&frames).await?;
491        self.control.written.notify_waiters();
492        Ok(())
493    }
494}
495
496impl Drop for Sender {
497    fn drop(&mut self) {
498        self.control.closed.store(true, Ordering::Release);
499        self.control.written.notify_waiters();
500    }
501}
502
503/// The read half of a connection, through which `tungstenite` also writes the replies to pings:
504/// they are handed to the [`Sender`], which writes them between messages.
505pub(crate) struct ReadIo {
506    read: ReadHalf<TokioIo<Upgraded>>,
507    control: Arc<ControlFrames>,
508}
509
510impl AsyncRead for ReadIo {
511    fn poll_read(
512        mut self: Pin<&mut Self>,
513        cx: &mut Context<'_>,
514        buf: &mut ReadBuf<'_>,
515    ) -> Poll<io::Result<()>> {
516        Pin::new(&mut self.read).poll_read(cx, buf)
517    }
518}
519
520impl AsyncWrite for ReadIo {
521    /// Takes all of `buf`, so that it always holds whole frames.
522    fn poll_write(
523        self: Pin<&mut Self>,
524        _cx: &mut Context<'_>,
525        buf: &[u8],
526    ) -> Poll<io::Result<usize>> {
527        self.control.frames.lock().extend_from_slice(buf);
528        self.control.queued.notify_one();
529        Poll::Ready(Ok(buf.len()))
530    }
531
532    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
533        Poll::Ready(Ok(()))
534    }
535
536    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
537        Poll::Ready(Ok(()))
538    }
539}
540
541/// Control frames that `tungstenite` has written while reading, which the [`Sender`] writes out.
542#[derive(Default)]
543struct ControlFrames {
544    frames: Mutex<Vec<u8>>,
545    /// Notifies the [`Sender`] that frames are queued.
546    queued: Notify,
547    /// Notifies the reader that the queued frames have been written.
548    written: Notify,
549    /// Whether the [`Sender`] has been dropped.
550    closed: AtomicBool,
551    /// The validated close reply payload; `None` means no close was received from the client.
552    /// An empty payload preserves a close without a status code.
553    close_reply: Mutex<Option<Bytes>>,
554}
555
556impl ControlFrames {
557    /// Waits until no control frame is queued, and returns `false` once the [`Sender`] is gone.
558    async fn written(&self) -> bool {
559        loop {
560            // Created before the check, so that a notification in between isn't missed.
561            let written = self.written.notified();
562            if self.closed.load(Ordering::Acquire) {
563                return false;
564            }
565            if self.frames.lock().is_empty() {
566                return true;
567            }
568            written.await;
569        }
570    }
571}
572
573/// The calls of a connection that are running, whose responses the send task may wait for.
574struct CallsInFlight {
575    permits: Arc<Semaphore>,
576    /// The permits of the semaphore, of which every running call holds one.
577    max: usize,
578}
579
580impl CallsInFlight {
581    /// Returns whether any call is running.
582    fn any(&self) -> bool {
583        self.permits.available_permits() < self.max
584    }
585}
586
587enum Receive<S> {
588    ConnectionClosed,
589    Stopped,
590    Err(tungstenite::Error, S),
591    Ok(Bytes, S),
592}
593
594/// Attempts to read data from WebSocket fails if the server was stopped.
595async fn try_recv<T, S>(ws_stream: &mut T, stopped: S) -> Receive<S>
596where
597    S: Future<Output = ()> + Unpin,
598    T: StreamExt<Item = Result<Bytes, tungstenite::Error>> + Unpin,
599{
600    // `select` polls its first argument first and returns as soon as that one is ready, so the stop
601    // signal has to come first. Polling the stream first starves it: a peer that always has another
602    // message ready never lets the read be pending, and the session would then never stop.
603    match future::select(stopped, ws_stream.next()).await {
604        // Server has been stopped.
605        Either::Left(_) => Receive::Stopped,
606        // The connection is closed.
607        Either::Right((None, _)) => Receive::ConnectionClosed,
608        // The message has been received, we are done
609        Either::Right((Some(Ok(data)), stopped)) => Receive::Ok(data, stopped),
610        // Received an error, terminate the connection.
611        Either::Right((Some(Err(e)), stopped)) => Receive::Err(e, stopped),
612    }
613}
614
615#[derive(Debug, Copy, Clone)]
616pub(crate) enum Shutdown {
617    Stopped,
618    ConnectionClosed,
619}
620
621/// Enforce a graceful shutdown.
622///
623/// This will return once the connection has been terminated or all pending calls have been
624/// executed.
625async fn graceful_shutdown<S>(
626    result: Result<Shutdown, tungstenite::Error>,
627    pending_calls: mpsc::Receiver<()>,
628    ws_stream: S,
629    mut conn_tx: oneshot::Sender<()>,
630    send_task_handle: tokio::task::JoinHandle<()>,
631) where
632    S: StreamExt<Item = Result<Bytes, tungstenite::Error>> + Unpin,
633{
634    let pending_calls = ReceiverStream::new(pending_calls);
635
636    if let Ok(Shutdown::Stopped) = result {
637        let graceful_shutdown = pending_calls.for_each(|_| async {});
638        let disconnect = ws_stream.try_for_each(|_| async { Ok(()) });
639
640        tokio::select! {
641            _ = graceful_shutdown => {}
642            res = disconnect => {
643                if let Err(err) = res {
644                    tracing::warn!(target: LOG_TARGET, "Graceful shutdown terminated because of error: `{err}`");
645                }
646            }
647            _ = conn_tx.closed() => {}
648        }
649    }
650
651    // Send a message to close down the "send task".
652    _ = conn_tx.send(());
653    // Ensure that send task has been closed.
654    _ = send_task_handle.await;
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660    use futures_util::stream;
661
662    #[tokio::test]
663    async fn try_recv_observes_stop_while_input_stays_ready() {
664        // A peer that always has another message ready must not keep the session from stopping.
665        let mut always_ready =
666            stream::repeat_with(|| Ok::<_, tungstenite::Error>(Bytes::from_static(b"{}")));
667
668        let received = try_recv(&mut always_ready, future::ready(())).await;
669        assert!(matches!(received, Receive::Stopped));
670    }
671
672    #[test]
673    fn upgrade_request_is_detected_in_header_lists() {
674        let request = |connection, upgrade| {
675            http::Request::builder()
676                .header(CONNECTION, connection)
677                .header(UPGRADE, upgrade)
678                .body(())
679                .unwrap()
680        };
681
682        assert!(is_upgrade_request(&request("Upgrade", "websocket")));
683        assert!(is_upgrade_request(&request("keep-alive, Upgrade", "h2c, WebSocket")));
684        assert!(!is_upgrade_request(&request("keep-alive", "websocket")));
685        assert!(!is_upgrade_request(&request("upgrade", "h2c")));
686        assert!(!is_upgrade_request(&http::Request::new(())));
687    }
688}