Skip to content

Commit

Permalink
Garbage collect expired clips
Browse files Browse the repository at this point in the history
  • Loading branch information
filiptronicek committed Mar 29, 2024
1 parent 63fe926 commit 5f2fcde
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ fern = "0.5"
dotenv = "0.15.0"
diesel = { version = "2.1.4", features = ["postgres", "chrono"] }
regex = "1.10"
clokwerk = "0.3.5"

## file things
aws-config = "0.14.0"
Expand Down
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod models;
mod schema;
mod utils;

use clokwerk::{Scheduler, TimeUnits};
use regex::Regex;
use rocket::http::{Header, Status};
use rocket::response::status::Custom;
Expand All @@ -22,7 +23,7 @@ use std::time::Duration;
use rocket::form::Form;
use rocket::serde::json::Json;

use utils::db;
use utils::db::{self, collect_garbage};

use crate::utils::rate_limit::RateLimiter;
use crate::utils::structs::{APIResponse, APIStatus};
Expand Down Expand Up @@ -379,6 +380,12 @@ async fn rocket() -> _ {

let s3_client = create_storage_client().await.unwrap();

let mut db_connection = db::initialize().expect("Failed to connect to the database");
let mut scheduler = Scheduler::with_tz(chrono::Utc);
scheduler.every(1.hour()).run(move || {
let _ = collect_garbage(&mut db_connection);
});

rocket::build()
.mount(
"/api",
Expand Down
7 changes: 7 additions & 0 deletions src/utils/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,10 @@ pub fn insert_clip(
.values(&new_clip)
.get_result::<Clip>(connection)
}

/// Deletes expired clips from the database
pub fn collect_garbage(connection: &mut PgConnection) -> Result<usize, diesel::result::Error> {
use crate::schema::clips::dsl::*;

diesel::delete(clips.filter(expires_at.is_not_null().and(expires_at.lt(chrono::Local::now().naive_local())))).execute(connection)
}

0 comments on commit 5f2fcde

Please sign in to comment.