implemented working cache

some testing still has to be done
This commit is contained in:
2025-03-16 02:56:54 -04:00
parent 328dacb675
commit d126fed2bd
5 changed files with 457 additions and 71 deletions

View File

@ -1,7 +1,7 @@
use std::collections::HashMap;
use crate::utils::rss;
use crate::{datasources::posts::PostsDatasource, AppState};
use crate::{datasources::posts::PostsDatasource, state::AppState};
use axum::http::{HeaderMap, HeaderValue};
use axum::{
extract::{Path, State},
@ -11,10 +11,11 @@ use axum::{
Json, Router,
};
use chrono::Utc;
use serde::{Deserialize, Serialize, Serializer};
use sqlx::{Pool, Postgres};
use fred::types::Expiration;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
#[derive(sqlx::FromRow, Serialize, Debug, Clone)]
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
@ -23,10 +24,11 @@ pub struct Post {
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
}
#[derive(sqlx::FromRow, Serialize, Debug)]
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
pub struct PostFeaturedVariant {
pub post_id: i32,
pub author_id: Option<i32>,
@ -35,6 +37,7 @@ pub struct PostFeaturedVariant {
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
#[serde(deserialize_with = "deserialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
pub is_featured: Option<bool>,
}
@ -56,63 +59,275 @@ impl PostsRoute {
.route("/hot", get(PostsRoute::get_hot_posts))
.route("/featured", get(PostsRoute::get_featured_posts))
.route("/rss", get(PostsRoute::get_rss_posts))
.with_state(app_state.db.clone())
.with_state(app_state.clone())
}
// get all posts
async fn get_all(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_all(&pool).await {
Ok(posts) => Ok(Json(posts)),
async fn get_all(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:all"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing all posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing all posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:all"),
&posts,
Some(Expiration::EX(10)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get one post
async fn get_one(
State(pool): State<Pool<Postgres>>,
State(app_state): State<AppState>,
Path(params): Path<PostGetOneParams>,
) -> impl IntoResponse {
match PostsDatasource::get_one(&pool, params.id).await {
Ok(post) => Ok(Json(post)),
let mut state = app_state.lock().await;
let cached: Option<PostFeaturedVariant> = state
.cache
.get(format!("posts:{}", params.id))
.await
.unwrap_or(None);
if let Some(post) = cached {
tracing::info!("grabbing one post from cache");
return Ok(Json(post));
};
match PostsDatasource::get_one(&state.database, params.id).await {
Ok(post) => {
tracing::info!("grabbing one post from database");
if let p = &post {
let post = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
format!("posts:{}", params.id),
&post,
Some(Expiration::EX(10)),
None,
false,
)
.await;
});
};
Ok(Json(post))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get recent posts
async fn get_recent_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_recent(&pool).await {
Ok(posts) => Ok(Json(posts)),
async fn get_recent_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:recent"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing recent posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_recent(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing recent posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:recent"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the highest view count
async fn get_popular_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_popular(&pool).await {
Ok(posts) => Ok(Json(posts)),
async fn get_popular_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:popular"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing popular posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_popular(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing popular posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:popular"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the most comments
async fn get_hot_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_hot(&pool).await {
Ok(posts) => Ok(Json(posts)),
async fn get_hot_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:hot"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing hot posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_hot(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing hot posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:hot"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get posts that are featured
async fn get_featured_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_featured(&pool).await {
Ok(posts) => Ok(Json(posts)),
async fn get_featured_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let mut state = app_state.lock().await;
let cached: Option<Vec<Post>> = state
.cache
.get(String::from("posts:featured"))
.await
.unwrap_or(None);
if let Some(posts) = cached {
tracing::info!("grabbing featured posts from cache");
return Ok(Json(posts));
};
match PostsDatasource::get_featured(&state.database).await {
Ok(posts) => {
tracing::info!("grabbing featured posts from database");
if let p = &posts {
let posts = p.clone();
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
.cache
.set(
String::from("posts:featured"),
&posts,
Some(Expiration::EX(5)),
None,
false,
)
.await;
});
};
Ok(Json(posts))
}
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get rss posts
async fn get_rss_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_all(&pool).await {
async fn get_rss_posts(State(app_state): State<AppState>) -> impl IntoResponse {
let state = app_state.lock().await;
match PostsDatasource::get_all(&state.database).await {
Ok(posts) => {
let web_url = std::env::var("BASE_URI_WEB").expect("No environment variable found");
let mapped_posts: HashMap<String, Post> = posts
@ -154,3 +369,46 @@ where
{
serializer.serialize_str(&date.unwrap().to_rfc3339())
}
pub fn deserialize_datetime<'de, D>(
deserializer: D,
) -> Result<Option<chrono::DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
struct DateTimeVisitor;
impl<'de> serde::de::Visitor<'de> for DateTimeVisitor {
type Value = Option<chrono::DateTime<Utc>>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an ISO 8601 formatted date string or null")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match chrono::DateTime::parse_from_rfc3339(value) {
Ok(dt) => Ok(Some(dt.with_timezone(&Utc))),
Err(e) => Err(E::custom(format!("Failed to parse datetime: {}", e))),
}
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(None)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(self)
}
}
deserializer.deserialize_option(DateTimeVisitor)
}