| 1 | use std::time::{Duration, SystemTime}; |
| 2 | |
| 3 | use tokio::sync::{Mutex, MutexGuard}; |
| 4 | |
| 5 | use super::blobs::blob_key; |
| 6 | use crate::state::AppState; |
| 7 | |
| 8 | static LOCK: Mutex<()> = Mutex::const_new(()); |
| 9 | |
| 10 | pub const GRACE: Duration = Duration::from_secs(60 * 60); |
| 11 | |
| 12 | pub async fn lock() -> MutexGuard<'static, ()> { |
| 13 | LOCK.lock().await |
| 14 | } |
| 15 | |
| 16 | pub async fn sweep_orphans(state: &AppState) -> forge_core::Result<usize> { |
| 17 | let cutoff = SystemTime::now() - GRACE; |
| 18 | let mut removed = 0; |
| 19 | for key in state.blobs.keys_older_than("oci/", cutoff).await? { |
| 20 | let Some(hex) = key.strip_prefix("oci/") else { |
| 21 | continue; |
| 22 | }; |
| 23 | let _guard = lock().await; |
| 24 | if state |
| 25 | .store |
| 26 | .oci_digest_linked(&format!("sha256:{hex}")) |
| 27 | .await? |
| 28 | { |
| 29 | continue; |
| 30 | } |
| 31 | state.blobs.delete(&key).await?; |
| 32 | removed += 1; |
| 33 | } |
| 34 | Ok(removed) |
| 35 | } |
| 36 | |
| 37 | pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> { |
| 38 | let _guard = lock().await; |
| 39 | let linked_before = forge_core::time::stamp_ago(GRACE); |
| 40 | let dropped = state |
| 41 | .store |
| 42 | .oci_sweep_unreferenced(package_id, &linked_before) |
| 43 | .await?; |
| 44 | for digest in &dropped { |
| 45 | if state.store.oci_digest_linked(digest).await? { |
| 46 | continue; |
| 47 | } |
| 48 | if let Some(hex) = digest.strip_prefix("sha256:") { |
| 49 | state.blobs.delete(&blob_key(hex)).await?; |
| 50 | } |
| 51 | } |
| 52 | Ok(dropped.len()) |
| 53 | } |