[code][fix] improvements for LAN 202503

- more robust client <-> server connection
  - new client event: DownloadGameFilesFailed
  - 3 seconds to reconnect
  - retry forever if server is gone and never lose a UI request

- code cleanup here and there (mostly server)
This commit is contained in:
2025-03-20 19:39:32 +01:00
parent 19434cd1b1
commit 765447e6d1
9 changed files with 405 additions and 239 deletions

View File

@ -20,16 +20,29 @@ static CERT_PEM: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../..
#[derive(Debug)]
pub enum ClientEvent {
ListGames(Vec<Game>),
GotGameFiles(Vec<GameFileDescription>),
DownloadGameFilesBegin { id: String },
DownloadGameFilesFinished { id: String },
GotGameFiles {
id: String,
file_descriptions: Vec<GameFileDescription>,
},
DownloadGameFilesBegin {
id: String,
},
DownloadGameFilesFinished {
id: String,
},
DownloadGameFilesFailed {
id: String,
},
}
#[derive(Debug)]
pub enum ClientCommand {
ListGames,
GetGame(String),
DownloadGameFiles(Vec<GameFileDescription>),
DownloadGameFiles {
id: String,
file_descriptions: Vec<GameFileDescription>,
},
ServerAddr(SocketAddr),
SetGameDir(String),
}
@ -66,9 +79,39 @@ async fn initial_server_alive_check(conn: &mut Connection) -> bool {
false
}
async fn receive_game_file(
conn: &mut Connection,
desc: &GameFileDescription,
games_folder: &str,
) -> eyre::Result<()> {
log::info!("downloading: {desc:?}");
let stream = conn.open_bidirectional_stream().await?;
let (mut rx, mut tx) = stream.split();
let request = Request::GetGameFileData(desc.clone());
// request file
tx.write_all(&request.encode()).await?;
// create file
let path = PathBuf::from(&games_folder).join(&desc.relative_path);
let mut file = File::create(&path)?;
// receive file contents
while let Some(data) = rx.receive().await? {
file.write_all(&data)?;
}
log::debug!("file download complete: {}", path.display());
tx.close().await?;
Ok(())
}
async fn download_game_files(
game_id: &str,
game_file_descs: Vec<GameFileDescription>,
games_dir: String,
games_folder: String,
server_addr: SocketAddr,
tx_notify_ui: UnboundedSender<ClientEvent>,
) -> eyre::Result<()> {
@ -84,64 +127,37 @@ async fn download_game_files(
let mut conn = client.connect(conn).await?;
conn.keep_alive(true)?;
let game_file_descs = game_file_descs
.into_iter()
let game_files = game_file_descs
.iter()
.filter(|desc| !desc.is_dir)
.filter(|desc| !desc.is_version_ini())
.collect::<Vec<_>>();
if game_file_descs.is_empty() {
log::error!("game_file_descs empty: no game files to download");
return Ok(());
if game_files.is_empty() {
eyre::bail!("game_file_descs empty: no game files to download");
}
let game_id = game_file_descs
.first()
.expect("game_file_descs empty: 2nd case CANNOT HAPPEN")
.game_id
.clone();
tx_notify_ui.send(ClientEvent::DownloadGameFilesBegin {
id: game_id.clone(),
id: game_id.to_string(),
})?;
for file_desc in game_file_descs {
log::info!("downloading file: {}", file_desc.relative_path);
let stream = conn.open_bidirectional_stream().await?;
let (mut rx, mut tx) = stream.split();
let request = Request::GetGameFileData(file_desc.clone());
if let Ok(()) = tx.write_all(&request.encode()).await {
let path = PathBuf::from(&games_dir).join(&file_desc.relative_path);
let mut file = match File::create(&path) {
Ok(file) => file,
Err(e) => {
log::error!("failed to create file: {e}");
continue;
}
};
// if let Err(e) = tokio::io::copy(&mut rx, &mut file).await {
// log::error!("failed to download file: {e}");
// continue;
// }
while let Ok(Some(data)) = rx.receive().await {
if let Err(e) = file.write_all(&data) {
log::error!("failed to write to file: {e}");
break;
}
}
log::error!("file download complete: {}", path.display());
}
if let Err(e) = tx.close().await {
log::error!("failed to close stream: {e}");
}
// receive all game files
for file_desc in game_files {
receive_game_file(&mut conn, file_desc, &games_folder).await?;
}
let version_file_desc = game_file_descs
.iter()
.find(|desc| desc.is_version_ini())
.ok_or_else(|| eyre::eyre!("version.ini not found"))?;
// receive version.ini
receive_game_file(&mut conn, version_file_desc, &games_folder).await?;
log::info!("all files downloaded for game: {game_id}");
tx_notify_ui.send(ClientEvent::DownloadGameFilesFinished { id: game_id })?;
tx_notify_ui.send(ClientEvent::DownloadGameFilesFinished {
id: game_id.to_string(),
})?;
Ok(())
}
@ -171,7 +187,7 @@ pub async fn run(
loop {
let limits = Limits::default()
.with_max_handshake_duration(Duration::from_secs(3))?
.with_max_idle_timeout(Duration::ZERO)?;
.with_max_idle_timeout(Duration::from_secs(3))?;
let client = QuicClient::builder()
.with_tls(CERT_PEM)?
@ -179,8 +195,8 @@ pub async fn run(
.with_limits(limits)?
.start()?;
let conn = Connect::new(server_addr).with_server_name("localhost");
let mut conn = match client.connect(conn).await {
let connection = Connect::new(server_addr).with_server_name("localhost");
let mut conn = match client.connect(connection.clone()).await {
Ok(conn) => conn,
Err(e) => {
log::error!("failed to connect to server: {e}");
@ -206,7 +222,7 @@ pub async fn run(
let request = match cmd {
ClientCommand::ListGames => Request::ListGames,
ClientCommand::GetGame(id) => {
log::debug!("requesting game from server: {id}");
log::info!("requesting game from server: {id}");
Request::GetGame { id }
}
ClientCommand::ServerAddr(_) => {
@ -217,34 +233,73 @@ pub async fn run(
*ctx.game_dir.lock().await = Some(game_dir.clone());
continue;
}
ClientCommand::DownloadGameFiles(game_file_descs) => {
ClientCommand::DownloadGameFiles {
id,
file_descriptions,
} => {
log::info!("got ClientCommand::DownloadGameFiles");
let games_dir = { ctx.game_dir.lock().await.clone() };
if let Some(games_dir) = games_dir {
let games_folder = { ctx.game_dir.lock().await.clone() };
if let Some(games_folder) = games_folder {
let tx_notify_ui = tx_notify_ui.clone();
tokio::task::spawn(async move {
if let Err(e) = download_game_files(
game_file_descs,
games_dir,
&id,
file_descriptions,
games_folder,
server_addr,
tx_notify_ui,
tx_notify_ui.clone(),
)
.await
{
log::error!("failed to download game files: {e}");
if let Err(e) =
tx_notify_ui.send(ClientEvent::DownloadGameFilesFailed { id })
{
log::error!(
"failed to send DownloadGameFilesFailed event: {e}"
);
}
}
});
} else {
log::error!("Cannot handle game file descriptions: game_dir is not set");
log::error!(
"Cannot handle game file descriptions: games_folder is not set"
);
}
continue;
}
};
// we got a command from the UI client
// but it is possible that we lost the connection to the server
// so we check and reconnect if needed
let mut retries = 0;
loop {
if initial_server_alive_check(&mut conn).await {
log::info!("server is back alive! 😊");
break;
}
if retries == 0 {
log::warn!("server connection lost, reconnecting...");
}
retries += 1;
conn = match client.connect(connection.clone()).await {
Ok(conn) => conn,
Err(e) => {
log::warn!("failed to connect to server: {e}");
log::warn!("retrying in 3 seconds...");
tokio::time::sleep(Duration::from_secs(3)).await;
continue;
}
};
}
let data = request.encode();
log::debug!("encoded data: {}", String::from_utf8_lossy(&data));
log::trace!("encoded data: {}", String::from_utf8_lossy(&data));
let stream = match conn.open_bidirectional_stream().await {
Ok(stream) => stream,
@ -271,36 +326,43 @@ pub async fn run(
log::trace!("msg: {response:?}");
match response {
Response::Games(games) => {
Response::ListGames(games) => {
for game in &games {
log::trace!("{game}");
}
if let Err(e) = tx_notify_ui.send(ClientEvent::ListGames(games)) {
log::debug!("failed to send ClientEvent::ListGames to client {e:?}");
} else {
log::info!("sent ClientEvent::ListGames to Tauri client");
log::error!("failed to send ClientEvent::ListGames to client {e:?}");
}
}
Response::GetGame(game_file_descs) => {
Response::GetGame {
id,
file_descriptions,
} => {
log::info!(
"got {} game file descriptions from server",
game_file_descs.len()
file_descriptions.len()
);
let games_dir = { ctx.game_dir.lock().await.clone() };
let games_folder = { ctx.game_dir.lock().await.clone() };
match games_dir {
Some(games_dir) => {
game_file_descs.iter().filter(|f| f.is_dir).for_each(|dir| {
let path = PathBuf::from(&games_dir).join(&dir.relative_path);
if let Err(e) = std::fs::create_dir_all(path) {
log::error!("failed to create directory: {e}");
}
});
if let Err(e) =
tx_notify_ui.send(ClientEvent::GotGameFiles(game_file_descs))
{
match games_folder {
Some(games_folder) => {
// create all directories before receiving the actual files
file_descriptions
.iter()
.filter(|f| f.is_dir)
.for_each(|dir| {
let path =
PathBuf::from(&games_folder).join(&dir.relative_path);
if let Err(e) = std::fs::create_dir_all(path) {
log::error!("failed to create directory: {e}");
}
});
if let Err(e) = tx_notify_ui.send(ClientEvent::GotGameFiles {
id,
file_descriptions,
}) {
log::error!(
"failed to send ClientEvent::GotGameFiles to client: {e}"
);