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

54
src/cache/mod.rs vendored
View file

@ -1,9 +1,12 @@
mod memory;
mod sqlite;
use std::{time::{SystemTime, UNIX_EPOCH}, fmt};
use async_trait::async_trait;
use sqlx::FromRow;
use std::{
fmt,
time::{SystemTime, UNIX_EPOCH},
};
use self::{memory::Memory, sqlite::Sqlite};
@ -14,7 +17,10 @@ pub struct 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
@ -24,7 +30,7 @@ pub enum Tier {
Memory,
Sqlite,
External,
None
None,
}
impl fmt::Display for Tier {
@ -44,7 +50,7 @@ pub struct CachedItem {
pub content: String,
cached: i64,
#[sqlx(default)]
tier: Option<Tier>
tier: Option<Tier>,
}
impl CachedItem {
@ -54,7 +60,7 @@ impl CachedItem {
}
#[async_trait]
pub trait CacheMechanism: Sized + Clone + Send + Sync + 'static {
pub trait CacheMechanism: Sized + Clone + Send + Sync + 'static {
async fn get(&self, key: &String) -> Option<CachedItem>;
async fn rm(&mut self, key: String);
async fn set(&self, key: String, item: CachedItem);
@ -68,7 +74,8 @@ impl Cache {
}
if self.sqlite.is_some() {
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()
.duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!")
@ -78,36 +85,41 @@ impl Cache {
let mut refresh_memory = s.clone().unwrap();
refresh_memory.cached = current_time;
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 {
let current_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!")
.as_secs()
.try_into()
.unwrap();
let cached_item = CachedItem{ content_type, content, cached: current_time, tier: None };
self.memory.set(key.clone(), cached_item.clone()).await;
if self.sqlite.is_some() {
let sq = self.sqlite.clone().unwrap();
sq.set(key.clone(), cached_item.clone()).await;
}
true
}
let cached_item = CachedItem {
content_type,
content,
cached: current_time,
tier: None,
};
self.memory.set(key.clone(), cached_item.clone()).await;
if self.sqlite.is_some() {
let sq = self.sqlite.clone().unwrap();
sq.set(key.clone(), cached_item.clone()).await;
}
true
}
}
/// Determine whether we should actually use the cached item or not.
fn should_use(item: &CachedItem, tier: Tier) -> bool {
// TODO: Make configurable.
let cache_time = match tier {
Tier::Memory => 2*60,
Tier::Sqlite => 10*60,
Tier::Memory => 2 * 60,
Tier::Sqlite => 10 * 60,
Tier::External => 0,
Tier::None => 0,
};
@ -115,7 +127,9 @@ fn should_use(item: &CachedItem, tier: Tier) -> bool {
let current_time: i64 = SystemTime::now()
.duration_since(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 != ""
}

17
src/cache/sqlite.rs vendored
View file

@ -1,23 +1,27 @@
use std::{env, str::FromStr};
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)]
pub struct Sqlite {
pool: Pool<sqlx::Sqlite>
pool: Pool<sqlx::Sqlite>,
}
pub async fn new() -> Option<Sqlite> {
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)
.create_if_missing(true);
let pool = SqlitePoolOptions::new().connect_with(opts).await.unwrap();
return Some(Sqlite{ pool });
return Some(Sqlite { pool });
}
#[async_trait]
@ -25,7 +29,8 @@ impl CacheMechanism for Sqlite {
async fn get(&self, key: &String) -> Option<CachedItem> {
let res = sqlx::query_as::<_, CachedItem>("SELECT * FROM cached WHERE route = $1")
.bind(&key)
.fetch_one(&self.pool).await;
.fetch_one(&self.pool)
.await;
if res.is_ok() {
let c = res.unwrap();
if should_use(&c, Tier::Sqlite) {

View file

@ -1,8 +1,8 @@
#[macro_use]
extern crate lazy_static;
mod posts;
mod cache;
mod posts;
use axum::extract::Path;
use axum::response::IntoResponse;
@ -89,7 +89,9 @@ async fn main() -> Result<(), sqlx::Error> {
sqlx::migrate!("./migrations").run(&pool).await?;
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()
.route("/", get(homepage))
@ -142,10 +144,10 @@ async fn render_blog_post(Path(post): Path<String>) -> Result<impl IntoResponse,
}
};
Ok(Response::builder()
.header("content-type", "text/html")
.status(StatusCode::OK)
.body(Full::from(html.into_string()))
.unwrap())
.header("content-type", "text/html")
.status(StatusCode::OK)
.body(Full::from(html.into_string()))
.unwrap())
}
async fn rss() -> Result<impl IntoResponse, StatusCode> {
@ -284,7 +286,7 @@ async fn cached_page<T>(
.header("cache", "miss")
.status(StatusCode::OK)
.body(Full::from(bytes))
.unwrap()
.unwrap();
} else {
let i = item.unwrap();
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;
pub struct PostMetadata {
@ -13,7 +16,7 @@ pub struct PostContent {
pub title: String,
pub date: String,
pub content: String,
pub html: String
pub html: String,
}
impl Render for PostMetadata {
@ -110,11 +113,11 @@ pub fn blog_post(post: String) -> Result<PostContent, bool> {
parsed.write_html(&mut writer).unwrap();
html = String::from_utf8(writer).unwrap();
}
return Ok(PostContent{
return Ok(PostContent {
title,
date,
content,
html
html,
});
}
}