1#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct DirEntry {
109 pub name: String,
111 pub is_directory: bool,
113}
114
115#[cfg(not(target_arch = "wasm32"))]
120#[async_trait]
121pub trait Vfs: Send + Sync {
122 async fn read(&self, path: &str) -> VfsResult<Vec<u8>>;
124
125 async fn read_to_string(&self, path: &str) -> VfsResult<String>;
127
128 async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
130
131 async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
133
134 async fn exists(&self, path: &str) -> VfsResult<bool>;
136
137 async fn remove(&self, path: &str) -> VfsResult<()>;
139
140 async fn create_dir_all(&self, path: &str) -> VfsResult<()>;
142
143 async fn rename(&self, from: &str, to: &str) -> VfsResult<()>;
145
146 async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>>;
148}
149
150#[cfg(target_arch = "wasm32")]
152#[async_trait(?Send)]
153pub trait Vfs {
154 async fn read(&self, path: &str) -> VfsResult<Vec<u8>>;
156
157 async fn read_to_string(&self, path: &str) -> VfsResult<String>;
159
160 async fn write(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
162
163 async fn append(&self, path: &str, contents: &[u8]) -> VfsResult<()>;
165
166 async fn exists(&self, path: &str) -> VfsResult<bool>;
168
169 async fn remove(&self, path: &str) -> VfsResult<()>;
171
172 async fn create_dir_all(&self, path: &str) -> VfsResult<()>;
174
175 async fn rename(&self, from: &str, to: &str) -> VfsResult<()>;
177
178 async fn list_dir(&self, path: &str) -> VfsResult<Vec<DirEntry>>;
180}
181
182pub 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(()) }
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#[cfg(not(target_arch = "wasm32"))]
274pub struct NativeVfs {
275 base_dir: PathBuf,
277}
278
279#[cfg(not(target_arch = "wasm32"))]
280impl NativeVfs {
281 pub fn new<P: Into<PathBuf>>(base_dir: P) -> Self {
283 Self {
284 base_dir: base_dir.into(),
285 }
286 }
287
288 fn resolve(&self, path: &str) -> PathBuf {
290 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 if let Some(parent) = full_path.parent() {
316 tokio::fs::create_dir_all(parent).await?;
317 }
318
319 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 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 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#[cfg(not(target_arch = "wasm32"))]
404pub type PlatformVfs = NativeVfs;
405
406#[cfg(target_arch = "wasm32")]
407pub type PlatformVfs = WorkerOpfsVfs;
408
409#[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(_) => {} }
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#[cfg(target_arch = "wasm32")]
436#[derive(Clone)]
437pub enum WebVfs {
438 Opfs(WorkerOpfsVfs),
440 IndexedDb(IndexedDbVfs),
442}
443
444#[cfg(target_arch = "wasm32")]
445impl WebVfs {
446 pub fn is_fallback(&self) -> bool {
448 matches!(self, WebVfs::IndexedDb(_))
449 }
450
451 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#[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 match WorkerOpfsVfs::new() {
547 Ok(opfs) => {
548 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 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;