Allow configuring the number of days to expire documents

This commit is contained in:
orhun 2021-06-10 03:15:22 +03:00
parent f4e4a79798
commit 33d6c6f0d0
No known key found for this signature in database
GPG key ID: F83424824B3E4B90
3 changed files with 24 additions and 10 deletions

1
.env
View file

@ -1,2 +1,3 @@
# Environment variables for development
RUST_LOG=info
EXPIRY_DAYS=1

View file

@ -44,9 +44,16 @@ struct Stats {
num_documents: usize,
}
/// Data that will be used to configure the server.
#[derive(Debug)]
pub struct ServerData {
/// Number of days to clean up documents after inactivity.
pub expiry_days: u32,
}
/// A combined filter handling all server routes.
pub fn server() -> BoxedFilter<(impl Reply,)> {
warp::path("api").and(backend()).or(frontend()).boxed()
pub fn server(data: ServerData) -> BoxedFilter<(impl Reply,)> {
warp::path("api").and(backend(data)).or(frontend()).boxed()
}
/// Construct routes for static files from React.
@ -55,9 +62,9 @@ fn frontend() -> BoxedFilter<(impl Reply,)> {
}
/// Construct backend routes, including WebSocket handlers.
fn backend() -> BoxedFilter<(impl Reply,)> {
fn backend(data: ServerData) -> BoxedFilter<(impl Reply,)> {
let state: Arc<DashMap<String, Document>> = Default::default();
tokio::spawn(cleaner(Arc::clone(&state)));
tokio::spawn(cleaner(Arc::clone(&state), Arc::new(data.expiry_days)));
let state_filter = warp::any().map(move || Arc::clone(&state));
@ -106,15 +113,14 @@ fn backend() -> BoxedFilter<(impl Reply,)> {
}
const HOUR: Duration = Duration::from_secs(3600);
const DAY: Duration = Duration::from_secs(24 * 3600);
// Reclaims memory for documents after a day of inactivity.
async fn cleaner(state: Arc<DashMap<String, Document>>) {
// Reclaims memory for documents.
async fn cleaner(state: Arc<DashMap<String, Document>>, expiry_days: Arc<u32>) {
loop {
time::sleep(HOUR).await;
let mut keys = Vec::new();
for entry in &*state {
if entry.last_accessed.elapsed() > DAY {
if entry.last_accessed.elapsed() > HOUR * 24 * *expiry_days {
keys.push(entry.key().clone());
}
}

View file

@ -1,4 +1,4 @@
use rustpad_server::server;
use rustpad_server::{server, ServerData};
#[tokio::main]
async fn main() {
@ -10,5 +10,12 @@ async fn main() {
.parse()
.expect("Unable to parse PORT");
warp::serve(server()).run(([0, 0, 0, 0], port)).await;
let data = ServerData {
expiry_days: std::env::var("EXPIRY_DAYS")
.unwrap_or_else(|_| String::from("1"))
.parse()
.expect("Unable to parse EXPIRY_DAYS"),
};
warp::serve(server(data)).run(([0, 0, 0, 0], port)).await;
}