From 42bdf98d8fe812c9b674792916b1b0786b83880f Mon Sep 17 00:00:00 2001 From: Lena Date: Sun, 15 Dec 2024 23:01:32 +0100 Subject: [PATCH] breaking: update tokio-tungstenite to 0.25 and update examples --- axum/Cargo.toml | 2 +- axum/src/extract/ws.rs | 26 ++++++++++++------------- examples/chat/src/main.rs | 6 +++--- examples/testing-websockets/src/main.rs | 8 ++++---- examples/websockets-http2/src/main.rs | 4 ++-- examples/websockets/src/main.rs | 6 +++--- 6 files changed, 26 insertions(+), 26 deletions(-) diff --git a/axum/Cargo.toml b/axum/Cargo.toml index 043aa606092..a978bc7682e 100644 --- a/axum/Cargo.toml +++ b/axum/Cargo.toml @@ -76,7 +76,7 @@ serde_path_to_error = { version = "0.1.8", optional = true } serde_urlencoded = { version = "0.7", optional = true } sha1 = { version = "0.10", optional = true } tokio = { package = "tokio", version = "1.25.0", features = ["time"], optional = true } -tokio-tungstenite = { version = "0.24.0", optional = true } +tokio-tungstenite = { version = "0.25.0", optional = true } tracing = { version = "0.1", default-features = false, optional = true } [dependencies.tower-http] diff --git a/axum/src/extract/ws.rs b/axum/src/extract/ws.rs index fa06d249ad3..cf44596f303 100644 --- a/axum/src/extract/ws.rs +++ b/axum/src/extract/ws.rs @@ -114,7 +114,7 @@ use std::{ use tokio_tungstenite::{ tungstenite::{ self as ts, - protocol::{self, WebSocketConfig}, + protocol::{self, frame::{Payload, Utf8Payload}, WebSocketConfig}, }, WebSocketStream, }; @@ -591,16 +591,16 @@ pub struct CloseFrame<'t> { #[derive(Debug, Eq, PartialEq, Clone)] pub enum Message { /// A text WebSocket message - Text(String), + Text(Utf8Payload), /// A binary WebSocket message - Binary(Vec), + Binary(Payload), /// A ping message with the specified payload /// /// The payload here must have a length less than 125 bytes. /// /// Ping messages will be automatically responded to by the server, so you do not have to worry /// about dealing with them yourself. - Ping(Vec), + Ping(Payload), /// A pong message with the specified payload /// /// The payload here must have a length less than 125 bytes. @@ -608,7 +608,7 @@ pub enum Message { /// Pong messages will be automatically sent to the client if a ping message is received, so /// you do not have to worry about constructing them yourself unless you want to implement a /// [unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3). - Pong(Vec), + Pong(Payload), /// A close message with the optional close frame. /// /// You may "uncleanly" close a WebSocket connection at any time @@ -666,8 +666,8 @@ impl Message { /// Consume the WebSocket and return it as binary data. pub fn into_data(self) -> Vec { match self { - Self::Text(string) => string.into_bytes(), - Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data, + Self::Text(string) => string.to_string().into_bytes(), + Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data.as_slice().to_vec(), Self::Close(None) => Vec::new(), Self::Close(Some(frame)) => frame.reason.into_owned().into_bytes(), } @@ -676,8 +676,8 @@ impl Message { /// Attempt to consume the WebSocket message and convert it to a String. pub fn into_text(self) -> Result { match self { - Self::Text(string) => Ok(string), - Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data) + Self::Text(string) => Ok(string.to_string()), + Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data.as_slice().to_vec()) .map_err(|err| err.utf8_error()) .map_err(Error::new)?), Self::Close(None) => Ok(String::new()), @@ -689,9 +689,9 @@ impl Message { /// this will try to convert binary data to utf8. pub fn to_text(&self) -> Result<&str, Error> { match *self { - Self::Text(ref string) => Ok(string), + Self::Text(ref string) => Ok(string.as_str()), Self::Binary(ref data) | Self::Ping(ref data) | Self::Pong(ref data) => { - Ok(std::str::from_utf8(data).map_err(Error::new)?) + Ok(std::str::from_utf8(data.as_slice()).map_err(Error::new)?) } Self::Close(None) => Ok(""), Self::Close(Some(ref frame)) => Ok(&frame.reason), @@ -701,7 +701,7 @@ impl Message { impl From for Message { fn from(string: String) -> Self { - Message::Text(string) + Message::Text(string.into()) } } @@ -719,7 +719,7 @@ impl<'b> From<&'b [u8]> for Message { impl From> for Message { fn from(data: Vec) -> Self { - Message::Binary(data) + Message::Binary(data.into()) } } diff --git a/examples/chat/src/main.rs b/examples/chat/src/main.rs index 77baada1b58..f5f742602ba 100644 --- a/examples/chat/src/main.rs +++ b/examples/chat/src/main.rs @@ -79,7 +79,7 @@ async fn websocket(stream: WebSocket, state: Arc) { while let Some(Ok(message)) = receiver.next().await { if let Message::Text(name) = message { // If username that is sent by client is not taken, fill username string. - check_username(&state, &mut username, &name); + check_username(&state, &mut username, name.as_str()); // If not empty we want to quit the loop else we want to quit function. if !username.is_empty() { @@ -87,7 +87,7 @@ async fn websocket(stream: WebSocket, state: Arc) { } else { // Only send our client that username is taken. let _ = sender - .send(Message::Text(String::from("Username already taken."))) + .send(Message::Text("Username already taken.".into())) .await; return; @@ -109,7 +109,7 @@ async fn websocket(stream: WebSocket, state: Arc) { let mut send_task = tokio::spawn(async move { while let Ok(msg) = rx.recv().await { // In any websocket error, break loop. - if sender.send(Message::Text(msg)).await.is_err() { + if sender.send(Message::Text(msg.into())).await.is_err() { break; } } diff --git a/examples/testing-websockets/src/main.rs b/examples/testing-websockets/src/main.rs index 384be35d536..2f9a71b902b 100644 --- a/examples/testing-websockets/src/main.rs +++ b/examples/testing-websockets/src/main.rs @@ -48,7 +48,7 @@ async fn integration_testable_handle_socket(mut socket: WebSocket) { while let Some(Ok(msg)) = socket.recv().await { if let Message::Text(msg) = msg { if socket - .send(Message::Text(format!("You said: {msg}"))) + .send(Message::Text(format!("You said: {msg}").into())) .await .is_err() { @@ -79,7 +79,7 @@ where while let Some(Ok(msg)) = read.next().await { if let Message::Text(msg) = msg { if write - .send(Message::Text(format!("You said: {msg}"))) + .send(Message::Text(format!("You said: {msg}").into())) .await .is_err() { @@ -137,7 +137,7 @@ mod tests { tokio::spawn(unit_testable_handle_socket(socket_write, socket_read)); test_tx - .send(Ok(Message::Text("foo".to_owned()))) + .send(Ok(Message::Text("foo".into()))) .await .unwrap(); @@ -146,6 +146,6 @@ mod tests { other => panic!("expected a text message but got {other:?}"), }; - assert_eq!(msg, "You said: foo"); + assert_eq!(msg.as_str(), "You said: foo"); } } diff --git a/examples/websockets-http2/src/main.rs b/examples/websockets-http2/src/main.rs index dbc682c4d9d..f3f33aacacf 100644 --- a/examples/websockets-http2/src/main.rs +++ b/examples/websockets-http2/src/main.rs @@ -75,7 +75,7 @@ async fn ws_handler( res = ws.recv() => { match res { Some(Ok(ws::Message::Text(s))) => { - let _ = sender.send(s); + let _ = sender.send(s.to_string()); } Some(Ok(_)) => {} Some(Err(e)) => tracing::debug!("client disconnected abruptly: {e}"), @@ -85,7 +85,7 @@ async fn ws_handler( // Tokio guarantees that `broadcast::Receiver::recv` is cancel-safe. res = receiver.recv() => { match res { - Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg)).await { + Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg.into())).await { tracing::debug!("client disconnected abruptly: {e}"); } Err(_) => continue, diff --git a/examples/websockets/src/main.rs b/examples/websockets/src/main.rs index 7c4a9801af7..5f487ebcab9 100644 --- a/examples/websockets/src/main.rs +++ b/examples/websockets/src/main.rs @@ -101,7 +101,7 @@ async fn ws_handler( /// Actual websocket statemachine (one will be spawned per connection) async fn handle_socket(mut socket: WebSocket, who: SocketAddr) { // send a ping (unsupported by some browsers) just to kick things off and get a response - if socket.send(Message::Ping(vec![1, 2, 3])).await.is_ok() { + if socket.send(Message::Ping(vec![1, 2, 3].into())).await.is_ok() { println!("Pinged {who}..."); } else { println!("Could not send ping {who}!"); @@ -131,7 +131,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) { // connecting to server and receiving their greetings. for i in 1..5 { if socket - .send(Message::Text(format!("Hi {i} times!"))) + .send(Message::Text(format!("Hi {i} times!").into())) .await .is_err() { @@ -151,7 +151,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) { for i in 0..n_msg { // In case of any websocket error, we exit. if sender - .send(Message::Text(format!("Server message {i} ..."))) + .send(Message::Text(format!("Server message {i} ...").into())) .await .is_err() {