dua-cli 2.40.0

A tool to conveniently learn about the disk usage of directories, fast!
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
//! Parallel filesystem traversal backed by a work-stealing worker pool.
//!
//! [`walk`] yields the root first, then workers read directories and distribute newly discovered
//! subdirectories among themselves. [`Order::ParentFirst`] publishes each directory's entries
//! before scheduling its children, while [`Order::Completion`] allows descendant batches to arrive
//! first when their reads finish sooner. Sibling order is unspecified in both modes.
//!
//! The `descend` predicate controls which directories are traversed; rejected directories are
//! still yielded (but not traversed).
//! Symbolic links are reported but never followed, and filesystem errors are
//! returned as iterator items. Dropping the iterator stops and joins its workers.
//!
//! # Scheduling
//!
//! The root directory starts in a shared injector queue. Each worker takes jobs from its local
//! FIFO queue, then the injector, then other workers. Reading a directory schedules each accepted
//! child directory on the current worker and requests a worker to wake so it can steal available
//! work. A worker parks when no queue has work and is unparked when new work arrives or the walk
//! stops. The last completed job emits the finished event; dropping the iterator stops all workers,
//! unparks them, and joins their threads.

use crossbeam::deque::{Injector, Steal, Stealer, Worker};
use std::{
    ffi::OsString,
    fs::{self, FileType, Metadata},
    io,
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering},
        mpsc::{Receiver, SyncSender, sync_channel},
    },
    thread,
};

type Descend = dyn Fn(&Entry) -> bool + Send + Sync;
type Batch = io::Result<Vec<io::Result<Entry>>>;

/// Controls when entries are yielded relative to their descendants.
#[derive(Clone, Copy)]
pub enum Order {
    /// Yield entries as their parent-directory reads complete.
    Completion,
    /// Yield every parent before its descendants.
    ParentFirst,
}

/// A filesystem entry produced by [`walk`].
pub struct Entry {
    /// Number of ancestors below the walk root.
    pub depth: usize,
    /// File name relative to `parent_path`.
    pub file_name: OsString,
    /// Filesystem entry type without following symbolic links.
    pub file_type: FileType,
    /// Entry metadata, or the error encountered while reading it.
    pub metadata: io::Result<Metadata>,
    /// Path containing this entry.
    pub parent_path: Arc<Path>,
}

struct Job {
    path: Arc<Path>,
    depth: usize,
}

enum Event {
    Batch(Batch),
    Finished,
}

struct PoolShared {
    /// Global queue that makes the initial root job available to whichever worker starts first.
    injector: Injector<Job>,
    stealers: Vec<Stealer<Job>>,
    stop: AtomicBool,
    descend: Arc<Descend>,
    events: SyncSender<Event>,
    /// Number of directory jobs that are queued or running.
    pending: AtomicUsize,
    order: Order,
    threads: Mutex<Vec<thread::Thread>>,
    /// A round-robbin counter for the next thread to wake.
    next_wake: AtomicUsize,
}

struct Pool {
    shared: Arc<PoolShared>,
    handles: Vec<thread::JoinHandle<()>>,
}

/// A directory iterator whose directory reads happen in parallel.
pub struct Walk {
    /// Entries buffered for delivery.
    ///
    /// This vector is used as a stack: it starts with the root, and received batches are inserted
    /// in reverse so popping preserves their original order.
    ///
    /// If consumption isn't as fast as its production, threads will block.
    next: Vec<io::Result<Entry>>,
    /// Worker-event receiver while a directory traversal is active.
    ///
    /// It is `None` when the root is not traversed and after the finished event is received.
    events: Option<Receiver<Event>>,
    /// Owns the worker threads for as long as traversal is active.
    ///
    /// Clearing or dropping it requests shutdown, unparks every worker, and joins their threads.
    pool: Option<Pool>,
}

/// Walk `root` without following symlinks.
pub fn walk(
    root: &Path,
    threads: usize,
    order: Order,
    descend: impl Fn(&Entry) -> bool + Send + Sync + 'static,
) -> Walk {
    let threads = threads.max(1);
    let root = Entry::from_path(root);
    let mut pool = None;
    let mut events = None;

    if let Ok(entry) = &root
        && entry.file_type.is_dir()
        && descend(entry)
    {
        let (new_pool, event_rx) = start_pool(
            Job {
                path: Arc::from(entry.path()),
                depth: 1,
            },
            threads,
            order,
            Arc::new(descend),
        );
        pool = Some(new_pool);
        events = Some(event_rx);
    }

    Walk {
        next: vec![root],
        events,
        pool,
    }
}

impl Iterator for Walk {
    type Item = io::Result<Entry>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(entry) = self.next.pop() {
                return Some(entry);
            }

