use std::time::Duration;
use futures::{SinkExt, StreamExt};
use socketeer::{Bytes, EchoControlMessage, Message, WebSocketStreamType, tungstenite};
use tokio::time::timeout;
pub async fn backpressure_probe_server(
ws: WebSocketStreamType,
) -> Result<bool, tungstenite::Error> {
let (mut sink, mut stream) = ws.split();
for i in 0..5u32 {
let msg = EchoControlMessage::Message(format!("burst-{i}"));
let text = serde_json::to_string(&msg).unwrap();
sink.send(Message::Text(text.into())).await?;
}
let got_ping = timeout(Duration::from_millis(500), async {
while let Some(Ok(frame)) = stream.next().await {
if matches!(frame, Message::Ping(_)) {
return true;
}
}
false
})
.await
.unwrap_or(false);
if got_ping {
let alive = EchoControlMessage::Message("alive".to_string());
let text = serde_json::to_string(&alive).unwrap();
sink.send(Message::Text(text.into())).await?;
}
while let Some(Ok(frame)) = stream.next().await {
match frame {
Message::Ping(_) => sink.send(Message::Pong(Bytes::new())).await?,
Message::Close(_) => {
sink.close().await?;
break;
}
_ => {}
}
}
Ok(true)
}