refactor: more flexible cached scrape

This commit is contained in:
mokurin000
2025-08-03 12:06:07 +08:00
parent a60e65e110
commit 7e4dc9b978

View File

@@ -9,12 +9,12 @@ use redb::TableDefinition;
use serde::Serialize; use serde::Serialize;
use spdlog::{error, info}; use spdlog::{error, info};
use sdgb_api::bincode; use sdgb_api::title::MaiVersionExt;
use sdgb_api::title::MaiVersionExt as _;
use sdgb_api::title::{ use sdgb_api::title::{
Sdgb1_50, Sdgb1_50,
methods::{APIExt, HasUid}, methods::{APIExt, HasUid},
}; };
use sdgb_api::{ApiError, bincode};
use bincode::{BorrowDecode, Encode, borrow_decode_from_slice}; use bincode::{BorrowDecode, Encode, borrow_decode_from_slice};
@@ -88,6 +88,28 @@ pub async fn cached_concurrent_fetch<A: APIExt>(
where where
A::Payload: From<u32>, A::Payload: From<u32>,
A::Response: Encode + for<'a> BorrowDecode<'a, ()> + HasUid, A::Response: Encode + for<'a> BorrowDecode<'a, ()> + HasUid,
{
cached_concurrent_fetch_userfn(
user_ids,
client,
concurrency,
definition,
async |client, user_id| {
Sdgb1_50::request_ext::<A>(client, A::Payload::from(user_id), user_id).await
},
)
.await
}
pub async fn cached_concurrent_fetch_userfn<R>(
user_ids: impl Into<Vec<u32>>,
client: &AsyncClient,
concurrency: usize,
definition: TableDefinition<'_, u32, Vec<u8>>,
scrape: impl AsyncFn(&AsyncClient, u32) -> Result<R, ApiError>,
) -> Result<(), Box<dyn snafu::Error>>
where
R: Encode + for<'a> BorrowDecode<'a, ()> + HasUid,
{ {
let _ = cache::init_db(); let _ = cache::init_db();
@@ -107,8 +129,7 @@ where
let cache_table = cache::open_table_ro(&read, definition)?; let cache_table = cache::open_table_ro(&read, definition)?;
let data = cache_table.get(user_id)?; let data = cache_table.get(user_id)?;
if let Some(data) = data { if let Some(data) = data {
let decoded: (A::Response, _) = let decoded: (R, _) = borrow_decode_from_slice(&data.value(), config)?;
borrow_decode_from_slice(&data.value(), config)?;
return Ok(decoded.0); return Ok(decoded.0);
} }
@@ -118,9 +139,7 @@ where
return Err("early skip due to ctrl-c")?; return Err("early skip due to ctrl-c")?;
} }
let resp = let resp = scrape(&client, user_id).await;
Sdgb1_50::request_ext::<A>(&client, <A as APIExt>::Payload::from(user_id), user_id)
.await;
match &resp { match &resp {
Ok(resp) => { Ok(resp) => {