lockbook_server_lib/
garbage_worker.rs1use crate::guard::ServerTx;
2use std::time::Duration;
3use tracing::{debug, error, info};
4
5use lb_rs::model::clock::get_time;
6
7use crate::{
8 ServerState,
9 billing::{
10 app_store_client::AppStoreClient, google_play_client::GooglePlayClient,
11 stripe_client::StripeClient,
12 },
13 document_service::DocumentService,
14};
15
16impl<S, A, G, D> ServerState<S, A, G, D>
17where
18 S: StripeClient,
19 A: AppStoreClient,
20 G: GooglePlayClient,
21 D: DocumentService,
22{
23 pub fn start_garbage_worker(&self) {
24 let bg_self = self.clone();
25
26 tokio::spawn(async move {
27 loop {
28 tokio::time::sleep(Duration::from_secs(60)).await;
29 info!("garbage collecting");
30 bg_self.garbage_collect().await;
31 info!("garbage collected");
32 }
33 });
34 }
35
36 pub async fn garbage_collect(&self) {
37 let mut guard = self.index_db.lock().await;
38 let mut db = match ServerTx::begin(&mut guard) {
39 Ok(tx) => tx,
40 Err(error) => {
41 error!(?error, "failed to begin garbage collection transaction");
42 return;
43 }
44 };
45 let files = db.scheduled_file_cleanups.iter();
46 let mut cleaned = 0;
47 let mut skipped = 0;
48 let mut remove = vec![];
49 for ((id, hmac), time) in files {
50 if get_time().0 - time > 1000 * 60 * 5 {
51 cleaned += 1;
52 if let Err(e) = self.document_service.delete::<()>(id, hmac).await {
53 error!(
54 "failed to garbage collect {:?} {e:?}",
55 self.document_service.get_path(id, hmac)
56 );
57 } else {
58 remove.push((*id, *hmac));
59 }
60 debug!("garbage collected: {:?}", self.document_service.get_path(id, hmac));
61 } else {
62 skipped += 1;
63 }
64 }
65
66 for (id, hmac) in remove {
67 db.scheduled_file_cleanups.remove(&(id, hmac)).unwrap();
68 }
69
70 if let Err(error) = db.end() {
71 error!(?error, "failed to flush garbage collection transaction");
72 }
73
74 info!("cleaned {cleaned}, skipped {skipped}");
75 }
76}