Implement message timeouts

This commit is contained in:
htrefil 2020-10-30 18:01:04 +01:00
parent 54c32d4c80
commit b18d0282e4
3 changed files with 8 additions and 3 deletions

View file

@ -12,6 +12,7 @@ use structopt::StructOpt;
use tokio::fs;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::time;
use tokio_native_tls::native_tls::{Certificate, TlsConnector};
async fn run(server: &str, port: u16, certificate_path: &Path) -> Result<Infallible, Error> {
@ -50,7 +51,9 @@ async fn run(server: &str, port: u16, certificate_path: &Path) -> Result<Infalli
let mut writer = EventWriter::new().await?;
loop {
let message = net::read_message(&mut stream).await?;
let message = time::timeout(net::MESSAGE_TIMEOUT, net::read_message(&mut stream))
.await
.context("Read timed out")??;
match message {
Message::Event(event) => writer.write(event).await?,
Message::KeepAlive => {}

View file

@ -2,10 +2,12 @@ use input::Event;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::io::{Error, ErrorKind};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
// Is it bold to assume there won't be more than 65536 protocol versions?
pub const PROTOCOL_VERSION: u16 = 0;
pub const MESSAGE_TIMEOUT: Duration = Duration::from_secs(5);
pub async fn read_version<R>(mut reader: R) -> Result<u16, Error>
where

View file

@ -10,7 +10,6 @@ use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process;
use std::time::Duration;
use structopt::StructOpt;
use tokio::fs;
use tokio::io::{AsyncRead, AsyncWrite};
@ -38,7 +37,8 @@ where
}
loop {
let message = match time::timeout(Duration::from_secs(10), receiver.recv()).await {
// Sent a keep alive message in intervals of half of the timeout just to be on the safe side.
let message = match time::timeout(net::MESSAGE_TIMEOUT / 2, receiver.recv()).await {
Ok(Some(message)) => Message::Event(message),
Ok(None) => return Ok(()),
Err(_) => Message::KeepAlive,