improve tracing, bundle sqlite

This commit is contained in:
41666 2023-06-09 10:43:41 -04:00
parent 5fef497bfc
commit 6b9c879ba7
4 changed files with 21 additions and 4 deletions

2
Cargo.lock generated
View file

@ -13,6 +13,7 @@ dependencies = [
"r2d2",
"r2d2_sqlite",
"reqwest",
"rusqlite",
"serde",
"serde_json",
"tokio",
@ -577,6 +578,7 @@ version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]

View file

@ -19,3 +19,4 @@ chrono = { version = "0.4", features = ["serde"] }
tower-http = { version = "0.4", features = ["trace"] }
r2d2_sqlite = "0.22"
r2d2 = "0.8"
rusqlite = { version = "0.29.0", features = ["bundled"] }

View file

@ -84,29 +84,40 @@ pub async fn get_world(
response
}
#[tracing::instrument(skip(db))]
fn world_from_cache(db: r2d2::Pool<SqliteConnectionManager>, world: i32) -> Result<Response, ()> {
let db = db.get().unwrap();
let mut query = db.prepare("SELECT data FROM worlds WHERE id = ?").unwrap();
let value: Result<Vec<u8>, _> = query.query_row(params![world], |r| r.get(0));
if value.is_err() {
tracing::debug!("Cache miss (non-exist) for world {}", world);
return Err(());
}
match bincode::deserialize::<Response>(value.unwrap().as_slice()) {
Ok(response) => {
if response.cached_at + chrono::Duration::minutes(5) < chrono::Utc::now() {
tracing::debug!("Cache miss (expired) for world {}", world);
return Err(());
}
tracing::debug!("Cache hit for world {}", world);
Ok(response)
}
_ => Err(()),
_ => {
tracing::debug!("Cache miss (corrupt) for world {}", world);
Err(())
}
}
}
#[tracing::instrument(skip(db, response))]
fn world_to_cache(db: r2d2::Pool<SqliteConnectionManager>, world: i32, response: &Response) {
let value = bincode::serialize(response).unwrap();
let db = db.get().unwrap();
let mut query = db.prepare("INSERT INTO worlds (id, data) VALUES (?, ?) ON CONFLICT DO UPDATE SET data=excluded.data").unwrap();
let mut query = db
.prepare("INSERT OR REPLACE INTO worlds (id, data) VALUES (?, ?)")
.unwrap();
query.execute(params![world, value]).unwrap();
}

View file

@ -12,7 +12,10 @@ mod types;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_env_filter("tower_http=trace")
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("tower_http=trace".parse().unwrap()),
)
.init();
let sqlite_manager = SqliteConnectionManager::memory();