object-log 0.3.4

A buffered, multiplexing append log over pluggable object storage, with a sequencing seam (opaque payloads, durable-on-return writes, group-commit).
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
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! The object-storage port and the bundled adapters.

use crate::ObjectLogError;
use async_trait::async_trait;
use bytes::{Bytes, BytesMut};
use std::collections::BTreeMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::Range;
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Instant, SystemTime, UNIX_EPOCH};

/// Result of [`BlobStore::compare_and_swap`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CasOutcome {
    /// `new_value` is now the object's contents.
    Stored,
    /// The object did not match `expected`. `current` is the value observed
    /// after the failed update (`None` if the key is absent).
    Conflict {
        /// Bytes present after the rejected update.
        current: Option<Bytes>,
    },
}

/// Durable-media accounting for the flush budget controller (TD-004).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MediaOpStats {
    /// File/dir fsyncs or billable durable requests performed since last take.
    pub media_ops: u64,
    /// Bytes written through durable (or memory) put paths since last take.
    pub bytes: u64,
}

/// Suffix for in-flight temp files written by [`LocalBlobStore`]; keys ending in
/// it are skipped by [`list`](BlobStore::list).
const TMP_SUFFIX: &str = ".olog-tmp";

fn diagnostic_unix_us() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_micros()
}

fn object_class(key: &str) -> &'static str {
    if key.starts_with("fwlog/") {
        "segment"
    } else if key.starts_with("fwmeta/manifest/") {
        "manifest"
    } else {
        "metadata"
    }
}

/// Physical store join id for opt-in publication traces.
///
/// Workload stores live at `shard-N/{log,projection.db}`. Object keys and
/// queue ids are shared across those physical stores.
fn diagnostic_store_tag(path: &Path) -> String {
    let mut fallback = None;
    for component in path.components() {
        let name = component.as_os_str().to_string_lossy();
        if let Some(rest) = name.strip_prefix("shard-")
            && !rest.is_empty()
            && rest.bytes().all(|b| b.is_ascii_digit())
        {
            return name.into_owned();
        }
        if !matches!(
            name.as_ref(),
            "log" | "fwlog" | "fwmeta" | "manifest" | "projection.db" | "/" | "."
        ) {
            fallback = Some(name.into_owned());
        }
    }
    fallback
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| "unknown".into())
}

/// A minimal async object store over immutable, string-keyed blobs.
///
/// This is the storage *port* the log engine is built on. Implement it for your
/// backend (e.g. S3) to store the log there. Data objects are written once under
/// a unique key. Partition index objects use
/// [`compare_and_swap`](BlobStore::compare_and_swap).
///
/// Durability: [`put`](BlobStore::put) is **durable-on-return** for crash-durable
/// adapters ([`LocalBlobStore`], an S3 adapter) — once it resolves `Ok`, the bytes
/// survive a crash, so a caller may treat `Ok` as a durability barrier.
/// [`MemoryBlobStore`] is a test/dev backend and is **not** crash-durable.
#[async_trait]
pub trait BlobStore: Send + Sync {
    /// Durably store `value` at `key` (see the trait-level durability note).
    /// `value` may be arbitrarily large; a network adapter should chunk it
    /// (e.g. S3 multipart) rather than rely on a single request.
    async fn put(&self, key: &str, value: Bytes) -> Result<(), ObjectLogError>;

    /// Durably store a logical object assembled from immutable byte chunks.
    ///
    /// The default implementation concatenates chunks and delegates to
    /// [`put`](BlobStore::put). Object-store adapters can override this to stream
    /// or multipart-upload chunks without materializing the full object twice.
    async fn put_chunks(&self, key: &str, chunks: Vec<Bytes>) -> Result<(), ObjectLogError> {
        match chunks.len() {
            0 => self.put(key, Bytes::new()).await,
            1 => self.put(key, chunks.into_iter().next().unwrap()).await,
            _ => {
                let total = chunks.iter().map(Bytes::len).sum();
                let mut value = BytesMut::with_capacity(total);
                for chunk in chunks {
                    value.extend_from_slice(&chunk);
                }
                self.put(key, value.freeze()).await
            }
        }
    }

    /// Fetch the whole object at `key`, or `None` if absent.
    async fn get(&self, key: &str) -> Result<Option<Bytes>, ObjectLogError>;