            match self.events.as_ref()?.recv() {
                Ok(Event::Batch(Ok(entries))) => {
                    self.next.extend(entries.into_iter().rev());
                }
                Ok(Event::Batch(Err(err))) => return Some(Err(err)),
                Ok(Event::Finished) => {
                    self.events = None;
                    self.pool = None;
                    return None;
                }
                Err(_) => return Some(Err(io::Error::other("directory worker stopped"))),
            }
        }
    }
}

impl PoolShared {
    /// Unpark one worker, selected round-robin.
    ///
    /// Selection does not exclude the caller. Unparking the current thread stores a wake token,
    /// causing its next [`thread::park`] to return immediately rather than waking a peer. This
    /// preserves correctness but may delay additional parallelism until a later call advances to
    /// another worker. Unparking an already-awake worker has the same token semantics.
    fn wake_one_worker(&self) {
        let threads = self.threads.lock().expect("worker list lock");
        if let Some(thread) =
            threads.get(self.next_wake.fetch_add(1, AtomicOrdering::Relaxed) % threads.len().max(1))
        {
            thread.unpark();
        }
    }

    fn wake_workers(&self) {
        for thread in self.threads.lock().expect("worker list lock").iter() {
            thread.unpark();
        }
    }
}

impl Entry {
    /// Return the full path to this entry.
    #[must_use]
    pub fn path(&self) -> PathBuf {
        self.parent_path.join(&self.file_name)
    }

    fn from_path(path: &Path) -> io::Result<Self> {
        let metadata = fs::symlink_metadata(path)?;
        Ok(Self {
            depth: 0,
            file_name: path.file_name().unwrap_or(path.as_os_str()).to_owned(),
            file_type: metadata.file_type(),
            metadata: Ok(metadata),
            parent_path: Arc::from(path.parent().unwrap_or(Path::new(""))),
        })
    }

    fn from_dir_entry(
        depth: usize,
        parent_path: Arc<Path>,
        entry: fs::DirEntry,
    ) -> io::Result<Self> {
        Ok(Self {
            depth,
            file_name: entry.file_name(),
            file_type: entry.file_type()?,
            metadata: entry.metadata(),
            parent_path,
        })
    }
}

fn start_pool(
    first_job: Job,
    threads: usize,
    order: Order,
    descend: Arc<Descend>,
) -> (Pool, Receiver<Event>) {
    let workers: Vec<_> = (0..threads).map(|_| Worker::new_fifo()).collect();
    let (event_tx, event_rx) = sync_channel(threads * 2);
    let shared = Arc::new(PoolShared {
        injector: Injector::new(),
        stealers: workers.iter().map(Worker::stealer).collect(),
        stop: AtomicBool::new(false),
        descend,
        events: event_tx,
        pending: AtomicUsize::new(1),
        order,
        threads: Mutex::new(Vec::with_capacity(threads)),
        next_wake: AtomicUsize::new(0),
    });
    shared.injector.push(first_job);

    let handles: Vec<_> = workers
        .into_iter()
        .enumerate()
        .map(|(idx, worker)| {
            let shared = Arc::clone(&shared);
            thread::Builder::new()
                .name(format!("dua-fs-walk-{idx}"))
                .spawn(move || worker_loop(worker, shared))
                .expect("filesystem worker thread can be spawned")
        })
        .collect();
    *shared.threads.lock().expect("worker list lock") = handles
        .iter()
        .map(|handle| handle.thread().clone())
        .collect();
    shared.wake_workers();

    (Pool { shared, handles }, event_rx)
}

fn worker_loop(worker: Worker<Job>, shared: Arc<PoolShared>) {
    while !shared.stop.load(AtomicOrdering::Relaxed) {
        if let Some(job) = find_job(&worker, &shared) {
            run_job(job, &worker, &shared);
        } else {
            thread::park();
        }
    }
}

impl Drop for Pool {
    fn drop(&mut self) {
        self.shared.stop.store(true, AtomicOrdering::Relaxed);
        self.shared.wake_workers();
        for handle in self.handles.drain(..) {
            handle.join().ok();
        }
    }
}

/// Find work in order of increasing synchronization cost.
///
/// The worker checks its own FIFO queue first, preserving local scheduling order and avoiding
/// shared-queue contention. It next takes a batch from the injector, keeping one job and moving
/// the rest into its local queue. Only then does it inspect other workers, because stealing from a
/// peer is the most contentious path. Consequently, a worker with local jobs keeps processing
/// them before helping elsewhere, and injector jobs take priority over peer jobs.
fn find_job(worker: &Worker<Job>, shared: &PoolShared) -> Option<Job> {
    loop {
        if let Some(job) = worker.pop() {
            return Some(job);
        }

        match shared.injector.steal_batch_and_pop(worker) {
            Steal::Success(job) => return Some(job),
            Steal::Retry => continue,
            Steal::Empty => {}
        }

        let mut retry = false;
        for stealer in &shared.stealers {
            match stealer.steal() {
                Steal::Success(job) => return Some(job),
                Steal::Retry => retry = true,
                Steal::Empty => {}
            }
        }
        if !retry {
            return None;
        }
    }
}

