id_effect_platform 0.4.0

Platform capability traits (HTTP, FS, process) for id_effect — @effect/platform-style boundaries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Virtual filesystem ([`FileSystem`]): live Tokio ([`LiveFileSystem`]) and in-memory test double ([`TestFileSystem`]).
//!
//! ## Path handling (Phase A / `iep-a-050`)
//!
//! The public API uses [`std::path::Path`] for maximum compatibility. Callers that need UTF-8 paths
//! should validate or convert at the boundary (e.g. with [`camino::Utf8PathBuf`](https://docs.rs/camino)
//! in application code) before calling these traits.
//!
//! ## Security (Phase A / `iep-a-033`)
//!
//! - **Path traversal:** [`TestFileSystem`] rejects path keys containing `..`. Live I/O follows the OS;
//!   sandboxed apps should canonicalize or jail paths at a higher layer.
//! - **Symlinks:** No special symlink policy here; treat remote paths as untrusted unless you control the tree.

#![allow(clippy::new_ret_no_self, clippy::unused_unit)]
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use id_effect::kernel::Effect;
use id_effect::{Env, Needs, ProviderError, ProviderSpec};

use crate::error::FsError;

/// Capability: portable filesystem operations as [`Effect`] values.
pub trait FileSystem: Send + Sync + 'static {
  /// Read entire file into a byte vector.
  fn read(&self, path: &Path) -> Effect<Vec<u8>, FsError, ()>;
  /// Write bytes (overwrite).
  fn write(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()>;
  /// Append bytes (create if missing).
  fn append(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()>;
  /// Create a directory (and parents), Unix semantics.
  fn create_dir_all(&self, path: &Path) -> Effect<(), FsError, ()>;
  /// Remove a file.
  fn remove_file(&self, path: &Path) -> Effect<(), FsError, ()>;
  /// Metadata: file length if a regular file.
  fn metadata_len(&self, path: &Path) -> Effect<u64, FsError, ()>;
  /// Whether `path` exists (file or directory).
  fn exists(&self, path: &Path) -> Effect<bool, FsError, ()>;
}

/// Tokio-backed live filesystem.
#[derive(Clone, Default)]
pub struct LiveFileSystem;

impl LiveFileSystem {
  /// New live filesystem handle.
  #[inline]
  pub fn new() -> Self {
    Self
  }
}

impl FileSystem for LiveFileSystem {
  fn read(&self, path: &Path) -> Effect<Vec<u8>, FsError, ()> {
    let path = path.to_path_buf();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move { tokio::fs::read(&path).await.map_err(FsError::from) })
    })
  }

  fn write(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()> {
    let path = path.to_path_buf();
    let data = data.to_vec();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move { tokio::fs::write(&path, &data).await.map_err(FsError::from) })
    })
  }

  fn append(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()> {
    let path = path.to_path_buf();
    let data = data.to_vec();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move {
        use tokio::io::AsyncWriteExt;
        let mut f = tokio::fs::OpenOptions::new()
          .create(true)
          .append(true)
          .open(&path)
          .await
          .map_err(FsError::from)?;
        f.write_all(&data).await.map_err(FsError::from)?;
        f.flush().await.map_err(FsError::from)?;
        Ok(())
      })
    })
  }

  fn create_dir_all(&self, path: &Path) -> Effect<(), FsError, ()> {
    let path = path.to_path_buf();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move {
        tokio::fs::create_dir_all(&path)
          .await
          .map_err(FsError::from)
      })
    })
  }

  fn remove_file(&self, path: &Path) -> Effect<(), FsError, ()> {
    let path = path.to_path_buf();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move { tokio::fs::remove_file(&path).await.map_err(FsError::from) })
    })
  }

  fn metadata_len(&self, path: &Path) -> Effect<u64, FsError, ()> {
    let path = path.to_path_buf();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move {
        let m = tokio::fs::metadata(&path).await.map_err(FsError::from)?;
        Ok(m.len())
      })
    })
  }

  fn exists(&self, path: &Path) -> Effect<bool, FsError, ()> {
    let path = path.to_path_buf();
    Effect::new_async(move |_r: &mut ()| {
      Box::pin(async move { tokio::fs::try_exists(&path).await.map_err(FsError::from) })
    })
  }
}