    /// Read a byte sub-range of an object without fetching the whole thing.
    /// `None` if the key is absent. `range.end > len` or `range.start > range.end`
    /// is [`ObjectLogError::RangeOutOfBounds`]; an empty `n..n` returns
    /// `Ok(Some(<empty>))`. No integrity check is performed — payloads are opaque.
    async fn get_range(
        &self,
        key: &str,
        range: Range<u64>,
    ) -> Result<Option<Bytes>, ObjectLogError>;

    /// List keys beginning with `prefix`.
    async fn list(&self, prefix: &str) -> Result<Vec<String>, ObjectLogError>;

    /// Delete an object; deleting a missing key is a no-op success.
    async fn delete(&self, key: &str) -> Result<(), ObjectLogError>;

    /// Replace `key` only when its current bytes equal `expected`.
    ///
    /// `expected == None` succeeds only when the key is absent (create-only).
    /// The default reads and then [`put`](BlobStore::put)s, which is not atomic
    /// across processes. [`MemoryBlobStore`], [`LocalBlobStore`], and the S3
    /// adapter override it with a real conditional update.
    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<Bytes>,
        new_value: Bytes,
    ) -> Result<CasOutcome, ObjectLogError> {
        let current = self.get(key).await?;
        let matches = match (&expected, &current) {
            (None, None) => true,
            (Some(expected), Some(current)) => expected == current,
            _ => false,
        };
        if !matches {
            return Ok(CasOutcome::Conflict { current });
        }
        self.put(key, new_value).await?;
        Ok(CasOutcome::Stored)
    }

    /// Snapshot and reset media-op counters since the previous take.
    ///
    /// Adapters that can count exact durable units (fsyncs, S3 PUTs) should
    /// implement this. The default returns [`None`]; the engine then treats each
    /// successful [`put`](BlobStore::put) / [`put_chunks`](BlobStore::put_chunks)
    /// as **one** media op (documented fallback).
    fn take_media_op_stats(&self) -> Option<MediaOpStats> {
        None
    }
}

/// Slice `bytes` by `range`, applying the [`BlobStore::get_range`] bounds rules.
fn slice_range(bytes: &Bytes, range: Range<u64>) -> Result<Bytes, ObjectLogError> {
    if range.start > range.end {
        return Err(ObjectLogError::RangeOutOfBounds(format!(
            "start {} > end {}",
            range.start, range.end
        )));
    }
    let len = bytes.len() as u64;
    if range.end > len {
        return Err(ObjectLogError::RangeOutOfBounds(format!(
            "end {} > len {len}",
            range.end
        )));
    }
    Ok(bytes.slice(range.start as usize..range.end as usize))
}

/// In-process [`BlobStore`] backed by a map. For tests and development; state is
/// lost on drop and is **not** crash-durable.
#[derive(Clone, Default)]
pub struct MemoryBlobStore {
    objects: Arc<Mutex<BTreeMap<String, Bytes>>>,
    bytes_written: Arc<AtomicU64>,
}

impl MemoryBlobStore {
    /// Create an empty store.
    pub fn new() -> Self {
        Self::default()
    }

    /// Number of stored objects (lets tests assert PUT-count / cost invariants).
    pub fn object_count(&self) -> usize {
        self.objects.lock().expect("poisoned").len()
    }

    /// Total stored bytes across all objects.
    pub fn total_bytes(&self) -> usize {
        self.objects
            .lock()
            .expect("poisoned")
            .values()
            .map(|v| v.len())
            .sum()
    }
}

#[async_trait]
impl BlobStore for MemoryBlobStore {
    async fn put(&self, key: &str, value: Bytes) -> Result<(), ObjectLogError> {
        self.bytes_written
            .fetch_add(value.len() as u64, Ordering::Relaxed);
        self.objects
            .lock()
            .expect("poisoned")
            .insert(key.to_string(), value);
        Ok(())
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<Bytes>,
        new_value: Bytes,
    ) -> Result<CasOutcome, ObjectLogError> {
        let mut objects = self.objects.lock().expect("poisoned");
        let current = objects.get(key).cloned();
        let matches = match (&expected, &current) {
            (None, None) => true,
            (Some(expected), Some(current)) => expected == current,
            _ => false,
        };
        if !matches {
            return Ok(CasOutcome::Conflict { current });
        }
        self.bytes_written
            .fetch_add(new_value.len() as u64, Ordering::Relaxed);
        objects.insert(key.to_string(), new_value);
        Ok(CasOutcome::Stored)
    }

