cargo fmt

This commit is contained in:
Gabriel Simmer 2023-10-02 15:33:19 +01:00
parent 8a52d12891
commit d14bfda77e
Signed by: arch
SSH key fingerprint: SHA256:m3OEcdtrnBpMX+2BDGh/byv3hrCekCLzDYMdvGEKPPQ
5 changed files with 70 additions and 44 deletions

12
src/cache/memory.rs vendored
View file

@ -3,7 +3,7 @@ use std::collections::HashMap;
use async_trait::async_trait; use async_trait::async_trait;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use super::{CacheMechanism, CachedItem, should_use, Tier}; use super::{should_use, CacheMechanism, CachedItem, Tier};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Memory {} pub struct Memory {}
@ -13,7 +13,7 @@ lazy_static! {
} }
pub fn new() -> Memory { pub fn new() -> Memory {
return Memory{}; return Memory {};
} }
#[async_trait] #[async_trait]
@ -26,9 +26,11 @@ impl CacheMechanism for Memory {
let mut r = c.clone(); let mut r = c.clone();
r.tier = Some(Tier::Memory); r.tier = Some(Tier::Memory);
Some(r) Some(r)
} else { None } } else {
}, None
None => None }
}
None => None,
} }
} }

36
src/cache/mod.rs vendored
View file

