From 315a05d59a7c61fbf0b3f37c5eb97bf1e4bb8f33 Mon Sep 17 00:00:00 2001 From: Katalina Okano Date: Fri, 9 Jun 2023 07:52:19 -0400 Subject: [PATCH] background refresh --- src/handlers.rs | 14 ++++++++------ src/main.rs | 18 ++++++++++++++++-- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/handlers.rs b/src/handlers.rs index 7e1ba0c..28aa895 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -9,7 +9,7 @@ use axum::{ use tokio::task::JoinSet; pub async fn get_one_world(State(db): State, Path(world): Path) -> Json { - Json(get_world(db, world).await) + Json(get_world(db, world, false).await) } pub async fn get_all_worlds(State(db): State) -> Json> { @@ -17,7 +17,7 @@ pub async fn get_all_worlds(State(db): State) -> Json> { let mut worlds = vec![Response::default(); 8]; for world in vec![1, 10, 13, 17, 19, 40, 1000, 2000] { - set.spawn(get_world(db.clone(), world)); + set.spawn(get_world(db.clone(), world, false)); } let mut i = 0; @@ -29,9 +29,11 @@ pub async fn get_all_worlds(State(db): State) -> Json> { Json(worlds) } -async fn get_world(db: sled::Db, world: i32) -> Response { - if let Ok(data) = world_from_cache(db.clone(), world) { - return data; +pub async fn get_world(db: sled::Db, world: i32, skip_cache: bool) -> Response { + if !skip_cache { + if let Ok(data) = world_from_cache(db.clone(), world) { + return data; + } } let mut response = Response::default(); @@ -81,7 +83,7 @@ fn world_from_cache(db: sled::Db, world: i32) -> Result { match bincode::deserialize::(&value) { Ok(response) => { - if response.cached_at + chrono::Duration::minutes(3) < chrono::Utc::now() { + if response.cached_at + chrono::Duration::minutes(5) < chrono::Utc::now() { return Err(()); } Ok(response) diff --git a/src/main.rs b/src/main.rs index 535dd13..f906399 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ -use crate::handlers::{get_all_worlds, get_one_world}; +use crate::handlers::{get_all_worlds, get_one_world, get_world}; use axum::{response::Html, routing::get, Router}; use std::net::SocketAddr; +use tokio::task::JoinSet; use tower_http::trace::TraceLayer; mod handlers; @@ -21,7 +22,20 @@ async fn main() { .route("/population/all", get(get_all_worlds)) .route("/population/:world", get(get_one_world)) .layer(TraceLayer::new_for_http()) - .with_state(db); + .with_state(db.clone()); + + tokio::spawn(async move { + loop { + let mut set = JoinSet::new(); + for world in vec![1, 10, 13, 17, 19, 40, 1000, 2000] { + set.spawn(get_world(db.clone(), world, true)); + } + + while let Some(_) = set.join_next().await {} + + tokio::time::sleep(tokio::time::Duration::from_secs(60 * 3)).await; + } + }); let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); tracing::debug!("listening on {}", addr);