Skip to main content

day_part_filesystem/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-filesystem: app-local file storage with one API on every target (docs/fs.md). No UI; any
5//! Rust code can depend on this crate and call [`read`]/[`write()`]/[`list`]/[`remove`].
6//!
7//! ```no_run
8//! day_part_filesystem::write("notes/today.txt", b"rain later")?;
9//! let bytes = day_part_filesystem::read("notes/today.txt")?;
10//! # Ok::<(), day_part_filesystem::FsError>(())
11//! ```
12//!
13//! Files live under a private per-app root: a real directory on the native targets (the mobile
14//! hosts pass it as `DAY_DATA_DIR`; desktops use the platform's data-dir convention), and the
15//! browser's Origin Private File System on web-dom. Paths are **relative and sandboxed** (an
16//! absolute path or a `.`/`..` segment is [`FsError::BadPath`]), and `write` creates missing
17//! parent directories.
18//!
19//! **Threading.** The blocking calls run where you call them, so keep them off the UI thread
20//! for large files; on web they return [`FsError::Unsupported`] (one thread, no blocking waits:
21//! the day-part-http rule). The `*_async` twins and futures work on every target; completions
22//! arrive on an unspecified background thread natively and on the sole browser thread on web,
23//! so deliver into UI state with a `Setter` or await under `day::task` (docs/async.md).
24
25use std::sync::{Arc, Mutex};
26
27/// A storage failure. The web tier collapses provider detail into [`FsError::Io`], like
28/// day-part-http's error taxonomy does for the browser.
29#[non_exhaustive]
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub enum FsError {
32    /// The path does not exist.
33    NotFound,
34    /// The path is absolute or contains a `.`/`..`/empty segment.
35    BadPath,
36    /// Everything else the platform reported.
37    Io(String),
38    /// No storage on this target, or a blocking entry point on web (docs/fs.md).
39    Unsupported,
40}
41
42impl std::fmt::Display for FsError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            FsError::NotFound => write!(f, "not found"),
46            FsError::BadPath => write!(f, "bad path (relative, no `.`/`..` segments)"),
47            FsError::Io(m) => write!(f, "{m}"),
48            FsError::Unsupported => write!(f, "no file storage on this target"),
49        }
50    }
51}
52
53impl std::error::Error for FsError {}
54
55/// Reject absolute paths and `.`/`..`/empty segments, the same rule the day CLI's web server
56/// applies to request paths. Every entry point funnels through this before touching a backend.
57fn check_path(path: &str) -> Result<(), FsError> {
58    if path.is_empty()
59        || path.starts_with('/')
60        || path.starts_with('\\')
61        || path.contains(':')
62        || path
63            .split(['/', '\\'])
64            .any(|seg| seg.is_empty() || seg == "." || seg == "..")
65    {
66        return Err(FsError::BadPath);
67    }
68    Ok(())
69}
70
71/// Read a file's bytes. Blocking; [`FsError::Unsupported`] on web, so use [`read_async`] or
72/// [`read_future`] there (they work everywhere).
73///
74/// # Errors
75///
76/// [`FsError::BadPath`] for a path outside the relative-path rules, [`FsError::NotFound`] when
77/// it does not exist, [`FsError::Unsupported`] on web or without a data directory, and
78/// [`FsError::Io`] for anything else the platform reports.
79pub fn read(path: &str) -> Result<Vec<u8>, FsError> {
80    check_path(path)?;
81    imp::read(path)
82}
83
84/// Open an app-local file for read-only, seekable access on native targets.
85/// Uses the same relative path rules and storage root as [`read`]. This lets archive
86/// readers fetch individual entries without loading the whole file. Opening and reading
87/// are blocking; use a worker when called from UI code. Not available on web, whose
88/// storage API currently supplies owned buffers through [`read_future`].
89///
90/// # Errors
91///
92/// [`FsError::BadPath`] for a path outside the relative-path rules, [`FsError::NotFound`] when
93/// it does not exist, [`FsError::Unsupported`] without a data directory, and [`FsError::Io`]
94/// for anything else the platform reports.
95#[cfg(not(target_arch = "wasm32"))]
96pub fn open_read(path: &str) -> Result<std::fs::File, FsError> {
97    check_path(path)?;
98    imp::open_read(path)
99}
100
101/// Write `bytes` to `path` (create or truncate), creating missing parent directories. Blocking;
102/// [`FsError::Unsupported`] on web.
103///
104/// # Errors
105///
106/// [`FsError::BadPath`] for a path outside the relative-path rules, [`FsError::Unsupported`] on
107/// web or without a data directory, and [`FsError::Io`] for anything else the platform reports.
108pub fn write(path: &str, bytes: &[u8]) -> Result<(), FsError> {
109    check_path(path)?;
110    imp::write(path, bytes)
111}
112
113/// Remove a file (or an empty directory). Blocking; [`FsError::Unsupported`] on web. Removing a
114/// missing path is [`FsError::NotFound`].
115///
116/// # Errors
117///
118/// [`FsError::BadPath`] for a path outside the relative-path rules, [`FsError::NotFound`] when
119/// it does not exist, [`FsError::Unsupported`] on web or without a data directory, and
120/// [`FsError::Io`] for anything else the platform reports.
121pub fn remove(path: &str) -> Result<(), FsError> {
122    check_path(path)?;
123    imp::remove(path)
124}
125
126/// List the entry names directly under `dir` (`""` = the storage root), sorted. Directories are
127/// listed with a trailing `/`. Blocking; [`FsError::Unsupported`] on web.
128///
129/// # Errors
130///
131/// [`FsError::BadPath`] for a path outside the relative-path rules, [`FsError::Unsupported`] on
132/// web or without a data directory, and [`FsError::Io`] for anything else the platform reports.
133/// A directory that was never written lists as empty.
134pub fn list(dir: &str) -> Result<Vec<String>, FsError> {
135    if !dir.is_empty() {
136        check_path(dir)?;
137    }
138    imp::list(dir)
139}
140
141type BytesResult = Result<Vec<u8>, FsError>;
142type UnitResult = Result<(), FsError>;
143type ListResult = Result<Vec<String>, FsError>;
144
145/// [`read`] without blocking; `on_done` runs on an unspecified background thread (the sole
146/// browser thread on web).
147pub fn read_async(path: &str, on_done: impl FnOnce(BytesResult) + Send + 'static) {
148    if let Err(e) = check_path(path) {
149        on_done(Err(e));
150        return;
151    }
152    imp::read_async(path.to_string(), Box::new(on_done));
153}
154
155/// [`write()`] without blocking.
156pub fn write_async(path: &str, bytes: Vec<u8>, on_done: impl FnOnce(UnitResult) + Send + 'static) {
157    if let Err(e) = check_path(path) {
158        on_done(Err(e));
159        return;
160    }
161    imp::write_async(path.to_string(), bytes, Box::new(on_done));
162}
163
164/// [`remove`] without blocking.
165pub fn remove_async(path: &str, on_done: impl FnOnce(UnitResult) + Send + 'static) {
166    if let Err(e) = check_path(path) {
167        on_done(Err(e));
168        return;
169    }
170    imp::remove_async(path.to_string(), Box::new(on_done));
171}
172
173/// [`list`] without blocking.
174pub fn list_async(dir: &str, on_done: impl FnOnce(ListResult) + Send + 'static) {
175    if !dir.is_empty()
176        && let Err(e) = check_path(dir)
177    {
178        on_done(Err(e));
179        return;
180    }
181    imp::list_async(dir.to_string(), Box::new(on_done));
182}
183
184// ---------------------------------------------------------------------------
185// Futures: oneshot plumbing over the async completions, awaitable under any executor
186// (`day::task`, or a test's block_on): the day-part-http shape without the cancel grip
187// (storage operations are short; v1 has no cancellation).
188// ---------------------------------------------------------------------------
189
190struct FutureState<T> {
191    result: Option<T>,
192    waker: Option<std::task::Waker>,
193}
194
195impl<T> Default for FutureState<T> {
196    fn default() -> Self {
197        FutureState {
198            result: None,
199            waker: None,
200        }
201    }
202}
203
204/// An in-flight storage operation; `.await` resolves it.
205pub struct FsFuture<T> {
206    shared: Arc<Mutex<FutureState<T>>>,
207}
208
209fn lock<T>(m: &Mutex<FutureState<T>>) -> std::sync::MutexGuard<'_, FutureState<T>> {
210    match m.lock() {
211        Ok(g) => g,
212        Err(poisoned) => poisoned.into_inner(),
213    }
214}
215
216impl<T> std::future::Future for FsFuture<T> {
217    type Output = T;
218    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<T> {
219        let mut st = lock(&self.shared);
220        if let Some(r) = st.result.take() {
221            return std::task::Poll::Ready(r);
222        }
223        st.waker = Some(cx.waker().clone());
224        std::task::Poll::Pending
225    }
226}
227
228fn deliver<T>(shared: &Arc<Mutex<FutureState<T>>>, result: T) {
229    let waker = {
230        let mut st = lock(shared);
231        st.result = Some(result);
232        st.waker.take()
233    };
234    if let Some(w) = waker {
235        w.wake();
236    }
237}
238
239macro_rules! future_over {
240    ($shared:ident, $call:expr) => {{
241        let $shared = Arc::new(Mutex::new(FutureState::default()));
242        let sink = $shared.clone();
243        $call;
244        FsFuture { shared: sink }
245    }};
246}
247
248/// [`read_async`] as a `Future`.
249#[must_use]
250pub fn read_future(path: &str) -> FsFuture<BytesResult> {
251    future_over!(shared, {
252        let s = shared.clone();
253        read_async(path, move |r| deliver(&s, r));
254    })
255}
256
257/// [`write_async`] as a `Future`.
258#[must_use]
259pub fn write_future(path: &str, bytes: Vec<u8>) -> FsFuture<UnitResult> {
260    future_over!(shared, {
261        let s = shared.clone();
262        write_async(path, bytes, move |r| deliver(&s, r));
263    })
264}
265
266/// [`remove_async`] as a `Future`.
267#[must_use]
268pub fn remove_future(path: &str) -> FsFuture<UnitResult> {
269    future_over!(shared, {
270        let s = shared.clone();
271        remove_async(path, move |r| deliver(&s, r));
272    })
273}
274
275/// [`list_async`] as a `Future`.
276#[must_use]
277pub fn list_future(dir: &str) -> FsFuture<ListResult> {
278    future_over!(shared, {
279        let s = shared.clone();
280        list_async(dir, move |r| deliver(&s, r));
281    })
282}
283
284/// The app's data directory on native targets, [`day_process::storage::data_dir`]: `DAY_DATA_DIR`
285/// when a host or a test sets it, else the platform's folder for this app (Application Support
286/// on Apple platforms, `%LOCALAPPDATA%` on Windows, `$XDG_DATA_HOME` on Linux, each followed by
287/// the app id). This part's own files live in its `day-fs/` subdirectory; other parts that keep
288/// files, such as a download manager's journal, take a sibling. The web has no such directory.
289///
290/// # Errors
291///
292/// [`FsError::Unsupported`] when the platform names no data directory for this app.
293#[cfg(not(target_arch = "wasm32"))]
294pub fn data_dir() -> Result<std::path::PathBuf, FsError> {
295    imp::data_dir()
296}
297
298/// The platform's shared application-data directory, the one other applications keep their own
299/// folders in: `~/Library/Application Support` on Apple, the roaming `%APPDATA%` on Windows
300/// (where Electron and Tauri apps keep theirs), `$XDG_DATA_HOME` (else `~/.local/share`)
301/// elsewhere. For an app that opens a store another application keeps there, the way a CLI companion of a desktop app reads that app's database. `DAY_DATA_DIR`
302/// does not redirect it: a host that names the app's own directory says nothing about where
303/// other applications keep theirs.
304///
305/// # Errors
306///
307/// [`FsError::Unsupported`] when the environment names no such directory.
308#[cfg(not(target_arch = "wasm32"))]
309pub fn platform_data_dir() -> Result<std::path::PathBuf, FsError> {
310    imp::platform_data_dir()
311}
312
313// ---------------------------------------------------------------------------
314// Per-target implementations. Native targets share one std::fs backend rooted at the
315// per-platform app-data directory; web-dom rides the day-toolkit-dom shim into OPFS.
316// ---------------------------------------------------------------------------
317
318#[cfg(not(target_arch = "wasm32"))]
319#[path = "native.rs"]
320mod imp;
321
322#[cfg(target_arch = "wasm32")]
323#[path = "web.rs"]
324mod imp;
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn path_rules() {
332        for bad in [
333            "", "/abs", "a//b", "./x", "../x", "a/../b", "c:win", "a/./b",
334        ] {
335            assert_eq!(check_path(bad), Err(FsError::BadPath), "{bad:?}");
336        }
337        for good in ["a", "a/b.txt", "notes/2026/07.md"] {
338            assert_eq!(check_path(good), Ok(()), "{good:?}");
339        }
340    }
341
342    #[cfg(not(target_arch = "wasm32"))]
343    #[test]
344    fn round_trip_list_remove() {
345        // Root under a scratch dir so the test never touches the real data dir.
346        let scratch = std::env::temp_dir().join(format!("day-part-fs-{}", std::process::id()));
347        // SAFETY: tests in this crate run single-threaded over this env var (no other test
348        // reads it), and the var is test-scoped.
349        unsafe { std::env::set_var("DAY_DATA_DIR", &scratch) };
350
351        write("t/hello.txt", b"hi").unwrap();
352        assert_eq!(read("t/hello.txt").unwrap(), b"hi");
353        {
354            use std::io::{Read, Seek, SeekFrom, Write};
355            let mut file = open_read("t/hello.txt").unwrap();
356            file.seek(SeekFrom::Start(1)).unwrap();
357            let mut byte = [0];
358            file.read_exact(&mut byte).unwrap();
359            assert_eq!(&byte, b"i");
360            assert!(file.write_all(b"x").is_err(), "handle must be read-only");
361        }
362        assert_eq!(open_read("t/missing.txt").unwrap_err(), FsError::NotFound);
363        assert_eq!(open_read("../outside").unwrap_err(), FsError::BadPath);
364        assert_eq!(list("t").unwrap(), vec!["hello.txt".to_string()]);
365        assert_eq!(read("t/missing.txt"), Err(FsError::NotFound));
366        remove("t/hello.txt").unwrap();
367        assert_eq!(remove("t/hello.txt"), Err(FsError::NotFound));
368        assert_eq!(list("t").unwrap(), Vec::<String>::new());
369        let _ = std::fs::remove_dir_all(&scratch);
370    }
371}