/// In-memory filesystem for tests (single mutex; not for production concurrency).
#[derive(Clone, Default)]
pub struct TestFileSystem {
  inner: Arc<Mutex<std::collections::BTreeMap<String, Vec<u8>>>>,
}

impl TestFileSystem {
  /// Empty tree.
  #[inline]
  pub fn new() -> Self {
    Self {
      inner: Arc::new(Mutex::new(std::collections::BTreeMap::new())),
    }
  }

  #[cfg(test)]
  fn poison_inner_mutex(&self) {
    let inner = Arc::clone(&self.inner);
    let handle = std::thread::spawn(move || {
      let _guard = inner.lock().expect("lock");
      panic!("test mutex poison");
    });
    assert!(handle.join().is_err());
  }

  fn key(path: &Path) -> Result<String, FsError> {
    let s = path
      .to_str()
      .ok_or_else(|| FsError::PathNotAllowed("non-utf8 path".into()))?;
    if s.contains("..") {
      return Err(FsError::PathNotAllowed(
        "`..` not allowed in test paths".into(),
      ));
    }
    Ok(s.to_string())
  }
}

impl FileSystem for TestFileSystem {
  fn read(&self, path: &Path) -> Effect<Vec<u8>, FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    Effect::new(move |_r: &mut ()| {
      let map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      map.get(&key).cloned().ok_or_else(|| {
        FsError::Io(std::io::Error::new(
          std::io::ErrorKind::NotFound,
          "test file not found",
        ))
      })
    })
  }

  fn write(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    let data = data.to_vec();
    Effect::new(move |_r: &mut ()| {
      let mut map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      map.insert(key, data);
      Ok(())
    })
  }

  fn append(&self, path: &Path, data: &[u8]) -> Effect<(), FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    let data = data.to_vec();
    Effect::new(move |_r: &mut ()| {
      let mut map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      map.entry(key).or_default().extend_from_slice(&data);
      Ok(())
    })
  }

  fn create_dir_all(&self, _path: &Path) -> Effect<(), FsError, ()> {
    id_effect::succeed(())
  }

  fn remove_file(&self, path: &Path) -> Effect<(), FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    Effect::new(move |_r: &mut ()| {
      let mut map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      map.remove(&key).ok_or_else(|| {
        FsError::Io(std::io::Error::new(
          std::io::ErrorKind::NotFound,
          "test file not found",
        ))
      })?;
      Ok(())
    })
  }

  fn metadata_len(&self, path: &Path) -> Effect<u64, FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    Effect::new(move |_r: &mut ()| {
      let map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      let v = map.get(&key).ok_or_else(|| {
        FsError::Io(std::io::Error::new(
          std::io::ErrorKind::NotFound,
          "test file not found",
        ))
      })?;
      Ok(v.len() as u64)
    })
  }

  fn exists(&self, path: &Path) -> Effect<bool, FsError, ()> {
    let key = match Self::key(path) {
      Ok(k) => k,
      Err(e) => return id_effect::fail(e),
    };
    let inner = Arc::clone(&self.inner);
    Effect::new(move |_r: &mut ()| {
      let map = inner
        .lock()
        .map_err(|e| FsError::PathNotAllowed(e.to_string()))?;
      Ok(map.contains_key(&key))
    })
  }
}

/// Capability service handle for [`FileSystem`].
pub type FileSystemService = Arc<dyn FileSystem>;

/// Default [`ProviderSpec`] for a Tokio-backed live [`FileSystem`].
#[derive(::id_effect::ProviderSpecDerive)]
#[provides(FileSystemService)]
pub struct LiveFileSystemProvider;

impl LiveFileSystemProvider {
  fn new() -> FileSystemService {
    Arc::new(LiveFileSystem::new())
  }
}

/// Read via [`FileSystemService`].
#[inline]
pub fn read<R>(path: PathBuf) -> Effect<Vec<u8>, FsError, R>
where
  R: Needs<FileSystemService> + 'static,
{
  Effect::new_async(move |r: &mut R| {
    let fs = r.need().clone();
    let inner = fs.read(&path);
    Box::pin(async move { inner.run(&mut ()).await })
  })
}

/// Exists check via [`FileSystemService`].
#[inline]
pub fn exists<R>(path: PathBuf) -> Effect<bool, FsError, R>
where
  R: Needs<FileSystemService> + 'static,
{
  Effect::new_async(move |r: &mut R| {
    let fs = r.need().clone();
    let inner = fs.exists(&path);
    Box::pin(async move { inner.run(&mut ()).await })
  })
}

