Add WebSocket ping->pong message ticker

This commit is contained in:
Tobie Morgan Hitchcock 2022-10-19 14:56:43 +01:00
parent f0b30e9526
commit 18d69a620c
2 changed files with 24 additions and 0 deletions

View file

@ -1,4 +1,5 @@
use once_cell::sync::Lazy;
use std::time::Duration;
pub const LOGO: &str = "
.d8888b. 888 8888888b. 888888b.
@ -21,6 +22,9 @@ pub const APP_ENDPOINT: &str = "https://surrealdb.com/app";
/// How many concurrent tasks can be handled in a WebSocket
pub const MAX_CONCURRENT_CALLS: usize = 24;
/// Specifies the frequency with which ping messages should be sent to the client.
pub const WEBSOCKET_PING_FREQUENCY: Duration = Duration::from_secs(5);
/// The package identifier of this build
pub const PKG_NAME: &str = env!("CARGO_PKG_NAME");

View file

@ -2,6 +2,7 @@ use crate::cli::CF;
use crate::cnf::MAX_CONCURRENT_CALLS;
use crate::cnf::PKG_NAME;
use crate::cnf::PKG_VERS;
use crate::cnf::WEBSOCKET_PING_FREQUENCY;
use crate::dbs::DB;
use crate::err::Error;
use crate::net::session;
@ -61,6 +62,25 @@ impl Rpc {
let (chn, mut rcv) = channel::new(MAX_CONCURRENT_CALLS);
// Split the socket into send and recv
let (mut wtx, mut wrx) = ws.split();
// Clone the channel for sending pings
let png = chn.clone();
// Send messages to the client
tokio::task::spawn(async move {
// Create the interval ticker
let mut interval = tokio::time::interval(WEBSOCKET_PING_FREQUENCY);
// Loop indefinitely
loop {
// Wait for the timer
interval.tick().await;
// Create the ping message
let msg = Message::ping(vec![]);
// Send the message to the client
if let Err(_) = png.send(msg).await {
// Exit out of the loop
break;
}
}
});
// Send messages to the client
tokio::task::spawn(async move {
// Wait for the next message to send