@ -1,9 +1,12 @@
mod memory; mod memory;
mod sqlite; mod sqlite;
use std::{time::{SystemTime, UNIX_EPOCH}, fmt};
use async_trait::async_trait; use async_trait::async_trait;
use sqlx::FromRow; use sqlx::FromRow;
use std::{
fmt,
time::{SystemTime, UNIX_EPOCH},
};
use self::{memory::Memory, sqlite::Sqlite}; use self::{memory::Memory, sqlite::Sqlite};
@ -14,7 +17,10 @@ pub struct Cache {
} }
pub async fn init_cache() -> Cache { pub async fn init_cache() -> Cache {
Cache{ memory: memory::new(), sqlite: sqlite::new().await } Cache {
memory: memory::new(),
sqlite: sqlite::new().await,
}
} }
/// Tier enums take an i64, which is the amount of time in seconds /// Tier enums take an i64, which is the amount of time in seconds
@ -24,7 +30,7 @@ pub enum Tier {
Memory, Memory,
Sqlite, Sqlite,
External, External,
None None,
} }
impl fmt::Display for Tier { impl fmt::Display for Tier {
@ -44,7 +50,7 @@ pub struct CachedItem {
pub content: String, pub content: String,
cached: i64, cached: i64,
#[sqlx(default)] #[sqlx(default)]
tier: Option<Tier> tier: Option<Tier>,
} }
impl CachedItem { impl CachedItem {
@ -68,7 +74,8 @@ impl Cache {
} }
if self.sqlite.is_some() { if self.sqlite.is_some() {
let sq = self.sqlite.clone().unwrap(); let sq = self.sqlite.clone().unwrap();
let s = sq.get(key).await; if s.is_some() { let s = sq.get(key).await;
if s.is_some() {
let current_time = SystemTime::now() let current_time = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!") .expect("SystemTime before UNIX EPOCH!")
@ -78,11 +85,11 @@ impl Cache {
let mut refresh_memory = s.clone().unwrap(); let mut refresh_memory = s.clone().unwrap();
refresh_memory.cached = current_time; refresh_memory.cached = current_time;
let _ = self.memory.set(key.clone(), refresh_memory).await; let _ = self.memory.set(key.clone(), refresh_memory).await;
return s return s;
} }
} }
return None return None;
} }
pub async fn set(&self, key: String, content_type: String, content: String) -> bool { pub async fn set(&self, key: String, content_type: String, content: String) -> bool {
@ -92,7 +99,12 @@ impl Cache {
.as_secs() .as_secs()
.try_into() .try_into()
.unwrap(); .unwrap();
let cached_item = CachedItem{ content_type, content, cached: current_time, tier: None }; let cached_item = CachedItem {
content_type,
content,
cached: current_time,
tier: None,
};
self.memory.set(key.clone(), cached_item.clone()).await; self.memory.set(key.clone(), cached_item.clone()).await;
if self.sqlite.is_some() { if self.sqlite.is_some() {
let sq = self.sqlite.clone().unwrap(); let sq = self.sqlite.clone().unwrap();
@ -106,8 +118,8 @@ impl Cache {
fn should_use(item: &CachedItem, tier: Tier) -> bool { fn should_use(item: &CachedItem, tier: Tier) -> bool {
// TODO: Make configurable. // TODO: Make configurable.
let cache_time = match tier { let cache_time = match tier {
Tier::Memory => 2*60, Tier::Memory => 2 * 60,
Tier::Sqlite => 10*60, Tier::Sqlite => 10 * 60,
Tier::External => 0, Tier::External => 0,
Tier::None => 0, Tier::None => 0,
}; };
@ -115,7 +127,9 @@ fn should_use(item: &CachedItem, tier: Tier) -> bool {
let current_time: i64 = SystemTime::now() let current_time: i64 = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!") .expect("SystemTime before UNIX EPOCH!")
.as_secs().try_into().unwrap(); .as_secs()
.try_into()
.unwrap();
current_time <= (item.cached + cache_time) && item.content != "" current_time <= (item.cached + cache_time) && item.content != ""
} }

17
src/cache/sqlite.rs vendored
View file

@ -1,23 +1,27 @@
use std::{env, str::FromStr}; use std::{env, str::FromStr};
use async_trait::async_trait; use async_trait::async_trait;
use sqlx::{Pool, sqlite::{SqlitePoolOptions, SqliteJournalMode, SqliteConnectOptions}}; use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions},
Pool,
};
use super::{CacheMechanism, CachedItem, should_use, Tier}; use super::{should_use, CacheMechanism, CachedItem, Tier};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Sqlite { pub struct Sqlite {
pool: Pool<sqlx::Sqlite> pool: Pool<sqlx::Sqlite>,
} }
pub async fn new() -> Option<Sqlite> { pub async fn new() -> Option<Sqlite> {
let path = env::var("DATABASE_PATH").unwrap_or("gs.db".to_owned()); let path = env::var("DATABASE_PATH").unwrap_or("gs.db".to_owned());
let opts = SqliteConnectOptions::from_str(&path).unwrap() let opts = SqliteConnectOptions::from_str(&path)
.unwrap()
.journal_mode(SqliteJournalMode::Wal) .journal_mode(SqliteJournalMode::Wal)
.create_if_missing(true); .create_if_missing(true);
let pool = SqlitePoolOptions::new().connect_with(opts).await.unwrap(); let pool = SqlitePoolOptions::new().connect_with(opts).await.unwrap();
return Some(Sqlite{ pool }); return Some(Sqlite { pool });
} }
#[async_trait] #[async_trait]
@ -25,7 +29,8 @@ impl CacheMechanism for Sqlite {
async fn get(&self, key: &String) -> Option<CachedItem> { async fn get(&self, key: &String) -> Option<CachedItem> {
let res = sqlx::query_as::<_, CachedItem>("SELECT * FROM cached WHERE route = $1") let res = sqlx::query_as::<_, CachedItem>("SELECT * FROM cached WHERE route = $1")
.bind(&key) .bind(&key)
.fetch_one(&self.pool).await; .fetch_one(&self.pool)
.await;
if res.is_ok() { if res.is_ok() {
let c = res.unwrap(); let c = res.unwrap();
if should_use(&c, Tier::Sqlite) { if should_use(&c, Tier::Sqlite) {

View file

@ -1,8 +1,8 @@
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
mod posts;
mod cache; mod cache;
mod posts;
use axum::extract::Path; use axum::extract::Path;
use axum::response::IntoResponse; use axum::response::IntoResponse;
@ -89,7 +89,9 @@ async fn main() -> Result<(), sqlx::Error> {
sqlx::migrate!("./migrations").run(&pool).await?; sqlx::migrate!("./migrations").run(&pool).await?;
env::set_var("DATABASE_PATH", &args.database_path); env::set_var("DATABASE_PATH", &args.database_path);
let state = AppState { cache: init_cache().await }; let state = AppState {
cache: init_cache().await,
};
let app = Router::new() let app = Router::new()
.route("/", get(homepage)) .route("/", get(homepage))
@ -284,7 +286,7 @@ async fn cached_page<T>(
.header("cache", "miss") .header("cache", "miss")
.status(StatusCode::OK) .status(StatusCode::OK)
.body(Full::from(bytes)) .body(Full::from(bytes))
.unwrap() .unwrap();
} else { } else {
let i = item.unwrap(); let i = item.unwrap();
return Response::builder() return Response::builder()

View file

@ -1,6 +1,9 @@
use std::{fs::{self, File}, io::Read}; use std::{
fs::{self, File},
io::Read,
};
use maud::{Render, Markup, html}; use maud::{html, Markup, Render};
use orgize::Org; use orgize::Org;
pub struct PostMetadata { pub struct PostMetadata {
@ -13,7 +16,7 @@ pub struct PostContent {
pub title: String, pub title: String,
pub date: String, pub date: String,
pub content: String, pub content: String,
pub html: String pub html: String,
} }
impl Render for PostMetadata { impl Render for PostMetadata {
@ -110,11 +113,11 @@ pub fn blog_post(post: String) -> Result<PostContent, bool> {
parsed.write_html(&mut writer).unwrap(); parsed.write_html(&mut writer).unwrap();
html = String::from_utf8(writer).unwrap(); html = String::from_utf8(writer).unwrap();
} }
return Ok(PostContent{ return Ok(PostContent {
title, title,
date, date,
content, content,
html html,
}); });
} }
} }