local-store 0.2.0

Local storage primitives: platform-agnostic paths, atomic file/dir storage, atomic IO, format dispatch
Documentation
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
//! Atomic file I/O helpers shared across storage types.
//!
//! Provides `get_temp_path`, `atomic_rename`, and `cleanup_temp_files` as
//! free functions so that `FileStorage`, `DirStorage`, and `AsyncDirStorage`
//! can all delegate to a single implementation instead of duplicating the
//! logic in each `impl` block.

use crate::errors::{IoOperationKind, StoreError};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

/// Per-process monotonic counter appended to temporary file names so that
/// concurrent writers inside one process never share a temporary path.
static TMP_SEQ: AtomicU64 = AtomicU64::new(0);

/// Minimum age before an orphaned temporary file is removed by
/// [`cleanup_temp_files`].
///
/// Files younger than this are considered potentially in-flight (another
/// thread or process may still be writing them) and are left untouched.
pub const TMP_CLEANUP_MIN_AGE: Duration = Duration::from_secs(60);

/// Compute the path to a unique temporary file for `target_path`.
///
/// The temporary file is placed in the same directory as `target_path` so
/// that the subsequent rename stays on the same filesystem.
///
/// Format: `<parent>/.<filename>.tmp.<pid>-<seq>`
///
/// `<seq>` is a per-process monotonic counter, so concurrent writers in the
/// same process each get a distinct temporary file.
///
/// # Errors
///
/// `StoreError::IoError` if `target_path` has no parent directory or no
/// file-name component.
pub fn get_temp_path(target_path: &Path) -> Result<PathBuf, StoreError> {
    let parent = target_path.parent().ok_or_else(|| StoreError::IoError {
        operation: IoOperationKind::Create,
        path: target_path.display().to_string(),
        context: Some("path has no parent directory".to_string()),
        error: "cannot determine parent for temporary file".to_string(),
    })?;

    let file_name = target_path.file_name().ok_or_else(|| StoreError::IoError {
        operation: IoOperationKind::Create,
        path: target_path.display().to_string(),
        context: Some("path has no file name".to_string()),
        error: "cannot determine filename for temporary file".to_string(),
    })?;

    let tmp_name = format!(
        ".{}.tmp.{}-{}",
        file_name.to_string_lossy(),
        std::process::id(),
        TMP_SEQ.fetch_add(1, Ordering::Relaxed)
    );
    Ok(parent.join(tmp_name))
}

/// Fsync the parent directory of `target_path` so that a preceding rename is
/// durable across power loss (POSIX requires a directory fsync to persist
/// directory-entry changes).
///
/// No-op on non-Unix platforms, where directory handles cannot be synced the
/// same way.
///
/// # Errors
///
/// `StoreError::IoError { operation: Sync, … }` if the directory cannot be
/// opened or synced.
pub fn sync_parent_dir(target_path: &Path) -> Result<(), StoreError> {
    #[cfg(unix)]
    if let Some(parent) = target_path.parent() {
        if !parent.as_os_str().is_empty() {
            let map_err = |e: std::io::Error| StoreError::IoError {
                operation: IoOperationKind::Sync,
                path: parent.display().to_string(),
                context: Some("parent directory".to_string()),
                error: e.to_string(),
            };
            let dir = std::fs::File::open(parent).map_err(map_err)?;
            dir.sync_all().map_err(map_err)?;
        }
    }
    #[cfg(not(unix))]
    let _ = target_path;
    Ok(())
}