fn run_job(job: Job, worker: &Worker<Job>, shared: &PoolShared) {
    let (batch, jobs) = read_dir(&job.path, job.depth, shared);
    shared
        .pending
        .fetch_add(jobs.len(), AtomicOrdering::Relaxed);

    match shared.order {
        Order::ParentFirst => {
            if shared.events.send(Event::Batch(batch)).is_err() {
                shared.stop.store(true, AtomicOrdering::Relaxed);
                return;
            }
            schedule_jobs(jobs, worker, shared);
        }
        Order::Completion => {
            schedule_jobs(jobs, worker, shared);
            if shared.events.send(Event::Batch(batch)).is_err() {
                shared.stop.store(true, AtomicOrdering::Relaxed);
                return;
            }
        }
    }

    let only_this_thread_left = shared.pending.fetch_sub(1, AtomicOrdering::Relaxed) == 1;
    if only_this_thread_left {
        shared.events.send(Event::Finished).ok();
    }
}

fn schedule_jobs(jobs: Vec<Job>, worker: &Worker<Job>, shared: &PoolShared) {
    let has_jobs = !jobs.is_empty();
    for job in jobs {
        worker.push(job);
    }
    if has_jobs {
        shared.wake_one_worker();
    }
}

fn read_dir(path: &Arc<Path>, depth: usize, shared: &PoolShared) -> (Batch, Vec<Job>) {
    let entries = match fs::read_dir(path) {
        Ok(entries) => entries,
        Err(err) => return (Err(err), Vec::new()),
    };
    let mut jobs = Vec::new();
    let entries = entries
        .map(|entry| {
            entry
                .and_then(|entry| Entry::from_dir_entry(depth, Arc::clone(path), entry))
                .inspect(|entry| {
                    if entry.file_type.is_dir() && (shared.descend)(entry) {
                        jobs.push(Job {
                            path: Arc::from(entry.path()),
                            depth: depth + 1,
                        });
                    }
                })
        })
        .collect();
    (Ok(entries), jobs)
}

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

    #[test]
    fn parallel_walk_is_parent_first_and_does_not_follow_symlinks() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("b/child")).unwrap();
        fs::create_dir(dir.path().join("a")).unwrap();
        fs::write(dir.path().join("b/child/file"), b"x").unwrap();

        #[cfg(unix)]
        std::os::unix::fs::symlink(dir.path().join("b"), dir.path().join("link")).unwrap();

        #[cfg(unix)]
        let expected = ["", "a", "b", "b/child", "b/child/file", "link"];
        #[cfg(not(unix))]
        let expected = ["", "a", "b", "b/child", "b/child/file"];
        let expected = expected.into_iter().map(PathBuf::from).collect::<Vec<_>>();

        for threads in [1, 4] {
            let paths = walk(dir.path(), threads, Order::ParentFirst, |_| true)
                .map(|entry| {
                    entry
                        .unwrap()
                        .path()
                        .strip_prefix(dir.path())
                        .unwrap()
                        .to_owned()
                })
                .collect::<Vec<_>>();
            let mut sorted_paths = paths.clone();
            sorted_paths.sort();
            assert_eq!(
                sorted_paths, expected,
                "walk with {threads} threads should visit every expected path exactly once"
            );

            for path in paths.iter().filter(|path| path.components().count() > 1) {
                let parent = path.parent().unwrap();
                assert!(
                    paths.iter().position(|path| path == parent)
                        < paths.iter().position(|candidate| candidate == path),
                    "parent {parent:?} should precede child {path:?} with {threads} threads; \
                     traversal order: {paths:?}"
                );
            }
        }
    }

    #[test]
    fn pruning_keeps_the_directory_and_missing_roots_are_errors() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("skip/child")).unwrap();

        let paths = walk(dir.path(), 2, Order::Completion, |entry| {
            entry.file_name != "skip"
        })
        .map(|entry| entry.unwrap().file_name)
        .collect::<Vec<_>>();
        assert_eq!(
            paths,
            vec![
                dir.path().file_name().unwrap().to_owned(),
                OsString::from("skip")
            ],
            "a pruned directory should be yielded without traversing its children"
        );

        assert!(
            walk(&dir.path().join("missing"), 2, Order::Completion, |_| true)
                .next()
                .unwrap()
                .is_err(),
            "a missing root should be yielded as an I/O error"
        );
    }
}