@@ -25,7 +25,7 @@ use bytes::Bytes;
2525use futures_util::{SinkExt, StreamExt};
2626use nostr::{EventBuilder, Kind, Tag};
2727use serde::Deserialize;
28- use tokio::sync::mpsc;
28+ use tokio::sync::{ mpsc, OwnedSemaphorePermit, Semaphore} ;
2929use tokio_util::sync::CancellationToken;
3030use tracing::{debug, error, info, warn};
3131use uuid::Uuid;
@@ -46,6 +46,11 @@ const MAX_AUDIO_FRAME_BYTES: usize = 4096;
4646/// Maximum text frame size: 8 KB bounds auth/control JSON parsing.
4747const MAX_TEXT_FRAME_BYTES: usize = 8192;
4848
49+ /// Parser-level cap for this route. Text auth/control frames are the largest
50+ /// message type audio accepts; binary Opus frames are bounded more tightly
51+ /// after parsing.
52+ const MAX_WEBSOCKET_MESSAGE_BYTES: usize = MAX_TEXT_FRAME_BYTES;
53+
4954/// Heartbeat interval.
5055const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
5156
@@ -81,7 +86,36 @@ pub async fn ws_audio_handler(
8186 .into_response();
8287 }
8388 };
84- ws.on_upgrade(move |socket| handle_audio_connection(socket, state, tenant, channel_id))
89+
90+ let permit = match acquire_audio_connection_permit(&state.conn_semaphore) {
91+ Some(permit) => permit,
92+ None => {
93+ warn!(channel_id = %channel_id, "Connection limit reached, rejecting audio WebSocket");
94+ return (
95+ StatusCode::SERVICE_UNAVAILABLE,
96+ "relay: connection limit reached",
97+ )
98+ .into_response();
99+ }
100+ };
101+
102+ // Keep the parser boundary at the largest message this route accepts. The
103+ // checks in the receive loop still distinguish text from binary policy, but
104+ // they run after tungstenite has assembled a message.
105+ limit_audio_websocket(ws).on_upgrade(move |socket| {
106+ handle_audio_connection(socket, state, tenant, channel_id, permit)
107+ })
108+ }
109+
110+ fn acquire_audio_connection_permit(
111+ conn_semaphore: &Arc<Semaphore>,
112+ ) -> Option<OwnedSemaphorePermit> {
113+ Arc::clone(conn_semaphore).try_acquire_owned().ok()
114+ }
115+
116+ fn limit_audio_websocket<F>(ws: WebSocketUpgrade<F>) -> WebSocketUpgrade<F> {
117+ ws.max_message_size(MAX_WEBSOCKET_MESSAGE_BYTES)
118+ .max_frame_size(MAX_WEBSOCKET_MESSAGE_BYTES)
85119}
86120
87121/// Highest huddle audio protocol version this relay understands. Clients are
@@ -112,6 +146,7 @@ async fn handle_audio_connection(
112146 state: Arc<AppState>,
113147 tenant: TenantContext,
114148 channel_id: Uuid,
149+ _permit: OwnedSemaphorePermit,
115150) {
116151 let cancel = CancellationToken::new();
117152 let community_id = tenant.community();
@@ -1299,3 +1334,97 @@ async fn emit_participant_event(
12991334 );
13001335 }
13011336}
1337+
1338+ #[cfg(test)]
1339+ mod tests {
1340+ use std::sync::Mutex;
1341+
1342+ use axum::{routing::get, Router};
1343+ use futures_util::SinkExt;
1344+ use tokio::net::TcpListener;
1345+ use tokio::sync::oneshot;
1346+ use tokio_tungstenite::{connect_async, tungstenite::Message};
1347+
1348+ use super::*;
1349+
1350+ #[test]
1351+ fn audio_connection_permits_share_the_global_websocket_budget() {
1352+ let semaphore = Arc::new(Semaphore::new(1));
1353+ let first = acquire_audio_connection_permit(&semaphore).expect("first permit");
1354+
1355+ assert!(
1356+ acquire_audio_connection_permit(&semaphore).is_none(),
1357+ "audio connections must stop when the global WebSocket budget is exhausted"
1358+ );
1359+
1360+ drop(first);
1361+ assert!(
1362+ acquire_audio_connection_permit(&semaphore).is_some(),
1363+ "dropping an audio connection must return its global permit"
1364+ );
1365+ }
1366+
1367+ async fn handler_receives_message_of_size(size: usize) -> bool {
1368+ let (received_tx, received_rx) = oneshot::channel();
1369+ let received_tx = Arc::new(Mutex::new(Some(received_tx)));
1370+ let app = Router::new().route(
1371+ "/",
1372+ get({
1373+ let received_tx = Arc::clone(&received_tx);
1374+ move |ws: WebSocketUpgrade| {
1375+ let received_tx = Arc::clone(&received_tx);
1376+ async move {
1377+ limit_audio_websocket(ws).on_upgrade(move |mut socket| async move {
1378+ let received = matches!(socket.recv().await, Some(Ok(_)));
1379+ if let Some(tx) =
1380+ received_tx.lock().expect("result lock poisoned").take()
1381+ {
1382+ let _ = tx.send(received);
1383+ }
1384+ })
1385+ }
1386+ }
1387+ }),
1388+ );
1389+
1390+ let listener = TcpListener::bind("127.0.0.1:0")
1391+ .await
1392+ .expect("bind test WebSocket listener");
1393+ let addr = listener.local_addr().expect("test listener address");
1394+ let server = tokio::spawn(async move {
1395+ axum::serve(listener, app)
1396+ .await
1397+ .expect("test WebSocket server");
1398+ });
1399+
1400+ let (mut client, _) = connect_async(format!("ws://{addr}/"))
1401+ .await
1402+ .expect("connect test WebSocket client");
1403+ client
1404+ .send(Message::Text("x".repeat(size).into()))
1405+ .await
1406+ .expect("send test WebSocket message");
1407+
1408+ let received = tokio::time::timeout(Duration::from_secs(2), received_rx)
1409+ .await
1410+ .expect("server should process the test message")
1411+ .expect("server should report whether it received the message");
1412+
1413+ server.abort();
1414+ let _ = server.await;
1415+
1416+ received
1417+ }
1418+
1419+ #[tokio::test]
1420+ async fn audio_websocket_parser_rejects_oversized_messages_before_handler_reads_them() {
1421+ assert!(
1422+ handler_receives_message_of_size(MAX_WEBSOCKET_MESSAGE_BYTES).await,
1423+ "messages at the audio route limit should still reach the handler"
1424+ );
1425+ assert!(
1426+ !handler_receives_message_of_size(MAX_WEBSOCKET_MESSAGE_BYTES + 1).await,
1427+ "oversized messages must be rejected by the WebSocket parser before the handler sees them"
1428+ );
1429+ }
1430+ }
0 commit comments