/// Rename `tmp_path` to `target_path` atomically, retrying up to
/// `retry_count` times with a 10 ms delay between attempts.
///
/// # Errors
///
/// `StoreError::IoError { operation: Rename, … }` after all retries are
/// exhausted.
pub fn atomic_rename(
    tmp_path: &Path,
    target_path: &Path,
    retry_count: usize,
) -> Result<(), StoreError> {
    let mut last_error = None;

    for attempt in 0..retry_count {
        match std::fs::rename(tmp_path, target_path) {
            Ok(()) => return Ok(()),
            Err(e) => {
                last_error = Some(e);
                if attempt + 1 < retry_count {
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
            }
        }
    }

    Err(StoreError::IoError {
        operation: IoOperationKind::Rename,
        path: target_path.display().to_string(),
        context: Some(format!("after {} retries", retry_count)),
        error: last_error
            .map(|e| e.to_string())
            .unwrap_or_else(|| "unknown error after retries".to_string()),
    })
}

/// Remove orphaned `.<filename>.tmp.*` files in the same directory as
/// `target_path`.
///
/// Only files older than [`TMP_CLEANUP_MIN_AGE`] are removed: a younger file
/// may belong to a concurrent writer (another thread or process) that has not
/// yet renamed it into place.
///
/// Errors are silently ignored (best-effort cleanup).
pub fn cleanup_temp_files(target_path: &Path) -> std::io::Result<()> {
    cleanup_temp_files_with_min_age(target_path, TMP_CLEANUP_MIN_AGE)
}

/// [`cleanup_temp_files`] with an explicit minimum age threshold.
///
/// Files whose modification time is younger than `min_age` (or cannot be
/// determined) are left untouched.
///
/// Errors are silently ignored (best-effort cleanup).
pub fn cleanup_temp_files_with_min_age(
    target_path: &Path,
    min_age: Duration,
) -> std::io::Result<()> {
    let parent = match target_path.parent() {
        Some(p) => p,
        None => return Ok(()),
    };

    let file_name = match target_path.file_name() {
        Some(f) => f.to_string_lossy().into_owned(),
        None => return Ok(()),
    };

    let prefix = format!(".{}.tmp.", file_name);

    if let Ok(entries) = std::fs::read_dir(parent) {
        for entry in entries.flatten() {
            if let Ok(name) = entry.file_name().into_string() {
                if name.starts_with(&prefix) && is_older_than(&entry.path(), min_age) {
                    let _ = std::fs::remove_file(entry.path());
                }
            }
        }
    }

    Ok(())
}

/// Best-effort check that a file's mtime is at least `min_age` in the past.
///
/// Returns `false` when metadata or mtime is unavailable, or when the mtime
/// lies in the future — deleting is skipped in all uncertain cases.
fn is_older_than(path: &Path, min_age: Duration) -> bool {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|mtime| mtime.elapsed().ok())
        .map(|age| age >= min_age)
        .unwrap_or(false)
}

// ============================================================================
// Async variants
// ============================================================================

#[cfg(feature = "async")]
pub mod async_io {
    //! Async variants of the atomic I/O helpers.
    //!
    //! `get_temp_path` is synchronous and shared with the sync module;
    //! call `super::get_temp_path(target_path)` from async callers.

    use crate::errors::{IoOperationKind, StoreError};
    use std::path::Path;

    /// Rename `tmp_path` to `target_path` atomically (async), retrying up to
    /// `retry_count` times with a 10 ms `tokio::time::sleep` between attempts.
    ///
    /// # Errors
    ///
    /// `StoreError::IoError { operation: Rename, … }` after all retries are
    /// exhausted.
    pub async fn atomic_rename(
        tmp_path: &Path,
        target_path: &Path,
        retry_count: usize,
    ) -> Result<(), StoreError> {
        let mut last_error = None;

        for attempt in 0..retry_count {
            match tokio::fs::rename(tmp_path, target_path).await {
                Ok(()) => return Ok(()),
                Err(e) => {
                    last_error = Some(e);
                    if attempt + 1 < retry_count {
                        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
                    }
                }
            }
        }

        Err(StoreError::IoError {
            operation: IoOperationKind::Rename,
            path: target_path.display().to_string(),
            context: Some(format!("after {} retries (async)", retry_count)),
            error: last_error
                .map(|e| e.to_string())
                .unwrap_or_else(|| "unknown error after retries".to_string()),
        })
    }

    /// Remove orphaned `.<filename>.tmp.*` files in the same directory as
    /// `target_path` (async).
    ///
    /// Only files older than [`super::TMP_CLEANUP_MIN_AGE`] are removed: a
    /// younger file may belong to a concurrent writer (another thread or
    /// process) that has not yet renamed it into place.
    ///
    /// Errors are silently ignored (best-effort cleanup).
    pub async fn cleanup_temp_files(target_path: &Path) -> std::io::Result<()> {
        cleanup_temp_files_with_min_age(target_path, super::TMP_CLEANUP_MIN_AGE).await
    }

    /// [`cleanup_temp_files`] with an explicit minimum age threshold (async).
    ///
    /// Files whose modification time is younger than `min_age` (or cannot be
    /// determined) are left untouched.
    ///
    /// Errors are silently ignored (best-effort cleanup).
    pub async fn cleanup_temp_files_with_min_age(
        target_path: &Path,
        min_age: std::time::Duration,
    ) -> std::io::Result<()> {
        let parent = match target_path.parent() {
            Some(p) => p,
            None => return Ok(()),
        };

        let file_name = match target_path.file_name() {
            Some(f) => f.to_string_lossy().into_owned(),
            None => return Ok(()),
        };

        let prefix = format!(".{}.tmp.", file_name);

        let mut entries = match tokio::fs::read_dir(parent).await {
            Ok(e) => e,
            Err(_) => return Ok(()),
        };

        while let Ok(Some(entry)) = entries.next_entry().await {
            if let Ok(name) = entry.file_name().into_string() {
                if name.starts_with(&prefix) && super::is_older_than(&entry.path(), min_age) {
                    let _ = tokio::fs::remove_file(entry.path()).await;
                }
            }
        }

        Ok(())
    }