    async fn get(&self, key: &str) -> Result<Option<Bytes>, ObjectLogError> {
        Ok(self.objects.lock().expect("poisoned").get(key).cloned())
    }

    async fn get_range(
        &self,
        key: &str,
        range: Range<u64>,
    ) -> Result<Option<Bytes>, ObjectLogError> {
        let object = self.objects.lock().expect("poisoned").get(key).cloned();
        match object {
            Some(bytes) => Ok(Some(slice_range(&bytes, range)?)),
            None => Ok(None),
        }
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>, ObjectLogError> {
        Ok(self
            .objects
            .lock()
            .expect("poisoned")
            .keys()
            .filter(|k| k.starts_with(prefix))
            .cloned()
            .collect())
    }

    async fn delete(&self, key: &str) -> Result<(), ObjectLogError> {
        self.objects.lock().expect("poisoned").remove(key);
        Ok(())
    }

    fn take_media_op_stats(&self) -> Option<MediaOpStats> {
        // Memory has no crash-durable media cost.
        Some(MediaOpStats {
            media_ops: 0,
            bytes: self.bytes_written.swap(0, Ordering::Relaxed),
        })
    }
}

/// Filesystem-backed [`BlobStore`] rooted at a directory.
///
/// Single-node. Writes are **durable-on-return**: each `put` / `put_chunks`:
/// 1. write a temp file in the same directory as the final key  
/// 2. [`std::fs::File::sync_data`] (fdatasync on Unix) so payload bytes are durable  
/// 3. `rename` into place  
/// 4. `fsync` the parent directory so the directory entry survives power loss  
///
/// (On macOS, true device durability may need `F_FULLFSYNC`; Linux `sync_data` /
/// dir `sync_all` is the intended contract.)
#[derive(Clone)]
pub struct LocalBlobStore {
    root: Arc<PathBuf>,
    media_ops: Arc<AtomicU64>,
    bytes_written: Arc<AtomicU64>,
}

impl LocalBlobStore {
    /// Create a store rooted at `root` (created lazily on first write).
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: Arc::new(root.into()),
            media_ops: Arc::new(AtomicU64::new(0)),
            bytes_written: Arc::new(AtomicU64::new(0)),
        }
    }

    fn path_for(&self, key: &str) -> Result<PathBuf, ObjectLogError> {
        if key.is_empty() || key.contains('\0') || key.split('/').any(|p| p == "..") {
            return Err(ObjectLogError::InvalidObjectKey(key.to_string()));
        }
        Ok(self.root.join(key))
    }

    /// Durable publish: temp → sync_data → rename → dir fsync. No full pre-merge
    /// of `chunks` (streams them to the temp file).
    fn durable_publish_chunks(
        path: PathBuf,
        chunks: Vec<Bytes>,
        key: &str,
    ) -> std::io::Result<u64> {
        // Opt-in diagnostic only: preserve the exact publication operations and
        // ordering. No paths or payloads are emitted. Failed puts remain errors;
        // phase records below describe successful publications only.
        static TRACE: OnceLock<bool> = OnceLock::new();
        let trace =
            *TRACE.get_or_init(|| std::env::var_os("OBJECT_LOG_LOCAL_PUBLISH_TRACE").is_some());
        let started = trace.then(Instant::now);
        let started_unix_us = trace.then(diagnostic_unix_us);
        let mut phase = started;
        let mut elapsed = || {
            phase.map_or(0, |before| {
                let now = Instant::now();
                phase = Some(now);
                now.duration_since(before).as_micros()
            })
        };
        let parent = path.parent().expect("object path has a parent");
        std::fs::create_dir_all(parent)?;
        let mkdir_us = elapsed();
        let mut tmp = path.clone().into_os_string();
        tmp.push(TMP_SUFFIX);
        let tmp = PathBuf::from(tmp);
        let mut byte_len = 0u64;
        let (create_us, write_us, data_sync_us);
        {
            let mut f = std::fs::File::create(&tmp)?;
            create_us = elapsed();
            for chunk in &chunks {
                f.write_all(chunk)?;
                byte_len += chunk.len() as u64;
            }
            write_us = elapsed();
            // fdatasync on Unix: data durable; dir fsync below covers the name.
            f.sync_data()?;
            data_sync_us = elapsed();
        }
        std::fs::rename(&tmp, &path)?;
        let rename_us = elapsed(); // Includes closing the data file.
        let directory = std::fs::File::open(parent)?;
        let dir_open_us = elapsed();
        directory.sync_all()?;
        let dir_sync_us = elapsed();
        if let (Some(started), Some(started_unix_us)) = (started, started_unix_us) {
            eprintln!(
                "local_publish bytes={byte_len} mkdir_us={mkdir_us} create_us={create_us} write_us={write_us} data_sync_us={data_sync_us} rename_us={rename_us} dir_open_us={dir_open_us} dir_sync_us={dir_sync_us} total_us={} class={} store={} started_unix_us={started_unix_us}",
                started.elapsed().as_micros(),
                object_class(key),
                diagnostic_store_tag(&path),
            );
        }
        Ok(byte_len)
    }

    fn record_put(&self, byte_len: u64) {
        // Two media ops: file data sync + parent directory sync.
        self.media_ops.fetch_add(2, Ordering::Relaxed);
        self.bytes_written.fetch_add(byte_len, Ordering::Relaxed);
    }

    async fn publish_async(
        &self,
        path: PathBuf,
        chunks: Vec<Bytes>,
        key: String,
    ) -> Result<u64, ObjectLogError> {
        let run = move || {
            Self::durable_publish_chunks(path, chunks, &key)
                .map_err(|e| ObjectLogError::StorageUnavailable(e.to_string()))
        };
        match tokio::runtime::Handle::try_current() {
            // Multi-thread worker: avoid spawn_blocking queue (flush path uses this).
            Ok(h) if h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
                tokio::task::block_in_place(run)
            }
            // Current-thread runtime (many unit tests): must not block_in_place.
            Ok(_) => tokio::task::spawn_blocking(run)
                .await
                .map_err(|e| ObjectLogError::StorageUnavailable(e.to_string()))?,
            Err(_) => run(),
        }
    }
}

