|
1 |
+ |
//! Background cleanup worker: removes orphaned samples off the GUI thread.
|
|
2 |
+ |
//!
|
|
3 |
+ |
//! Mirrors the pattern in `export.rs` — dedicated thread with its own Database +
|
|
4 |
+ |
//! SampleStore, communicating via channels. The GUI thread polls events each frame.
|
|
5 |
+ |
|
|
6 |
+ |
use std::path::PathBuf;
|
|
7 |
+ |
use std::sync::{mpsc, Mutex};
|
|
8 |
+ |
use std::thread;
|
|
9 |
+ |
|
|
10 |
+ |
use tracing::{error, instrument};
|
|
11 |
+ |
|
|
12 |
+ |
use audiofiles_core::db::Database;
|
|
13 |
+ |
use audiofiles_core::store::SampleStore;
|
|
14 |
+ |
|
|
15 |
+ |
/// Command sent from the GUI thread to the cleanup worker.
|
|
16 |
+ |
pub enum CleanupCommand {
|
|
17 |
+ |
/// Start removing orphaned samples.
|
|
18 |
+ |
RemoveOrphans,
|
|
19 |
+ |
/// Cancel the current cleanup.
|
|
20 |
+ |
Cancel,
|
|
21 |
+ |
/// Shut down the worker thread.
|
|
22 |
+ |
Shutdown,
|
|
23 |
+ |
}
|
|
24 |
+ |
|
|
25 |
+ |
/// Event sent from the cleanup worker back to the GUI thread.
|
|
26 |
+ |
pub enum CleanupEvent {
|
|
27 |
+ |
/// Progress update for one sample removed.
|
|
28 |
+ |
Progress {
|
|
29 |
+ |
completed: usize,
|
|
30 |
+ |
total: usize,
|
|
31 |
+ |
current_name: String,
|
|
32 |
+ |
},
|
|
33 |
+ |
/// The cleanup is complete.
|
|
34 |
+ |
Complete {
|
|
35 |
+ |
removed: usize,
|
|
36 |
+ |
errors: usize,
|
|
37 |
+ |
},
|
|
38 |
+ |
}
|
|
39 |
+ |
|
|
40 |
+ |
/// Handle for communicating with the background cleanup worker.
|
|
41 |
+ |
///
|
|
42 |
+ |
/// The receiver is wrapped in a `Mutex` so `BrowserState` remains `Sync` (required by nih-plug).
|
|
43 |
+ |
/// Only the GUI thread actually calls `try_recv`, so contention is zero.
|
|
44 |
+ |
pub struct CleanupHandle {
|
|
45 |
+ |
cmd_tx: mpsc::Sender<CleanupCommand>,
|
|
46 |
+ |
event_rx: Mutex<mpsc::Receiver<CleanupEvent>>,
|
|
47 |
+ |
_thread: Option<thread::JoinHandle<()>>,
|
|
48 |
+ |
}
|
|
49 |
+ |
|
|
50 |
+ |
impl CleanupHandle {
|
|
51 |
+ |
/// Poll for the next event without blocking.
|
|
52 |
+ |
pub fn try_recv(&self) -> Option<CleanupEvent> {
|
|
53 |
+ |
self.event_rx.lock().ok()?.try_recv().ok()
|
|
54 |
+ |
}
|
|
55 |
+ |
|
|
56 |
+ |
/// Send a command to the worker.
|
|
57 |
+ |
pub fn send(&self, cmd: CleanupCommand) {
|
|
58 |
+ |
let _ = self.cmd_tx.send(cmd);
|
|
59 |
+ |
}
|
|
60 |
+ |
}
|
|
61 |
+ |
|
|
62 |
+ |
impl Drop for CleanupHandle {
|
|
63 |
+ |
fn drop(&mut self) {
|
|
64 |
+ |
let _ = self.cmd_tx.send(CleanupCommand::Shutdown);
|
|
65 |
+ |
if let Some(handle) = self._thread.take() {
|
|
66 |
+ |
let _ = handle.join();
|
|
67 |
+ |
}
|
|
68 |
+ |
}
|
|
69 |
+ |
}
|
|
70 |
+ |
|
|
71 |
+ |
/// Spawn the background cleanup worker thread.
|
|
72 |
+ |
///
|
|
73 |
+ |
/// The worker opens its own `Database` and `SampleStore` to avoid Mutex contention
|
|
74 |
+ |
/// with the GUI thread.
|
|
75 |
+ |
#[instrument(skip_all)]
|
|
76 |
+ |
pub fn spawn_cleanup_worker(
|
|
77 |
+ |
db_path: PathBuf,
|
|
78 |
+ |
store_root: PathBuf,
|
|
79 |
+ |
) -> std::io::Result<CleanupHandle> {
|
|
80 |
+ |
let (cmd_tx, cmd_rx) = mpsc::channel::<CleanupCommand>();
|
|
81 |
+ |
let (event_tx, event_rx) = mpsc::channel::<CleanupEvent>();
|
|
82 |
+ |
|
|
83 |
+ |
let thread = thread::Builder::new()
|
|
84 |
+ |
.name("cleanup-worker".to_string())
|
|
85 |
+ |
.spawn(move || {
|
|
86 |
+ |
worker_loop(cmd_rx, event_tx, &db_path, &store_root);
|
|
87 |
+ |
})?;
|
|
88 |
+ |
|
|
89 |
+ |
Ok(CleanupHandle {
|
|
90 |
+ |
cmd_tx,
|
|
91 |
+ |
event_rx: Mutex::new(event_rx),
|
|
92 |
+ |
_thread: Some(thread),
|
|
93 |
+ |
})
|
|
94 |
+ |
}
|
|
95 |
+ |
|
|
96 |
+ |
#[instrument(skip_all)]
|
|
97 |
+ |
fn worker_loop(
|
|
98 |
+ |
cmd_rx: mpsc::Receiver<CleanupCommand>,
|
|
99 |
+ |
event_tx: mpsc::Sender<CleanupEvent>,
|
|
100 |
+ |
db_path: &std::path::Path,
|
|
101 |
+ |
store_root: &std::path::Path,
|
|
102 |
+ |
) {
|
|
103 |
+ |
let db = match Database::open(db_path) {
|
|
104 |
+ |
Ok(d) => d,
|
|
105 |
+ |
Err(e) => {
|
|
106 |
+ |
let _ = event_tx.send(CleanupEvent::Complete {
|
|
107 |
+ |
removed: 0,
|
|
108 |
+ |
errors: 1,
|
|
109 |
+ |
});
|
|
110 |
+ |
error!("Cleanup worker failed to open database: {e}");
|
|
111 |
+ |
return;
|
|
112 |
+ |
}
|
|
113 |
+ |
};
|
|
114 |
+ |
|
|
115 |
+ |
let store = match SampleStore::new(store_root) {
|
|
116 |
+ |
Ok(s) => s,
|
|
117 |
+ |
Err(e) => {
|
|
118 |
+ |
let _ = event_tx.send(CleanupEvent::Complete {
|
|
119 |
+ |
removed: 0,
|
|
120 |
+ |
errors: 1,
|
|
121 |
+ |
});
|
|
122 |
+ |
error!("Cleanup worker failed to open store: {e}");
|
|
123 |
+ |
return;
|
|
124 |
+ |
}
|
|
125 |
+ |
};
|
|
126 |
+ |
|
|
127 |
+ |
while let Ok(cmd) = cmd_rx.recv() {
|
|
128 |
+ |
match cmd {
|
|
129 |
+ |
CleanupCommand::Shutdown => break,
|
|
130 |
+ |
CleanupCommand::Cancel => continue,
|
|
131 |
+ |
CleanupCommand::RemoveOrphans => {
|
|
132 |
+ |
remove_orphans(&cmd_rx, &event_tx, &db, &store);
|
|
133 |
+ |
}
|
|
134 |
+ |
}
|
|
135 |
+ |
}
|
|
136 |
+ |
}
|
|
137 |
+ |
|
|
138 |
+ |
fn remove_orphans(
|
|
139 |
+ |
cmd_rx: &mpsc::Receiver<CleanupCommand>,
|
|
140 |
+ |
event_tx: &mpsc::Sender<CleanupEvent>,
|
|
141 |
+ |
db: &Database,
|
|
142 |
+ |
store: &SampleStore,
|
|
143 |
+ |
) {
|
|
144 |
+ |
// Query all orphaned samples in one pass
|
|
145 |
+ |
let orphans = match db.conn().prepare(
|
|
146 |
+ |
"SELECT s.hash, s.file_extension, s.original_name
|
|
147 |
+ |
FROM samples s
|
|
148 |
+ |
LEFT JOIN vfs_nodes vn ON s.hash = vn.sample_hash
|
|
149 |
+ |
WHERE vn.id IS NULL",
|
|
150 |
+ |
) {
|
|
151 |
+ |
Ok(mut stmt) => {
|
|
152 |
+ |
let rows = stmt
|
|
153 |
+ |
.query_map([], |row| {
|
|
154 |
+ |
Ok((
|
|
155 |
+ |
row.get::<_, String>(0)?,
|
|
156 |
+ |
row.get::<_, String>(1)?,
|
|
157 |
+ |
row.get::<_, String>(2)?,
|
|
158 |
+ |
))
|
|
159 |
+ |
})
|
|
160 |
+ |
.ok()
|
|
161 |
+ |
.map(|iter| iter.flatten().collect::<Vec<_>>())
|
|
162 |
+ |
.unwrap_or_default();
|
|
163 |
+ |
rows
|
|
164 |
+ |
}
|
|
165 |
+ |
Err(e) => {
|
|
166 |
+ |
error!("Cleanup worker failed to query orphans: {e}");
|
|
167 |
+ |
let _ = event_tx.send(CleanupEvent::Complete {
|
|
168 |
+ |
removed: 0,
|
|
169 |
+ |
errors: 1,
|
|
170 |
+ |
});
|
|
171 |
+ |
return;
|
|
172 |
+ |
}
|
|
173 |
+ |
};
|
|
174 |
+ |
|
|
175 |
+ |
let total = orphans.len();
|
|
176 |
+ |
if total == 0 {
|
|
177 |
+ |
let _ = event_tx.send(CleanupEvent::Complete {
|
|
178 |
+ |
removed: 0,
|
|
179 |
+ |
errors: 0,
|
|
180 |
+ |
});
|
|
181 |
+ |
return;
|
|
182 |
+ |
}
|
|
183 |
+ |
|
|
184 |
+ |
let mut removed = 0usize;
|
|
185 |
+ |
let mut errors = 0usize;
|
|
186 |
+ |
|
|
187 |
+ |
for (i, (hash, ext, name)) in orphans.iter().enumerate() {
|
|
188 |
+ |
// Check for cancel between deletions
|
|
189 |
+ |
if let Ok(CleanupCommand::Cancel) | Ok(CleanupCommand::Shutdown) = cmd_rx.try_recv() {
|
|
190 |
+ |
let _ = event_tx.send(CleanupEvent::Complete { removed, errors });
|
|
191 |
+ |
return;
|
|
192 |
+ |
}
|
|
193 |
+ |
|
|
194 |
+ |
let _ = event_tx.send(CleanupEvent::Progress {
|
|
195 |
+ |
completed: i,
|
|
196 |
+ |
total,
|
|
197 |
+ |
current_name: name.clone(),
|
|
198 |
+ |
});
|
|
199 |
+ |
|
|
200 |
+ |
// Delete from DB
|
|
201 |
+ |
match db
|
|
202 |
+ |
.conn()
|
|
203 |
+ |
.execute("DELETE FROM samples WHERE hash = ?1", [hash])
|
|
204 |
+ |
{
|
|
205 |
+ |
Ok(_) => {
|
|
206 |
+ |
// Delete from disk
|
|
207 |
+ |
if let Ok(path) = store.sample_path(hash, ext) {
|
|
208 |
+ |
if path.exists() {
|
|
209 |
+ |
let _ = std::fs::remove_file(&path);
|
|
210 |
+ |
}
|
|
211 |
+ |
}
|
|
212 |
+ |
removed += 1;
|
|
213 |
+ |
}
|
|
214 |
+ |
Err(e) => {
|
|
215 |
+ |
error!("Cleanup: failed to delete sample {hash}: {e}");
|
|
216 |
+ |
errors += 1;
|
|
217 |
+ |
}
|
|
218 |
+ |
}
|
|
219 |
+ |
}
|
|
220 |
+ |
|
|
221 |
+ |
// WAL checkpoint for clean state
|
|
222 |
+ |
let _ = db
|
|
223 |
+ |
.conn()
|
|
224 |
+ |
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
225 |
+ |
|
|
226 |
+ |
let _ = event_tx.send(CleanupEvent::Complete { removed, errors });
|
|
227 |
+ |
}
|
|
228 |
+ |
|
|
229 |
+ |
#[cfg(test)]
|
|
230 |
+ |
mod tests {
|
|
231 |
+ |
use super::*;
|
|
232 |
+ |
|
|
233 |
+ |
#[test]
|
|
234 |
+ |
fn cleanup_command_variants_constructible() {
|
|
235 |
+ |
let _remove = CleanupCommand::RemoveOrphans;
|
|
236 |
+ |
let _cancel = CleanupCommand::Cancel;
|
|
237 |
+ |
let _shutdown = CleanupCommand::Shutdown;
|
|
238 |
+ |
}
|
|
239 |
+ |
|
|
240 |
+ |
#[test]
|
|
241 |
+ |
fn cleanup_event_variants_constructible() {
|
|
242 |
+ |
let _progress = CleanupEvent::Progress {
|
|
243 |
+ |
completed: 5,
|
|
244 |
+ |
total: 10,
|
|
245 |
+ |
current_name: "kick.wav".to_string(),
|
|
246 |
+ |
};
|
|
247 |
+ |
let _complete = CleanupEvent::Complete {
|
|
248 |
+ |
removed: 10,
|
|
249 |
+ |
errors: 0,
|
|
250 |
+ |
};
|
|
251 |
+ |
}
|
|
252 |
+ |
|
|
253 |
+ |
#[test]
|
|
254 |
+ |
fn spawn_and_drop_does_not_hang() {
|
|
255 |
+ |
let dir = tempfile::TempDir::new().unwrap();
|
|
256 |
+ |
let db_path = dir.path().join("audiofiles.db");
|
|
257 |
+ |
let store_root = dir.path().join("store");
|
|
258 |
+ |
std::fs::create_dir_all(&store_root).unwrap();
|
|
259 |
+ |
|
|
260 |
+ |
// Create the database so the worker can open it
|
|
261 |
+ |
let _db = Database::open(&db_path).unwrap();
|
|
262 |
+ |
|
|
263 |
+ |
let handle = spawn_cleanup_worker(db_path, store_root).unwrap();
|
|
264 |
+ |
assert!(handle.try_recv().is_none());
|
|
265 |
+ |
drop(handle); // Should send Shutdown and join cleanly
|
|
266 |
+ |
}
|
|
267 |
+ |
|
|
268 |
+ |
#[test]
|
|
269 |
+ |
fn cleanup_no_orphans_completes_immediately() {
|
|
270 |
+ |
let dir = tempfile::TempDir::new().unwrap();
|
|
271 |
+ |
let db_path = dir.path().join("audiofiles.db");
|
|
272 |
+ |
let store_root = dir.path().join("store");
|
|
273 |
+ |
std::fs::create_dir_all(&store_root).unwrap();
|
|
274 |
+ |
|
|
275 |
+ |
let _db = Database::open(&db_path).unwrap();
|
|
276 |
+ |
|
|
277 |
+ |
let handle = spawn_cleanup_worker(db_path, store_root).unwrap();
|
|
278 |
+ |
handle.send(CleanupCommand::RemoveOrphans);
|
|
279 |
+ |
|
|
280 |
+ |
// Give the worker a moment to process
|
|
281 |
+ |
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
282 |
+ |
|
|
283 |
+ |
let mut got_complete = false;
|
|
284 |
+ |
while let Some(event) = handle.try_recv() {
|
|
285 |
+ |
if let CleanupEvent::Complete { removed, errors } = event {
|
|
286 |
+ |
assert_eq!(removed, 0);
|
|
287 |
+ |
assert_eq!(errors, 0);
|
|
288 |
+ |
got_complete = true;
|
|
289 |
+ |
}
|
|
290 |
+ |
}
|
|
291 |
+ |
assert!(got_complete);
|
|
292 |
+ |
}
|
|
293 |
+ |
}
|