    /// Fsync the parent directory of `target_path` (async) so that a
    /// preceding rename is durable across power loss.
    ///
    /// No-op on non-Unix platforms, where directory handles cannot be synced
    /// the same way.
    ///
    /// # Errors
    ///
    /// `StoreError::IoError { operation: Sync, … }` if the directory cannot
    /// be opened or synced.
    pub async fn sync_parent_dir(target_path: &Path) -> Result<(), StoreError> {
        #[cfg(unix)]
        if let Some(parent) = target_path.parent() {
            if !parent.as_os_str().is_empty() {
                let map_err = |e: std::io::Error| StoreError::IoError {
                    operation: IoOperationKind::Sync,
                    path: parent.display().to_string(),
                    context: Some("parent directory (async)".to_string()),
                    error: e.to_string(),
                };
                let dir = tokio::fs::File::open(parent).await.map_err(map_err)?;
                dir.sync_all().await.map_err(map_err)?;
            }
        }
        #[cfg(not(unix))]
        let _ = target_path;
        Ok(())
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_get_temp_path_format() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("config.toml");
        let tmp = get_temp_path(&target).unwrap();
        let name = tmp.file_name().unwrap().to_string_lossy();
        assert!(
            name.starts_with(".config.toml.tmp."),
            "tmp name should start with .<filename>.tmp., got: {}",
            name
        );
        assert_eq!(tmp.parent().unwrap(), dir.path());
    }

    #[test]
    fn test_get_temp_path_no_parent_errors() {
        // A path with no parent (root-relative bare name has parent "").
        // Use a path that genuinely has no parent component.
        let bare = std::path::PathBuf::from("/");
        // "/" has no file_name, so this should error.
        let result = get_temp_path(&bare);
        assert!(result.is_err(), "root path should produce an error");
    }

    #[test]
    fn test_atomic_rename_success() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("src.tmp");
        let dst = dir.path().join("dst.toml");
        fs::write(&src, "data").unwrap();
        atomic_rename(&src, &dst, 3).unwrap();
        assert!(dst.exists());
        assert!(!src.exists());
        assert_eq!(fs::read_to_string(&dst).unwrap(), "data");
    }

    #[test]
    fn test_atomic_rename_fails_when_src_missing() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("nonexistent.tmp");
        let dst = dir.path().join("dst.toml");
        let result = atomic_rename(&src, &dst, 1);
        assert!(result.is_err(), "should fail when src does not exist");
        if let Err(StoreError::IoError { operation, .. }) = result {
            assert_eq!(operation, IoOperationKind::Rename);
        } else {
            panic!("expected StoreError::IoError(Rename)");
        }
    }

    #[test]
    fn test_get_temp_path_unique_per_call() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("config.toml");
        let tmp1 = get_temp_path(&target).unwrap();
        let tmp2 = get_temp_path(&target).unwrap();
        assert_ne!(
            tmp1, tmp2,
            "concurrent writers must never share a temp path"
        );
    }

    #[test]
    fn test_cleanup_temp_files_removes_matching() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("data.toml");

        let stale1 = dir.path().join(".data.toml.tmp.11111-0");
        let stale2 = dir.path().join(".data.toml.tmp.22222-0");
        let other = dir.path().join("other.toml");
        fs::write(&stale1, "s1").unwrap();
        fs::write(&stale2, "s2").unwrap();
        fs::write(&other, "keep").unwrap();

        // min_age = 0 so the freshly created files qualify as orphans.
        cleanup_temp_files_with_min_age(&target, Duration::ZERO).unwrap();

        assert!(!stale1.exists(), "stale1 should be removed");
        assert!(!stale2.exists(), "stale2 should be removed");
        assert!(other.exists(), "other.toml should be kept");
    }

    #[test]
    fn test_cleanup_temp_files_keeps_fresh_files() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("data.toml");

        // Simulates another writer's in-flight temp file.
        let in_flight = dir.path().join(".data.toml.tmp.33333-0");
        fs::write(&in_flight, "in-flight").unwrap();

        cleanup_temp_files(&target).unwrap();

        assert!(
            in_flight.exists(),
            "files younger than TMP_CLEANUP_MIN_AGE must be kept"
        );
    }

    #[test]
    fn test_cleanup_temp_files_no_matches_is_ok() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("config.toml");
        // No .tmp files — should not error.
        cleanup_temp_files(&target).unwrap();
    }
}