#[async_trait]
impl BlobStore for LocalBlobStore {
    async fn put(&self, key: &str, value: Bytes) -> Result<(), ObjectLogError> {
        let path = self.path_for(key)?;
        let byte_len = self
            .publish_async(path, vec![value], key.to_string())
            .await?;
        self.record_put(byte_len);
        Ok(())
    }

    async fn put_chunks(&self, key: &str, chunks: Vec<Bytes>) -> Result<(), ObjectLogError> {
        match chunks.len() {
            0 => self.put(key, Bytes::new()).await,
            1 => self.put(key, chunks.into_iter().next().unwrap()).await,
            _ => {
                let path = self.path_for(key)?;
                let byte_len = self.publish_async(path, chunks, key.to_string()).await?;
                self.record_put(byte_len);
                Ok(())
            }
        }
    }

    async fn get(&self, key: &str) -> Result<Option<Bytes>, ObjectLogError> {
        let path = self.path_for(key)?;
        match tokio::fs::read(&path).await {
            Ok(v) => Ok(Some(Bytes::from(v))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    async fn get_range(
        &self,
        key: &str,
        range: Range<u64>,
    ) -> Result<Option<Bytes>, ObjectLogError> {
        if range.start > range.end {
            return Err(ObjectLogError::RangeOutOfBounds(format!(
                "start {} > end {}",
                range.start, range.end
            )));
        }
        let path = self.path_for(key)?;
        tokio::task::spawn_blocking(move || -> Result<Option<Bytes>, ObjectLogError> {
            let mut f = match std::fs::File::open(&path) {
                Ok(f) => f,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
                Err(e) => return Err(e.into()),
            };
            let len = f.metadata()?.len();
            if range.end > len {
                return Err(ObjectLogError::RangeOutOfBounds(format!(
                    "end {} > len {len}",
                    range.end
                )));
            }
            let count = (range.end - range.start) as usize;
            let mut buf = vec![0u8; count];
            f.seek(SeekFrom::Start(range.start))?;
            f.read_exact(&mut buf)?;
            Ok(Some(Bytes::from(buf)))
        })
        .await
        .map_err(|e| ObjectLogError::StorageUnavailable(e.to_string()))?
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>, ObjectLogError> {
        let root = self.root.clone();
        let prefix = prefix.to_string();
        let keys = tokio::task::spawn_blocking(move || -> std::io::Result<Vec<String>> {
            let mut out = Vec::new();
            collect_files(&root, &root, &mut out)?;
            Ok(out)
        })
        .await
        .map_err(|e| ObjectLogError::StorageUnavailable(e.to_string()))??;
        Ok(keys
            .into_iter()
            .filter(|k| k.starts_with(&prefix))
            .collect())
    }

    async fn delete(&self, key: &str) -> Result<(), ObjectLogError> {
        let path = self.path_for(key)?;
        match tokio::fs::remove_file(&path).await {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e.into()),
        }
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<Bytes>,
        new_value: Bytes,
    ) -> Result<CasOutcome, ObjectLogError> {
        let path = self.path_for(key)?;
        let key = key.to_string();
        let byte_len = new_value.len() as u64;
        let outcome = tokio::task::spawn_blocking(move || {
            local_compare_and_swap(&path, &key, expected, new_value)
        })
        .await
        .map_err(|e| ObjectLogError::StorageUnavailable(e.to_string()))??;
        if matches!(outcome, CasOutcome::Stored) {
            self.record_put(byte_len);
        }
        Ok(outcome)
    }

    fn take_media_op_stats(&self) -> Option<MediaOpStats> {
        Some(MediaOpStats {
            media_ops: self.media_ops.swap(0, Ordering::Relaxed),
            bytes: self.bytes_written.swap(0, Ordering::Relaxed),
        })
    }
}

fn local_compare_and_swap(
    path: &Path,
    key: &str,
    expected: Option<Bytes>,
    new_value: Bytes,
) -> Result<CasOutcome, ObjectLogError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut lock_name = path.as_os_str().to_os_string();
    lock_name.push(".caslock");
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(lock_name)?;
    flock_exclusive(&lock)?;
    let current = match std::fs::read(path) {
        Ok(bytes) => Some(Bytes::from(bytes)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => {
            let _ = flock_unlock(&lock);
            return Err(error.into());
        }
    };
    let matches = match (&expected, &current) {
        (None, None) => true,
        (Some(expected), Some(current)) => expected == current,
        _ => false,
    };
    if !matches {
        let _ = flock_unlock(&lock);
        return Ok(CasOutcome::Conflict { current });
    }
    let published =
        LocalBlobStore::durable_publish_chunks(path.to_path_buf(), vec![new_value], key);
    let _ = flock_unlock(&lock);
    published?;
    Ok(CasOutcome::Stored)
}

fn flock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
    let rc = unsafe { flock(file.as_raw_fd(), 2) };
    if rc == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

fn flock_unlock(file: &std::fs::File) -> std::io::Result<()> {
    let rc = unsafe { flock(file.as_raw_fd(), 8) };
    if rc == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

unsafe extern "C" {
    fn flock(fd: i32, operation: i32) -> i32;
}

fn collect_files(root: &Path, dir: &Path, out: &mut Vec<String>) -> std::io::Result<()> {
    if !dir.exists() {
        return Ok(());
    }
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_files(root, &path, out)?;
        } else if !path.to_string_lossy().ends_with(TMP_SUFFIX)
            && !path.to_string_lossy().ends_with(".caslock")
            && let Ok(rel) = path.strip_prefix(root)
        {
            out.push(rel.to_string_lossy().replace('\\', "/"));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn diagnostic_store_tag_prefers_workload_shard_directory() {
        assert_eq!(
            diagnostic_store_tag(Path::new(
                "/tmp/run/shard-12/log/fwlog/00000000000000000001"
            )),
            "shard-12"
        );
        assert_eq!(
            diagnostic_store_tag(Path::new("/data/shard-0/projection.db")),
            "shard-0"
        );
        assert_eq!(object_class("fwlog/1"), "segment");
        assert_eq!(object_class("fwmeta/manifest/1"), "manifest");
        assert_eq!(object_class("fwmeta/high-water/1"), "metadata");
    }
}