Current section
Files
Jump to
Current section
Files
README.md
# Scandir
A small Elixir/Rust NIF for incremental local directory enumeration. It uses
`opendir`, `readdir`, and `closedir`; no child `stat`, sorting, recursion, or port.
## Build and integrate
Scandir is source-built via Rustler. Add `{:scandir, "~> 0.2.0"}` to `mix.exs`.
Keep `:scandir` in the release's started applications so its cleanup worker,
cache process, and eager NIF loader run at startup.
Build with Elixir 1.15+, compatible OTP (NIF API 2.15+), Rust/Cargo 1.91+, and a
native C linker/SDK. Cargo and the compiler are not needed in the deployed
release. Build separately for each OS, architecture, and libc; don't copy a glibc
NIF into an Alpine release. For native musl builds, set this **before** compiling
Scandir (including when building a consumer release):
```sh
export RUSTFLAGS="-C target-feature=-crt-static"
```
This enables dynamic `cdylib` output on musl Rust targets that default to static
CRT linkage. Verify the produced NIF loads in the actual runtime image.
| Source-build target | x86_64 / amd64 | arm64 / aarch64 |
| --- | --- | --- |
| Linux glibc | CI configured | CI configured |
| Linux musl | CI configured | CI configured |
| macOS | CI configured | CI configured |
## API
- `Scandir.open(path)` → `{:ok, cursor}` or `{:error, reason}`. Pass a nonempty,
NUL-free binary path. `opendir` follows symlinks in the input path.
- `Scandir.open(path, opts)` → `{:ok, cursor}` or `{:error, reason}`. Pass
`cache: true` to serve fresh listings from `Scandir.Cache` (bounded ETS TTL
cache) using the same `next/2` and `close/1` cursor protocol. On a cache miss,
the cursor streams from the native OS handle and caches the full listing once
`:eof` is reached within `:max_entries` (default `5_000`). Supports `:ttl_ms`
(default `5_000`), `:max_entries`, `:force`, `:table`, and `:server`.
- `Scandir.cached_list(path, opts)` → `{:ok, entries}` or `{:error, reason | :too_large}`
reads a directory via `Scandir.Cache` directly. `Scandir.invalidate_cache(path | :all, opts)`
evicts cached entries.
- `Scandir.next(cursor, max_visited)` → `{:ok, entries, :more | :eof}` or
`{:error, reason}`. `max_visited` must be an integer in `1..Scandir.max_batch()`
(128). `.` and `..` count against the visit budget but are never returned.
An empty `:more` batch is valid; `:more` does not promise another entry, and
there is no lookahead. EOF stays latched until close and does not close the FD.
- Entries are `{raw_name_binary, kind}` in filesystem order. `kind` is
`:directory`, `:regular`, `:symlink`, `:unknown`, or `:other`. The type is a
`d_type` hint, not verified metadata. Names are not necessarily UTF-8. The
directory is not a snapshot if modified during traversal.
- `Scandir.close(cursor)` → `:ok` or `{:error, reason}`. Idempotent after the close
completes, even if `closedir` reported an error. A valid read on a closed
cursor returns `{:error, :closed}`.
- Invalid arguments return `:badarg`. `:busy` means the FD cap was reached or
another operation currently holds the same cursor. OS errors use the fixed
atoms in `Scandir.reason/0`; unmapped errors become `:eio`. A failed batch can
have consumed entries without returning them; close and reopen if a new scan
is needed.
## Scheduling, cancellation, and cleanup
Use a bounded pool of scan workers, not a synchronous call in a UI/coordinator
process. Keep cursors in one worker; carry only entries and an ephemeral request
ID across the messaging boundary. Pull batches under backpressure, and on
navigation/cancellation ignore stale results and have the worker close in an
`after` clause. Filter, sort, and do any necessary metadata fallback in the
caller. Do not follow or probe children speculatively; preserve raw bytes for
filesystem access and handle invalid UTF-8 separately for display/transport.
Every libc operation is DirtyIo, including cleanup. Dirty I/O schedulers are
shared and finite: the 32-slot native FD cap is **not** a scheduler admission
limit. It includes in-progress opens/closes and pending GC cleanup, but does
not bound calls queued by BEAM before the NIF runs. Enforce a lower application
concurrency limit that leaves dirty I/O headroom. A timeout, disconnect, or
process kill cannot cancel a running syscall; don't recycle a worker permit
until native work really finishes. Stuck mounts or permission prompts can stall
calls indefinitely; native crashes remain VM-wide. macOS permission prompt
attribution must be verified separately in the actual signed deployment.
Explicit close is preferred. GC of the last cursor reference transfers its
handle into its reserved slot using an atomic store, without locks, syscalls,
or a message queue. One supervised BEAM worker polls the slots every 100 ms
(after each previous pass completes) with a bounded atomic check on a normal
scheduler. It only dispatches the DirtyIo cleanup NIF when it sees an abandoned
handle. A blocked close can delay that pass and consume capacity indefinitely.
Owner death is not a close if another process still holds the cursor. Keep the
application running while scanning; stop new work and explicitly close cursors
before stopping it. VM exit releases OS descriptors. Use a VM restart for
upgrades; live NIF replacement/purge is not supported.
## Tests
```sh
export MIX_BUILD_PATH=$(mktemp -d /private/tmp/scandir-test.XXXXXX) # macOS; use /tmp on Linux
mix deps.get
mix test
mix hex.build # local archive only
```
Fixtures cover bounded enumeration, skipped dot entries, stable EOF, types
(including dangling symlinks and a FIFO), Linux non-UTF-8 paths and names, invalid
inputs, missing/non-directory paths, idempotent close, cap exhaustion, and
recovery after cursor-holder exit. No protected paths, forced mounts, or test-only
NIF gates. See CI for the source-build matrix.