Scandir: Incremental directory scanning in Elixir
H's Workspace picker can show folders before it checks them for a .git marker. A small Rust NIF gives the Elixir worker control over when to read more.
- Published
- Reading time
- 9 min read
I wrote Scandir for the Workspace picker in H, the coding harness I develop in my diy-harness checkout. I wanted to open a directory, see the first folders as soon as they were available, and click into one while the picker was still filling in details about its siblings. Finding a .git marker in one folder should not have to finish before I can open another one.
File.ls/1 returns a complete list. Wrapping that list in an Elixir Stream makes the filtering lazy, but the filesystem work has already happened by then. Checking each child for metadata adds another wait. The picker can use the first few names well before either job is finished. I wanted to keep one directory stream open, read a small batch of entries, and let the Elixir worker decide whether to read again. That cursor became Scandir. H kept the decisions about what to show and when.
The directory cursor
Scandir wraps three libc functions with Rustler. Scandir.open/1 calls opendir and puts the resulting directory stream in a BEAM resource. Scandir.next/2 advances the same stream with readdir. Scandir.close/1 calls closedir. A worker can stop after one batch or pull successive batches to the end without reopening the directory.
The second argument to next/2 is a visit budget between 1 and 128. H asks for 64. The entries . and .. count toward that budget even though Scandir omits them from the result. With a budget of one, a call that visits . can return {:ok, [], :more}. A call that uses its entire budget on the last entry also returns :more. Scandir does not read ahead to find out whether the next call will hit EOF.
A consumer stops on :eof or when it has enough results. An empty batch alone is no reason to stop. The NIF clears errno before each readdir call so it can tell EOF from an error when libc returns a null pointer. A failed batch can have advanced the stream without returning the entries it already read. EOF stays latched, but it leaves the descriptor open, so the worker still closes it in an after clause.
Each result is a pair of raw filename bytes and an entry type. readdir can reuse its buffer on the next call, so the NIF copies the name into a BEAM binary before advancing. It reads the type from d_type when the filesystem provides it and reports :unknown otherwise. The NIF does not stat children, follow child symlinks, sort entries, or recurse. If someone changes the directory during a scan, the listing can reflect those changes. The cursor gives the worker a position in a live stream, not a snapshot to resume later.
The API keeps those limitations visible. A Linux filename can contain invalid UTF-8, and repairing it in the NIF would change the bytes needed to open it. H’s picker skips names it cannot represent as UTF-8 and marks the result partial. Another caller could keep the original bytes for filesystem access and use a separate display label.
The Workspace picker
Suppose I open a directory that contains project-1 alongside a few hundred other checkouts and loose files. H keeps the previous listing on screen until the new directory has opened. When a batch identifies project-1 as a directory, the worker can send a row with the path and session counts from H’s catalog. Its project markers are still empty. The view merges rows by path and sorts what it has received so far.
This is what I mean by optimistic scanning. I can open project-1 as soon as its row appears. If I stay on the listing, a later pass can find project-1/.git and update that same row. H also uses this pass to check unknown entries and symlinks. On a filesystem that never supplies entry types, the first pass has less to show because H needs those follow-up checks to find the directories. On macOS, the picker skips automatic probes of known protected home folders. Listing the parent need not trigger a child access just to look for a project marker.
The scan worker keeps the cursor and sends one data frame at a time. It waits for the consumer to accept that frame before producing another. If I click into project-1 while its siblings are still arriving, the view starts a new request and drops frames tagged with the old request reference. The cursor stays in the daemon. The in-VM client and the HTTP adapter use the same scan; HTTP sends only the result frames as newline-delimited JSON. Non-local execution environments still use the snapshot listing.
H also needs limits across batches. The local picker budgets for 100,000 visits and 5,000 rows, with 2 MB for names and paths and up to 10,000 entries set aside for metadata checks. The picker counts the visit budget it asks for, so the total is a conservative bound. Without a separate metadata limit, a directory where every entry reports :unknown could build a large backlog even though every native call returns at most 64 entries. The worker has a five-second scan budget that it checks between operations. It can return a partial listing when it reaches a limit. These policies belong in H because another caller might want every name and have no use for project markers.
Dirty I/O and cancellation
The opendir, readdir, and closedir calls run on BEAM dirty I/O schedulers and bypass OTP’s shared file server. The worker that calls the NIF still waits for it to return. A batch of 64 bounds the number of readdir calls inside that batch. It says nothing about how long one call can wait on a stalled mount or a macOS permission prompt.
That distinction decides when H can admit another scan. H allows up to four Workspace workers and reduces that number on a VM with fewer dirty I/O schedulers, leaving at least one outside the picker pool’s allowance. Other I/O still shares those schedulers. If the browser disconnects while a worker is stuck in readdir, H can stop asking for results, but it cannot interrupt the native call. The worker keeps its place in the pool until the call returns and cleanup finishes. Giving that place to a new scan when the browser stops waiting would let repeated navigation pile up blocked calls.
One integration test pauses the worker before its second read and checks that the consumer already has the first batch. Another pauses the worker before opendir, disconnects the consumer, and checks that the pool still counts the worker. Both tests simulate the wait with an injected scanner.
Scandir has a separate limit of 32 native slots. It reserves one before opendir and releases it after a failed open or once closedir returns. A closing stream or one awaiting cleanup still holds a slot. The cap limits how many streams the NIF can have open or in progress. An Elixir caller can already be queued for dirty I/O before the NIF checks that cap, which is why H needs admission control of its own. Within a cursor, a try-lock makes an overlapping read or close return :busy rather than wait for another operation on that stream. Once close finishes, a second close is a no-op. Scandir never retries closedir after an error because libc may already have invalidated the handle.
Cleanup after a worker exits
Explicit close is the normal path. I also needed a fallback for the case where the last reference to a live cursor disappears. A resource destructor can run where a blocking filesystem call is unacceptable. Instead of calling closedir there, the destructor stores the pointer in the slot the stream already owns. The handoff takes no lock and allocates no queue entry. Each stream already has room for its own pending close, even if all 32 are abandoned.
A supervised Elixir process checks the slots on a normal scheduler. When it finds an abandoned stream, it schedules a dirty I/O pass to close it. The process waits 100 milliseconds after each check and any resulting cleanup pass before checking again. A stuck closedir can delay the entire pass. The handoff also depends on the last reference going away. If another process holds the cursor, the original worker’s exit alone does not close it. Keep the :scandir application running so the cleanup process is there when needed.
Package and trade-offs
I wanted to reduce the wait for the first useful folder. That meant moving metadata off the first batch’s path and leaving the rest of the work unread if I navigated away. I have not measured the latency or throughput of this design. A whole-directory list is still the simpler API when the caller needs everything. H’s earlier macOS listing helper runs outside the VM and still handles compatibility listings. For the progressive picker I chose an in-process cursor. If I needed a native crash to leave the VM intact, I would keep the scan in a separate OS process.
Scandir 0.1.0 is on Hex under the MIT license, with API documentation on HexDocs. It builds from source on Linux and macOS, so the build machine needs Rust/Cargo 1.91 or later and a native linker. The deployed release needs the compiled library for its own OS, architecture, and libc, not the compiler.