Skip to content

Commit d37dc5d

Browse files
committed
feat(ws): add connection timeout for WebSocket connections
1 parent 4f7d3c5 commit d37dc5d

File tree

1 file changed

+23
-0
lines changed
  • apps/hermes/server/src/api

1 file changed

+23
-0
lines changed

apps/hermes/server/src/api/ws.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ use {
4545

4646
const PING_INTERVAL_DURATION: Duration = Duration::from_secs(30);
4747
const MAX_CLIENT_MESSAGE_SIZE: usize = 100 * 1024; // 100 KiB
48+
const MAX_CONNECTION_DURATION: Duration = Duration::from_secs(24 * 60 * 60); // 24 hours
4849

4950
/// The maximum number of bytes that can be sent per second per IP address.
5051
/// If the limit is exceeded, the connection is closed.
@@ -252,6 +253,7 @@ pub struct Subscriber<S> {
252253
sender: SplitSink<WebSocket, Message>,
253254
price_feeds_with_config: HashMap<PriceIdentifier, PriceFeedClientConfig>,
254255
ping_interval: tokio::time::Interval,
256+
connection_timeout: tokio::time::Sleep,
255257
exit: watch::Receiver<bool>,
256258
responded_to_ping: bool,
257259
}
@@ -280,6 +282,7 @@ where
280282
sender,
281283
price_feeds_with_config: HashMap::new(),
282284
ping_interval: tokio::time::interval(PING_INTERVAL_DURATION),
285+
connection_timeout: tokio::time::sleep(MAX_CONNECTION_DURATION),
283286
exit: crate::EXIT.subscribe(),
284287
responded_to_ping: true, // We start with true so we don't close the connection immediately
285288
}
@@ -325,6 +328,26 @@ where
325328
self.sender.send(Message::Ping(vec![])).await?;
326329
Ok(())
327330
},
331+
_ = &mut self.connection_timeout => {
332+
tracing::info!(
333+
id = self.id,
334+
ip = ?self.ip_addr,
335+
"Connection timeout reached (24h). Closing connection.",
336+
);
337+
self.sender
338+
.send(
339+
serde_json::to_string(&ServerMessage::Response(
340+
ServerResponseMessage::Err {
341+
error: "Connection timeout reached (24h)".to_string(),
342+
},
343+
))?
344+
.into(),
345+
)
346+
.await?;
347+
self.sender.close().await?;
348+
self.closed = true;
349+
return Ok(());
350+
},
328351
_ = self.exit.changed() => {
329352
self.sender.close().await?;
330353
self.closed = true;

0 commit comments

Comments
 (0)