#[cfg(test)]
mod tests {
  use super::*;

  use id_effect::run_blocking;
  use std::path::Path;

  #[test]
  fn filesystem_service_type_alias_is_object_safe() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<FileSystemService>();
  }

  mod test_file_system {
    use super::*;

    mod path_policy {
      use super::*;

      #[test]
      fn write_rejects_when_path_contains_dotdot() {
        let fs = TestFileSystem::new();
        let err = run_blocking(fs.write(Path::new("a/../b.txt"), b"x"), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[cfg(unix)]
      #[test]
      fn write_rejects_when_path_not_utf8() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;
        let fs = TestFileSystem::new();
        let p = PathBuf::from(OsString::from_vec(vec![0xFF, 0xFE]));
        let err = run_blocking(fs.write(&p, b"x"), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }
    }

    mod exists {
      use super::*;

      #[test]
      fn false_before_write_true_after() {
        let fs = TestFileSystem::new();
        let p = Path::new("probe.txt");
        assert!(!run_blocking(fs.exists(p), ()).unwrap());
        run_blocking(fs.write(p, b"x"), ()).unwrap();
        assert!(run_blocking(fs.exists(p), ()).unwrap());
      }

      #[test]
      fn false_after_remove() {
        let fs = TestFileSystem::new();
        let p = Path::new("gone.txt");
        run_blocking(fs.write(p, b"x"), ()).unwrap();
        run_blocking(fs.remove_file(p), ()).unwrap();
        assert!(!run_blocking(fs.exists(p), ()).unwrap());
      }
    }

    mod read_write_round_trip {
      use super::*;

      #[test]
      fn read_returns_bytes_after_write() {
        let fs = TestFileSystem::new();
        let p = Path::new("dir/file.bin");
        run_blocking(fs.write(p, b"payload"), ()).unwrap();
        let got = run_blocking(fs.read(p), ()).unwrap();
        assert_eq!(got, b"payload");
      }

      #[test]
      fn append_extends_existing_file() {
        let fs = TestFileSystem::new();
        let p = Path::new("log.txt");
        run_blocking(fs.write(p, b"a"), ()).unwrap();
        run_blocking(fs.append(p, b"b"), ()).unwrap();
        let got = run_blocking(fs.read(p), ()).unwrap();
        assert_eq!(got, b"ab");
      }

      #[test]
      fn metadata_len_matches_written_length() {
        let fs = TestFileSystem::new();
        let p = Path::new("sized.dat");
        let data = vec![0u8; 42];
        run_blocking(fs.write(p, &data), ()).unwrap();
        let n = run_blocking(fs.metadata_len(p), ()).unwrap();
        assert_eq!(n, 42);
      }

      #[test]
      fn remove_file_deletes_then_read_fails() {
        let fs = TestFileSystem::new();
        let p = Path::new("gone.txt");
        run_blocking(fs.write(p, b"x"), ()).unwrap();
        run_blocking(fs.remove_file(p), ()).unwrap();
        let err = run_blocking(fs.read(p), ()).unwrap_err();
        assert!(matches!(err, FsError::Io(_)));
      }
    }

    mod create_dir_all {
      use super::*;

      #[test]
      fn succeeds_without_mutating_store() {
        let fs = TestFileSystem::new();
        run_blocking(fs.create_dir_all(Path::new("any/nested")), ()).unwrap();
      }
    }

    mod poisoned_mutex {
      use super::*;

      #[test]
      fn read_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.read(Path::new("ok.txt")), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[test]
      fn write_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.write(Path::new("ok.txt"), b"x"), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[test]
      fn append_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.append(Path::new("ok.txt"), b"x"), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[test]
      fn remove_file_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.remove_file(Path::new("ok.txt")), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[test]
      fn metadata_len_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.metadata_len(Path::new("ok.txt")), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }

      #[test]
      fn exists_maps_lock_poison_to_path_not_allowed() {
        let fs = TestFileSystem::new();
        fs.poison_inner_mutex();
        let err = run_blocking(fs.exists(Path::new("ok.txt")), ()).unwrap_err();
        assert!(matches!(err, FsError::PathNotAllowed(_)));
      }
    }
  }
}