1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Temporary file management for media pipelines.
//!
//! Creates, tracks, and cleans up temporary files and directories used
//! during transcoding, analysis, and other intermediate processing stages.
#![allow(dead_code)]
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
/// Process-global counter that hands every `TempFileManager` a distinct id.
///
/// Combined with the process id and a high-resolution creation timestamp this
/// guarantees that filenames generated by independent managers — even ones
/// created simultaneously on different threads — never collide.
static MANAGER_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
/// Configuration for how temporary files are created and stored.
#[derive(Debug, Clone)]
pub struct TempFileConfig {
/// Base directory for temporary files. Defaults to the system temp dir.
pub base_dir: PathBuf,
/// Optional prefix applied to every generated filename.
pub prefix: String,
/// Optional suffix (e.g. `.mp4`) applied to every generated filename.
pub suffix: String,
/// Whether to delete files on [`TempFileHandle`] drop.
pub auto_delete: bool,
}
impl TempFileConfig {
/// Create a new config pointing at the system temp directory.
#[must_use]
pub fn new() -> Self {
Self {
base_dir: std::env::temp_dir(),
prefix: "oximedia_".to_string(),
suffix: String::new(),
auto_delete: true,
}
}
/// Override the base directory.
#[must_use]
pub fn with_base_dir(mut self, dir: impl AsRef<Path>) -> Self {
self.base_dir = dir.as_ref().to_path_buf();
self
}
/// Override the filename prefix.
#[must_use]
pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = prefix.into();
self
}
/// Override the filename suffix.
#[must_use]
pub fn with_suffix(mut self, suffix: impl Into<String>) -> Self {
self.suffix = suffix.into();
self
}
/// Disable automatic deletion on drop.
#[must_use]
pub fn no_auto_delete(mut self) -> Self {
self.auto_delete = false;
self
}
}
impl Default for TempFileConfig {
fn default() -> Self {
Self::new()
}
}
/// Handle to a single temporary file.
///
/// When `auto_delete` is set in the originating config the underlying file
/// is removed from disk when this handle is dropped.
#[derive(Debug)]
pub struct TempFileHandle {
/// Absolute path to the temporary file.
pub path: PathBuf,
auto_delete: bool,
}
impl TempFileHandle {
/// Return the path of this temporary file.
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
/// Return `true` if the file still exists on disk.
#[must_use]
pub fn exists(&self) -> bool {
self.path.exists()
}
/// Delete the file immediately without waiting for drop.
///
/// # Errors
///
/// Returns an I/O error if the file cannot be removed.
pub fn remove(self) -> std::io::Result<()> {
if self.path.exists() {
std::fs::remove_file(&self.path)?;
}
// Suppress auto-delete in Drop
std::mem::forget(self);
Ok(())
}
}
impl Drop for TempFileHandle {
fn drop(&mut self) {
if self.auto_delete && self.path.exists() {
let _ = std::fs::remove_file(&self.path);
}
}
}
/// Manages a collection of temporary files for a processing session.
///
/// Thread-safe: all mutations are guarded by an internal `Mutex`.
///
/// Every manager carries a unique tag composed of the process id, a
/// high-resolution creation timestamp, and a process-global manager id. This
/// tag is woven into every generated filename so that managers running in
/// parallel — across threads, processes, or repeated test runs — cannot
/// collide on the system temp directory.
#[derive(Debug, Clone)]
pub struct TempFileManager {
config: TempFileConfig,
/// Map from logical name to path (for named lookup).
registry: Arc<Mutex<HashMap<String, PathBuf>>>,
counter: Arc<Mutex<u64>>,
/// OS process id captured at construction time.
process_id: u32,
/// Nanoseconds since the Unix epoch captured at construction time.
creation_nanos: u128,
/// Monotonically increasing per-process manager id.
manager_id: u64,
}
impl TempFileManager {
/// Create a new manager with the given config.
#[must_use]
pub fn new(config: TempFileConfig) -> Self {
let creation_nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
Self {
config,
registry: Arc::new(Mutex::new(HashMap::new())),
counter: Arc::new(Mutex::new(0)),
process_id: std::process::id(),
creation_nanos,
manager_id: MANAGER_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
}
}
/// Create a new manager with default config.
#[must_use]
pub fn with_defaults() -> Self {
Self::new(TempFileConfig::default())
}
/// Allocate a new temporary file and return its handle.
///
/// The file is created (empty) on disk immediately.
///
/// # Errors
///
/// Returns an I/O error if the file cannot be created.
///
/// # Panics
///
/// Panics if the internal counter mutex is poisoned.
pub fn create(&self) -> std::io::Result<TempFileHandle> {
self.create_named(&self.next_name())
}
/// Allocate a temp file and register it under a logical `name` for later
/// lookup.
///
/// # Errors
///
/// Returns an I/O error if the file cannot be created.
///
/// # Panics
///
/// Panics if the internal registry mutex is poisoned.
pub fn create_named(&self, name: &str) -> std::io::Result<TempFileHandle> {
let filename = format!("{}{}{}", self.config.prefix, name, self.config.suffix);
let path = self.config.base_dir.join(&filename);
std::fs::write(&path, b"")?;
self.registry
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(name.to_string(), path.clone());
Ok(TempFileHandle {
path,
auto_delete: self.config.auto_delete,
})
}
/// Look up the path registered under a logical name.
///
/// # Panics
///
/// Panics if the internal registry mutex is poisoned.
#[must_use]
pub fn lookup(&self, name: &str) -> Option<PathBuf> {
self.registry
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(name)
.cloned()
}
/// Delete all tracked temporary files and clear the registry.
///
/// # Errors
///
/// Returns an I/O error if any file cannot be removed.
///
/// # Panics
///
/// Panics if the internal registry mutex is poisoned.
pub fn cleanup(&self) -> std::io::Result<()> {
let mut reg = self.registry.lock().unwrap_or_else(|e| e.into_inner());
for (_name, path) in reg.iter() {
if path.exists() {
std::fs::remove_file(path)?;
}
}
reg.clear();
Ok(())
}
/// Number of files currently tracked.
///
/// # Panics
///
/// Panics if the internal registry mutex is poisoned.
#[must_use]
pub fn count(&self) -> usize {
self.registry
.lock()
.unwrap_or_else(|e| e.into_inner())
.len()
}
fn next_name(&self) -> String {
let mut c = self.counter.lock().unwrap_or_else(|e| e.into_inner());
let n = *c;
*c += 1;
format!(
"{:x}_{:x}_{:x}_{n:08x}",
self.process_id, self.creation_nanos, self.manager_id
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_temp_file_exists_on_disk() {
let mgr = TempFileManager::with_defaults();
let handle = mgr.create().expect("failed to create temp file");
assert!(handle.exists());
}
#[test]
fn test_auto_delete_on_drop() {
let mgr = TempFileManager::with_defaults();
let path = {
let handle = mgr.create().expect("failed to create temp file");
handle.path().to_path_buf()
};
assert!(!path.exists());
}
#[test]
fn test_no_auto_delete_survives_drop() {
let config = TempFileConfig::new().no_auto_delete();
let mgr = TempFileManager::new(config);
let path = {
let handle = mgr.create().expect("failed to create temp file");
handle.path().to_path_buf()
};
// File should still exist — clean up manually
if path.exists() {
std::fs::remove_file(&path).expect("failed to remove file");
}
}
#[test]
fn test_explicit_remove() {
let mgr = TempFileManager::with_defaults();
let handle = mgr.create().expect("failed to create temp file");
let path = handle.path().to_path_buf();
handle.remove().expect("failed to remove temp file");
assert!(!path.exists());
}
#[test]
fn test_create_named_and_lookup() {
let mgr = TempFileManager::with_defaults();
let _handle = mgr
.create_named("audio_work")
.expect("failed to create named temp file");
let found = mgr.lookup("audio_work");
assert!(found.is_some());
}
#[test]
fn test_lookup_missing_returns_none() {
let mgr = TempFileManager::with_defaults();
assert!(mgr.lookup("nonexistent").is_none());
}
#[test]
fn test_cleanup_removes_files() {
let mgr = TempFileManager::new(TempFileConfig::new().no_auto_delete());
let h1 = mgr
.create_named("f1")
.expect("failed to create named temp file");
let h2 = mgr
.create_named("f2")
.expect("failed to create named temp file");
let p1 = h1.path().to_path_buf();
let p2 = h2.path().to_path_buf();
// Suppress their own drop (auto_delete = false)
std::mem::forget(h1);
std::mem::forget(h2);
mgr.cleanup().expect("cleanup should succeed");
assert!(!p1.exists());
assert!(!p2.exists());
}
#[test]
fn test_cleanup_clears_registry() {
let mgr = TempFileManager::with_defaults();
let h = mgr
.create_named("tmp_x")
.expect("failed to create named temp file");
std::mem::forget(h);
mgr.cleanup().expect("cleanup should succeed");
assert_eq!(mgr.count(), 0);
}
#[test]
fn test_count_tracks_entries() {
let mgr = TempFileManager::with_defaults();
assert_eq!(mgr.count(), 0);
let h1 = mgr
.create_named("a")
.expect("failed to create named temp file");
std::mem::forget(h1);
assert_eq!(mgr.count(), 1);
let h2 = mgr
.create_named("b")
.expect("failed to create named temp file");
std::mem::forget(h2);
assert_eq!(mgr.count(), 2);
mgr.cleanup().expect("cleanup should succeed");
assert_eq!(mgr.count(), 0);
}
#[test]
fn test_suffix_applied() {
let config = TempFileConfig::new().with_suffix(".ts");
let mgr = TempFileManager::new(config);
let handle = mgr.create().expect("failed to create temp file");
let path_str = handle.path().to_string_lossy().to_string();
assert!(path_str.ends_with(".ts"));
let _ = handle.remove();
}
#[test]
fn test_prefix_applied() {
let config = TempFileConfig::new().with_prefix("oxi_pfx_");
let mgr = TempFileManager::new(config);
let handle = mgr.create().expect("failed to create temp file");
let fname = handle
.path()
.file_name()
.expect("operation should succeed")
.to_string_lossy()
.to_string();
assert!(fname.starts_with("oxi_pfx_"));
let _ = handle.remove();
}
#[test]
fn test_config_default() {
let cfg = TempFileConfig::default();
assert_eq!(cfg.prefix, "oximedia_");
assert!(cfg.auto_delete);
}
#[test]
fn test_temp_file_config_builder_chain() {
let cfg = TempFileConfig::new()
.with_prefix("test_")
.with_suffix(".raw")
.no_auto_delete();
assert_eq!(cfg.prefix, "test_");
assert_eq!(cfg.suffix, ".raw");
assert!(!cfg.auto_delete);
}
#[test]
fn test_multiple_create_unique_paths() {
let mgr = TempFileManager::with_defaults();
let h1 = mgr.create().expect("failed to create temp file");
let h2 = mgr.create().expect("failed to create temp file");
assert_ne!(h1.path(), h2.path());
}
/// Regression test for https://github.com/cool-japan/oximedia/issues/14.
///
/// Each `TempFileManager` previously started its internal counter at zero
/// and produced names like `oximedia_00000000`, so multiple managers
/// running in parallel raced on the same paths in the system temp
/// directory. This test spawns many threads, each constructs an
/// independent manager, and checks that every generated path is unique.
#[test]
fn test_issue_14_concurrent_unique_filenames() {
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::thread;
const THREADS: usize = 16;
const FILES_PER_THREAD: usize = 64;
let collected: Arc<Mutex<Vec<TempFileHandle>>> = Arc::new(Mutex::new(Vec::new()));
let paths: Arc<Mutex<HashSet<PathBuf>>> = Arc::new(Mutex::new(HashSet::new()));
let mut handles = Vec::with_capacity(THREADS);
for _ in 0..THREADS {
let collected = Arc::clone(&collected);
let paths = Arc::clone(&paths);
handles.push(thread::spawn(move || {
// A fresh manager per thread mirrors how parallel tests use it.
let mgr = TempFileManager::with_defaults();
let mut local = Vec::with_capacity(FILES_PER_THREAD);
for _ in 0..FILES_PER_THREAD {
let h = mgr.create().expect("failed to create temp file");
paths
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(h.path().to_path_buf());
local.push(h);
}
// Defer cleanup until after the assertion so the on-disk
// representation is also unique while we measure.
collected
.lock()
.unwrap_or_else(|e| e.into_inner())
.extend(local);
}));
}
for h in handles {
h.join().expect("worker thread panicked");
}
let unique = paths.lock().unwrap_or_else(|e| e.into_inner()).len();
assert_eq!(
unique,
THREADS * FILES_PER_THREAD,
"TempFileManager produced colliding filenames across parallel managers"
);
// Handles drop here, removing every file thanks to auto_delete.
}
/// Two managers constructed back-to-back on the same thread must still
/// emit distinct names, even for their first allocation. This is the
/// exact scenario that broke `test_explicit_remove` in issue #14.
#[test]
fn test_issue_14_distinct_managers_first_name_differs() {
let mgr_a = TempFileManager::with_defaults();
let mgr_b = TempFileManager::with_defaults();
let a = mgr_a.create().expect("failed to create temp file");
let b = mgr_b.create().expect("failed to create temp file");
assert_ne!(
a.path(),
b.path(),
"fresh managers must not collide on first-allocated filename"
);
}
}