2025-03-15 17:27:32 -04:00
|
|
|
use fred::interfaces::KeysInterface;
|
|
|
|
use fred::{clients::Pool, prelude::*};
|
|
|
|
use sqlx::PgPool;
|
|
|
|
|
|
|
|
pub type AppState = std::sync::Arc<tokio::sync::Mutex<AppInternalState>>;
|
|
|
|
|
|
|
|
pub struct AppInternalState {
|
|
|
|
pub database: sqlx::postgres::PgPool,
|
|
|
|
pub cache: Cache,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Cache {
|
|
|
|
pub inmem: Pool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AppInternalState {
|
|
|
|
pub fn new(database: PgPool, cache: Pool) -> Self {
|
|
|
|
AppInternalState {
|
|
|
|
database,
|
|
|
|
cache: Cache { inmem: cache },
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Cache {
|
|
|
|
pub async fn get<T>(&mut self, key: String) -> Result<Option<T>, Box<dyn std::error::Error>>
|
|
|
|
where
|
|
|
|
T: for<'de> serde::Deserialize<'de>,
|
|
|
|
{
|
|
|
|
if !self.inmem.is_connected() {
|
2025-03-16 02:56:54 -04:00
|
|
|
return Err(Box::new(std::io::Error::new(
|
|
|
|
std::io::ErrorKind::Other,
|
|
|
|
"Not connected to cache".to_string(),
|
|
|
|
)));
|
2025-03-15 17:27:32 -04:00
|
|
|
}
|
|
|
|
|
2025-03-16 02:56:54 -04:00
|
|
|
let value: Option<String> = self.inmem.get(&key).await?;
|
2025-03-15 17:27:32 -04:00
|
|
|
|
2025-03-16 02:56:54 -04:00
|
|
|
match value {
|
|
|
|
Some(json_str) => match serde_json::from_str::<T>(&json_str) {
|
|
|
|
Ok(deserialized) => Ok(Some(deserialized)),
|
|
|
|
Err(_) => Ok(None),
|
2025-03-15 17:27:32 -04:00
|
|
|
},
|
2025-03-16 02:56:54 -04:00
|
|
|
None => Ok(None),
|
|
|
|
}
|
2025-03-15 17:27:32 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn set<T>(
|
|
|
|
&mut self,
|
|
|
|
key: String,
|
|
|
|
contents: &T,
|
|
|
|
expiration: Option<Expiration>,
|
|
|
|
set_opts: Option<SetOptions>,
|
|
|
|
get: bool,
|
|
|
|
) -> Result<(), Box<dyn std::error::Error>>
|
|
|
|
where
|
2025-03-16 02:56:54 -04:00
|
|
|
T: for<'de> serde::Deserialize<'de> + serde::Serialize,
|
2025-03-15 17:27:32 -04:00
|
|
|
{
|
|
|
|
if !self.inmem.is_connected() {
|
2025-03-16 02:56:54 -04:00
|
|
|
return Err(Box::new(std::io::Error::new(
|
|
|
|
std::io::ErrorKind::Other,
|
|
|
|
"Not connected to cache".to_string(),
|
|
|
|
)));
|
2025-03-15 17:27:32 -04:00
|
|
|
}
|
|
|
|
|
2025-03-16 02:56:54 -04:00
|
|
|
let json_string = serde_json::to_string(contents)?;
|
2025-03-15 17:27:32 -04:00
|
|
|
self.inmem
|
2025-03-16 02:56:54 -04:00
|
|
|
.set(key, json_string, expiration, set_opts, get)
|
2025-03-15 17:27:32 -04:00
|
|
|
.await?;
|
2025-03-16 02:56:54 -04:00
|
|
|
|
2025-03-15 17:27:32 -04:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn del(&mut self, key: String) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
self.inmem.del(key).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|