Skip to main content

logicaffeine_system/fs/
mod.rs

1//! Virtual File System Abstraction
2//!
3//! Provides platform-agnostic async file operations through the [`Vfs`] trait.
4//! This enables the same code to work on native platforms and in the browser.
5//!
6//! # Platform Implementations
7//!
8//! - **Native** ([`NativeVfs`]): Uses `tokio::fs` with atomic write operations
9//! - **WASM** (`OpfsVfs`): Uses the browser's Origin Private File System API
10//!
11//! # Features
12//!
13//! Requires the `persistence` feature.
14//!
15//! # Example
16//!
17//! ```no_run
18//! use logicaffeine_system::fs::{Vfs, NativeVfs};
19//! use std::sync::Arc;
20//!
21//! # fn main() {}
22//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
23//! let vfs: Arc<dyn Vfs + Send + Sync> = Arc::new(NativeVfs::new("/data"));
24//!
25//! // Write and read files
26//! vfs.write("config.json", b"{}").await?;
27//! let data = vfs.read("config.json").await?;
28//!
29//! // Atomic append for journaling
30//! vfs.append("log.txt", b"entry\n").await?;
31//! # Ok(())
32//! # }
33//! ```
34
35#[cfg(all(target_os = "linux", feature = "io-uring"))]
36mod uring;
37#[cfg(all(target_os = "linux", feature = "io-uring"))]
38pub(crate) mod uring_worker;
39
40#[cfg(all(target_os = "linux", feature = "io-uring"))]
41pub use uring::UringVfs;
42
43#[cfg(target_arch = "wasm32")]
44mod opfs;
45
46#[cfg(target_arch = "wasm32")]
47mod worker_opfs;
48
49#[cfg(target_arch = "wasm32")]
50mod indexeddb_vfs;
51
52#[cfg(target_arch = "wasm32")]
53pub use opfs::OpfsVfs;
54
55#[cfg(target_arch = "wasm32")]
56pub use worker_opfs::WorkerOpfsVfs;
57
58#[cfg(target_arch = "wasm32")]
59pub use indexeddb_vfs::IndexedDbVfs;
60
61use async_trait::async_trait;
62use std::io;
63
64#[cfg(not(target_arch = "wasm32"))]
65use std::path::PathBuf;
66
67/// Error type for VFS operations
68#[derive(Debug)]
69pub enum VfsError {
70    NotFound(String),
71    PermissionDenied(String),
72    AlreadyExists(String),
73    IoError(io::Error),
74    SerializationError(String),
75    JournalCorrupted(String),
76}
77
78impl std::fmt::Display for VfsError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            VfsError::NotFound(s) => write!(f, "Not found: {}", s),
82            VfsError::PermissionDenied(s) => write!(f, "Permission denied: {}", s),
83            VfsError::AlreadyExists(s) => write!(f, "Already exists: {}", s),
84            VfsError::IoError(e) => write!(f, "IO error: {}", e),
85            VfsError::SerializationError(s) => write!(f, "Serialization error: {}", s),
86            VfsError::JournalCorrupted(s) => write!(f, "Journal corrupted: {}", s),
87        }
88    }
89}
90
91impl std::error::Error for VfsError {}
92
93impl From<io::Error> for VfsError {
94    fn from(e: io::Error) -> Self {
95        match e.kind() {
96            io::ErrorKind::NotFound => VfsError::NotFound(e.to_string()),
97            io::ErrorKind::PermissionDenied => VfsError::PermissionDenied(e.to_string()),
98            io::ErrorKind::AlreadyExists => VfsError::AlreadyExists(e.to_string()),
99            _ => VfsError::IoError(e),
100        }
101    }
102}
103
104pub type VfsResult<T> = Result<T, VfsError>;
105
106/// A directory entry returned by `list_dir`.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct DirEntry {
109    /// Name of the file or directory (not full path).
110    pub name: String,
111    /// True if this entry is a directory.
112    pub is_directory: bool,
113}
114
115/// Virtual File System trait for platform-agnostic file operations.
116///
117/// On native platforms, requires Send+Sync for thread-safe access.
118/// On WASM, these bounds are relaxed since JS is single-threaded.
119#[cfg(not(target_arch = "wasm32"))]
120#[async_trait]
121pub trait Vfs: Send + Sync {
122    /// Read entire file contents as bytes.
123    async fn read(&self, path: &str) -> VfsResult<Vec<u8>>;
124
125    /// Read file contents as UTF-8 string.
126    async fn read_to_string(&self, path: &str) -> VfsResult<String>;
127
128    /// Write bytes to file (atomic on native, best-effort on WASM).
129    async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
130
131    /// Append bytes to file (atomic append semantics).
132    async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
133
134    /// Check if file exists.
135    async fn exists(&self, path: &str) -> VfsResult<bool>;
136
137    /// Delete a file.
138    async fn remove(&self, path: &str) -> VfsResult<()>;
139
140    /// Create directory and all parent directories.
141    async fn create_dir_all(&self, path: &str) -> VfsResult<()>;
142
143    /// Atomically rename a file (for journal compaction).
144    async fn rename(&self, from: &str, to: &str) -> VfsResult<()>;
145
146    /// List entries in a directory.
147    async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>>;
148}
149
150/// WASM version of VFS trait without Send+Sync (JS is single-threaded).
151#[cfg(target_arch = "wasm32")]
152#[async_trait(?Send)]
153pub trait Vfs {
154    /// Read entire file contents as bytes.
155    async fn read(&self, path: &str) -> VfsResult<Vec<u8>>;
156
157    /// Read file contents as UTF-8 string.
158    async fn read_to_string(&self, path: &str) -> VfsResult<String>;
159
160    /// Write bytes to file (atomic on native, best-effort on WASM).
161    async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
162
163    /// Append bytes to file (atomic append semantics).
164    async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
165
166    /// Check if file exists.
167    async fn exists(&self, path: &str) -> VfsResult<bool>;
168
169    /// Delete a file.
170    async fn remove(&self, path: &str) -> VfsResult<()>;
171
172    /// Create directory and all parent directories.
173    async fn create_dir_all(&self, path: &str) -> VfsResult<()>;
174
175    /// Atomically rename a file (for journal compaction).
176    async fn rename(&self, from: &str, to: &str) -> VfsResult<()>;
177
178    /// List entries in a directory.
179    async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>>;
180}
181
182/// The sealed test world's VFS:
183/// an in-memory filesystem that bridges the [`crate::testworld`] thread-local,
184/// so `Given a file …` seeds and Vfs-backed `Read`/`Write` statements share
185/// ONE source of truth. Installed per-test by the `largo test` runner; there
186/// is no real disk behind it (unless the test grants the filesystem
187/// capability, which routes it to a real `NativeVfs` instead). Its body only
188/// reads and writes the `testworld` thread-local, so it is equally at home
189/// behind either `Vfs` shape — the in-browser guide's page test runner drives
190/// it through the `?Send` one.
191pub struct MemVfs;
192
193impl MemVfs {
194    pub fn new() -> Self {
195        MemVfs
196    }
197}
198
199impl Default for MemVfs {
200    fn default() -> Self {
201        MemVfs::new()
202    }
203}
204
205#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
206#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
207impl Vfs for MemVfs {
208    async fn read(&self, path: &str) -> VfsResult<Vec<u8>> {
209        self.read_to_string(path).await.map(String::into_bytes)
210    }
211
212    async fn read_to_string(&self, path: &str) -> VfsResult<String> {
213        crate::testworld::with_world(|w| w.files.get(path).cloned())
214            .flatten()
215            .ok_or_else(|| VfsError::NotFound(path.to_string()))
216    }
217
218    async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
219        let text = String::from_utf8_lossy(contents).into_owned();
220        crate::testworld::seed_file(path.to_string(), text);
221        Ok(())
222    }
223
224    async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
225        let existing = self.read_to_string(path).await.unwrap_or_default();
226        let text = existing + &String::from_utf8_lossy(contents);
227        crate::testworld::seed_file(path.to_string(), text);
228        Ok(())
229    }
230
231    async fn exists(&self, path: &str) -> VfsResult<bool> {
232        Ok(crate::testworld::with_world(|w| w.files.contains_key(path)).unwrap_or(false))
233    }
234
235    async fn remove(&self, path: &str) -> VfsResult<()> {
236        crate::testworld::with_world(|w| w.files.remove(path));
237        Ok(())
238    }
239
240    async fn create_dir_all(&self, _path: &str) -> VfsResult<()> {
241        Ok(()) // directories are implicit in the flat in-memory map
242    }
243
244    async fn rename(&self, from: &str, to: &str) -> VfsResult<()> {
245        let content = self.read_to_string(from).await?;
246        crate::testworld::seed_file(to.to_string(), content);
247        crate::testworld::with_world(|w| w.files.remove(from));
248        Ok(())
249    }
250
251    async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>> {
252        let prefix = if path.is_empty() || path == "/" {
253            String::new()
254        } else {
255            format!("{}/", path.trim_end_matches('/'))
256        };
257        Ok(crate::testworld::with_world(|w| {
258            w.files
259                .keys()
260                .filter_map(|k| k.strip_prefix(&prefix))
261                .filter(|rest| !rest.is_empty() && !rest.contains('/'))
262                .map(|name| DirEntry {
263                    name: name.to_string(),
264                    is_directory: false,
265                })
266                .collect()
267        })
268        .unwrap_or_default())
269    }
270}
271
272/// Native filesystem VFS using tokio::fs.
273#[cfg(not(target_arch = "wasm32"))]
274pub struct NativeVfs {
275    /// Base directory for all operations (sandbox root).
276    base_dir: PathBuf,
277}
278
279#[cfg(not(target_arch = "wasm32"))]
280impl NativeVfs {
281    /// Create a new NativeVfs rooted at the given directory.
282    pub fn new<P: Into<PathBuf>>(base_dir: P) -> Self {
283        Self {
284            base_dir: base_dir.into(),
285        }
286    }
287
288    /// Resolve a virtual path to an absolute filesystem path.
289    fn resolve(&self, path: &str) -> PathBuf {
290        // Security: Prevent path traversal attacks
291        let clean = path.trim_start_matches('/').trim_start_matches("../");
292        self.base_dir.join(clean)
293    }
294}
295
296#[cfg(not(target_arch = "wasm32"))]
297#[async_trait]
298impl Vfs for NativeVfs {
299    async fn read(&self, path: &str) -> VfsResult<Vec<u8>> {
300        let full_path = self.resolve(path);
301        tokio::fs::read(&full_path).await.map_err(VfsError::from)
302    }
303
304    async fn read_to_string(&self, path: &str) -> VfsResult<String> {
305        let full_path = self.resolve(path);
306        tokio::fs::read_to_string(&full_path)
307            .await
308            .map_err(VfsError::from)
309    }
310
311    async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
312        let full_path = self.resolve(path);
313
314        // Ensure parent directory exists
315        if let Some(parent) = full_path.parent() {
316            tokio::fs::create_dir_all(parent).await?;
317        }
318
319        // Atomic write: write to temp file, then rename
320        let temp_path = full_path.with_extension("tmp");
321        tokio::fs::write(&temp_path, contents).await?;
322        tokio::fs::rename(&temp_path, &full_path).await?;
323
324        Ok(())
325    }
326
327    async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
328        use tokio::io::AsyncWriteExt;
329
330        let full_path = self.resolve(path);
331
332        // Ensure parent directory exists
333        if let Some(parent) = full_path.parent() {
334            tokio::fs::create_dir_all(parent).await?;
335        }
336
337        let mut file = tokio::fs::OpenOptions::new()
338            .create(true)
339            .append(true)
340            .open(&full_path)
341            .await?;
342
343        file.write_all(contents).await?;
344        file.sync_all().await?;
345
346        Ok(())
347    }
348
349    async fn exists(&self, path: &str) -> VfsResult<bool> {
350        let full_path = self.resolve(path);
351        Ok(full_path.exists())
352    }
353
354    async fn remove(&self, path: &str) -> VfsResult<()> {
355        let full_path = self.resolve(path);
356        tokio::fs::remove_file(&full_path)
357            .await
358            .map_err(VfsError::from)
359    }
360
361    async fn create_dir_all(&self, path: &str) -> VfsResult<()> {
362        let full_path = self.resolve(path);
363        tokio::fs::create_dir_all(&full_path)
364            .await
365            .map_err(VfsError::from)
366    }
367
368    async fn rename(&self, from: &str, to: &str) -> VfsResult<()> {
369        let from_path = self.resolve(from);
370        let to_path = self.resolve(to);
371        tokio::fs::rename(&from_path, &to_path)
372            .await
373            .map_err(VfsError::from)
374    }
375
376    async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>> {
377        let full_path = self.resolve(path);
378        let mut entries = Vec::new();
379        let mut read_dir = tokio::fs::read_dir(&full_path)
380            .await
381            .map_err(VfsError::from)?;
382
383        while let Some(entry) = read_dir.next_entry().await.map_err(VfsError::from)? {
384            let metadata = entry.metadata().await.map_err(VfsError::from)?;
385            entries.push(DirEntry {
386                name: entry.file_name().to_string_lossy().into_owned(),
387                is_directory: metadata.is_dir(),
388            });
389        }
390
391        // Sort entries: directories first, then alphabetically
392        entries.sort_by(|a, b| match (a.is_directory, b.is_directory) {
393            (true, false) => std::cmp::Ordering::Less,
394            (false, true) => std::cmp::Ordering::Greater,
395            _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
396        });
397
398        Ok(entries)
399    }
400}
401
402/// Type alias for platform-specific VFS.
403#[cfg(not(target_arch = "wasm32"))]
404pub type PlatformVfs = NativeVfs;
405
406#[cfg(target_arch = "wasm32")]
407pub type PlatformVfs = WorkerOpfsVfs;
408
409/// Get the platform-default VFS instance.
410///
411/// - Linux with `io-uring` feature: Tries `UringVfs` first for kernel-async I/O,
412///   falls back to `NativeVfs` if io_uring is unavailable (old kernel, container).
413/// - Other native: Returns `NativeVfs` (tokio::fs)
414/// - WASM: Returns `WorkerOpfsVfs` backed by a Web Worker
415#[cfg(not(target_arch = "wasm32"))]
416pub fn get_platform_vfs() -> Box<dyn Vfs + Send + Sync> {
417    #[cfg(all(target_os = "linux", feature = "io-uring"))]
418    {
419        match UringVfs::new(".") {
420            Ok(vfs) => return Box::new(vfs),
421            Err(_) => {} // Fall through to NativeVfs
422        }
423    }
424    Box::new(NativeVfs::new("."))
425}
426
427#[cfg(target_arch = "wasm32")]
428pub fn get_platform_vfs() -> VfsResult<WorkerOpfsVfs> {
429    WorkerOpfsVfs::new()
430}
431
432/// Enum wrapping both OPFS and IndexedDB VFS implementations.
433///
434/// Used for transparent fallback when OPFS is unavailable (e.g., Private Browsing).
435#[cfg(target_arch = "wasm32")]
436#[derive(Clone)]
437pub enum WebVfs {
438    /// Primary: OPFS via Web Worker (best performance, largest quota)
439    Opfs(WorkerOpfsVfs),
440    /// Fallback: IndexedDB (works in Private Browsing, session-scoped)
441    IndexedDb(IndexedDbVfs),
442}
443
444#[cfg(target_arch = "wasm32")]
445impl WebVfs {
446    /// Returns true if using the IndexedDB fallback.
447    pub fn is_fallback(&self) -> bool {
448        matches!(self, WebVfs::IndexedDb(_))
449    }
450
451    /// Returns a human-readable name for the current storage backend.
452    pub fn backend_name(&self) -> &'static str {
453        match self {
454            WebVfs::Opfs(_) => "OPFS",
455            WebVfs::IndexedDb(_) => "IndexedDB",
456        }
457    }
458}
459
460#[cfg(target_arch = "wasm32")]
461#[async_trait(?Send)]
462impl Vfs for WebVfs {
463    async fn read(&self, path: &str) -> VfsResult<Vec<u8>> {
464        match self {
465            WebVfs::Opfs(vfs) => vfs.read(path).await,
466            WebVfs::IndexedDb(vfs) => vfs.read(path).await,
467        }
468    }
469
470    async fn read_to_string(&self, path: &str) -> VfsResult<String> {
471        match self {
472            WebVfs::Opfs(vfs) => vfs.read_to_string(path).await,
473            WebVfs::IndexedDb(vfs) => vfs.read_to_string(path).await,
474        }
475    }
476
477    async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
478        match self {
479            WebVfs::Opfs(vfs) => vfs.write(path, contents).await,
480            WebVfs::IndexedDb(vfs) => vfs.write(path, contents).await,
481        }
482    }
483
484    async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()> {
485        match self {
486            WebVfs::Opfs(vfs) => vfs.append(path, contents).await,
487            WebVfs::IndexedDb(vfs) => vfs.append(path, contents).await,
488        }
489    }
490
491    async fn exists(&self, path: &str) -> VfsResult<bool> {
492        match self {
493            WebVfs::Opfs(vfs) => vfs.exists(path).await,
494            WebVfs::IndexedDb(vfs) => vfs.exists(path).await,
495        }
496    }
497
498    async fn remove(&self, path: &str) -> VfsResult<()> {
499        match self {
500            WebVfs::Opfs(vfs) => vfs.remove(path).await,
501            WebVfs::IndexedDb(vfs) => vfs.remove(path).await,
502        }
503    }
504
505    async fn create_dir_all(&self, path: &str) -> VfsResult<()> {
506        match self {
507            WebVfs::Opfs(vfs) => vfs.create_dir_all(path).await,
508            WebVfs::IndexedDb(vfs) => vfs.create_dir_all(path).await,
509        }
510    }
511
512    async fn rename(&self, from: &str, to: &str) -> VfsResult<()> {
513        match self {
514            WebVfs::Opfs(vfs) => vfs.rename(from, to).await,
515            WebVfs::IndexedDb(vfs) => vfs.rename(from, to).await,
516        }
517    }
518
519    async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>> {
520        match self {
521            WebVfs::Opfs(vfs) => vfs.list_dir(path).await,
522            WebVfs::IndexedDb(vfs) => vfs.list_dir(path).await,
523        }
524    }
525}
526
527/// Get platform VFS with automatic fallback.
528///
529/// Tries OPFS first (best performance), falls back to IndexedDB if OPFS is
530/// unavailable (e.g., Private Browsing mode).
531///
532/// Returns `(WebVfs, is_fallback)` where `is_fallback` is true if using IndexedDB.
533#[cfg(target_arch = "wasm32")]
534pub async fn get_platform_vfs_with_fallback() -> VfsResult<WebVfs> {
535    use wasm_bindgen::prelude::*;
536
537    #[wasm_bindgen]
538    extern "C" {
539        #[wasm_bindgen(js_namespace = console)]
540        fn log(s: &str);
541    }
542
543    log("[VFS] Attempting OPFS initialization...");
544
545    // Try OPFS first
546    match WorkerOpfsVfs::new() {
547        Ok(opfs) => {
548            // Test if OPFS actually works by trying to create a directory
549            // This catches Private Browsing mode where OPFS creation succeeds
550            // but operations fail
551            match opfs.create_dir_all("/").await {
552                Ok(_) => {
553                    log("[VFS] OPFS initialized successfully");
554                    return Ok(WebVfs::Opfs(opfs));
555                }
556                Err(e) => {
557                    log(&format!(
558                        "[VFS] OPFS test failed: {:?}, trying IndexedDB...",
559                        e
560                    ));
561                }
562            }
563        }
564        Err(e) => {
565            log(&format!(
566                "[VFS] OPFS creation failed: {:?}, trying IndexedDB...",
567                e
568            ));
569        }
570    }
571
572    // Fall back to IndexedDB
573    log("[VFS] Falling back to IndexedDB...");
574    match IndexedDbVfs::new().await {
575        Ok(idb) => {
576            log("[VFS] IndexedDB initialized successfully");
577            Ok(WebVfs::IndexedDb(idb))
578        }
579        Err(e) => {
580            log(&format!("[VFS] IndexedDB initialization failed: {:?}", e));
581            Err(e)
582        }
583    }
584}
585
586#[cfg(test)]
587#[path = "../../../logicaffeine_tests/unit/logicaffeine_system/fs/tests.rs"]
588mod tests;