aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorFuwn <[email protected]>2022-04-17 13:19:53 -0700
committerFuwn <[email protected]>2022-04-17 13:19:53 -0700
commit23a1199e195ce5482a93a7f33478231b7fbced3e (patch)
tree4c86cdf727b5aab510a28c45a7214942093c4236 /src
parentrefactor: route for future use (diff)
downloadlocus-23a1199e195ce5482a93a7f33478231b7fbced3e.tar.xz
locus-23a1199e195ce5482a93a7f33478231b7fbced3e.zip
feat: implement cacher
Diffstat (limited to 'src')
-rw-r--r--src/main.rs2
-rw-r--r--src/route.rs39
2 files changed, 40 insertions, 1 deletions
diff --git a/src/main.rs b/src/main.rs
index f926faf..613f2bc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -16,7 +16,7 @@
// Copyright (C) 2022-2022 Fuwn <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
-#![feature(once_cell)]
+#![feature(once_cell, is_some_with)]
#![deny(
warnings,
nonstandard_style,
diff --git a/src/route.rs b/src/route.rs
index 1c4b128..2da2cbb 100644
--- a/src/route.rs
+++ b/src/route.rs
@@ -16,6 +16,13 @@
// Copyright (C) 2022-2022 Fuwn <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only
+use std::{lazy::SyncLazy, sync::Mutex};
+
+use tokio::time::Instant;
+
+use crate::ROUTES;
+
+#[derive(Debug)]
pub struct Route {
pub description: String,
pub text_cache: String,
@@ -49,3 +56,35 @@ pub fn track_mount(
.insert(route.to_string(), Route::new(description));
router.mount(route, handler);
}
+
+#[allow(unused)]
+pub fn cache(context: &windmark::returnable::RouteContext<'_>, response: &str) {
+ static LAST_CACHED: SyncLazy<Mutex<Instant>> =
+ SyncLazy::new(|| Mutex::new(Instant::now()));
+
+ if (*LAST_CACHED.lock().unwrap()).elapsed()
+ >= std::time::Duration::from_secs(1)
+ || (*ROUTES.lock().unwrap())
+ .get(context.url.path())
+ .is_some_with(|&r| r.text_cache.is_empty())
+ {
+ (*LAST_CACHED.lock().unwrap()) = Instant::now();
+
+ if let Some(route) = (*ROUTES.lock().unwrap()).get_mut(context.url.path()) {
+ route.text_cache = response.to_string();
+ info!("cache set for {}", context.url.path());
+ } else {
+ warn!(
+ "cache could not be set for {} as it is not being tracked",
+ context.url.path()
+ );
+ }
+
+ trace!("recache for {}", context.url.path());
+ } else {
+ trace!(
+ "no cache, with last: {:?}",
+ (*ROUTES.lock().unwrap()).get(context.url.path())
+ );
+ }
+}