larastvel-core 0.2.1

Larastvel framework core - inspired by Laravel
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use tokio::fs;
use tokio::io::AsyncWriteExt;

#[derive(Debug, thiserror::Error)]
pub enum StorageError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Path not found: {0}")]
    NotFound(String),
    #[error("Path is not a file: {0}")]
    NotAFile(String),
    #[error("Path is not a directory: {0}")]
    NotADirectory(String),
    #[error("Storage error: {0}")]
    General(String),
}

#[async_trait]
pub trait Filesystem: Send + Sync + std::fmt::Debug {
    async fn put(&self, path: &str, contents: &[u8]) -> Result<(), StorageError>;
    async fn put_string(&self, path: &str, contents: &str) -> Result<(), StorageError> {
        self.put(path, contents.as_bytes()).await
    }
    async fn get(&self, path: &str) -> Result<Vec<u8>, StorageError>;
    async fn get_string(&self, path: &str) -> Result<String, StorageError> {
        let bytes = self.get(path).await?;
        String::from_utf8(bytes).map_err(|e| StorageError::General(e.to_string()))
    }
    async fn exists(&self, path: &str) -> bool;
    async fn missing(&self, path: &str) -> bool {
        !self.exists(path).await
    }
    async fn delete(&self, path: &str) -> Result<(), StorageError>;
    async fn copy(&self, from: &str, to: &str) -> Result<(), StorageError>;
    async fn move_file(&self, from: &str, to: &str) -> Result<(), StorageError>;
    async fn size(&self, path: &str) -> Result<u64, StorageError>;
    async fn last_modified(&self, path: &str) -> Result<u64, StorageError>;
    async fn files(&self, directory: &str) -> Result<Vec<String>, StorageError>;
    async fn all_files(&self, directory: &str) -> Result<Vec<String>, StorageError>;
    async fn directories(&self, directory: &str) -> Result<Vec<String>, StorageError>;
    async fn all_directories(&self, directory: &str) -> Result<Vec<String>, StorageError>;
    async fn make_directory(&self, path: &str) -> Result<(), StorageError>;
    async fn delete_directory(&self, path: &str) -> Result<(), StorageError>;
    fn url(&self, path: &str) -> String;
    fn path(&self, relative: &str) -> PathBuf;
}

#[derive(Debug, Clone)]
pub struct LocalDisk {
    root: PathBuf,
    url_prefix: String,
}

impl LocalDisk {
    pub fn new(root: PathBuf, url_prefix: String) -> Self {
        Self { root, url_prefix }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    fn full_path(&self, path: &str) -> PathBuf {
        let sanitized = path.trim_start_matches('/');
        self.root.join(sanitized)
    }
}

#[async_trait]
impl Filesystem for LocalDisk {
    async fn put(&self, path: &str, contents: &[u8]) -> Result<(), StorageError> {
        let full = self.full_path(path);
        if let Some(parent) = full.parent() {
            fs::create_dir_all(parent).await?;
        }
        let mut file = fs::File::create(&full).await?;
        file.write_all(contents).await?;
        file.flush().await?;
        Ok(())
    }

    async fn get(&self, path: &str) -> Result<Vec<u8>, StorageError> {
        let full = self.full_path(path);
        if !full.exists() {
            return Err(StorageError::NotFound(path.to_string()));
        }
        if !full.is_file() {
            return Err(StorageError::NotAFile(path.to_string()));
        }
        Ok(fs::read(&full).await?)
    }

    async fn exists(&self, path: &str) -> bool {
        self.full_path(path).exists()
    }

    async fn delete(&self, path: &str) -> Result<(), StorageError> {
        let full = self.full_path(path);
        if !full.exists() {
            return Err(StorageError::NotFound(path.to_string()));
        }
        if full.is_dir() {
            fs::remove_dir_all(&full).await?;
        } else {
            fs::remove_file(&full).await?;
        }
        Ok(())
    }

    async fn copy(&self, from: &str, to: &str) -> Result<(), StorageError> {
        let from_full = self.full_path(from);
        let to_full = self.full_path(to);
        if !from_full.exists() {
            return Err(StorageError::NotFound(from.to_string()));
        }
        if let Some(parent) = to_full.parent() {
            fs::create_dir_all(parent).await?;
        }
        fs::copy(&from_full, &to_full).await?;
        Ok(())
    }

    async fn move_file(&self, from: &str, to: &str) -> Result<(), StorageError> {
        let from_full = self.full_path(from);
        let to_full = self.full_path(to);
        if !from_full.exists() {
            return Err(StorageError::NotFound(from.to_string()));
        }
        if let Some(parent) = to_full.parent() {
            fs::create_dir_all(parent).await?;
        }
        fs::rename(&from_full, &to_full).await?;
        Ok(())
    }

    async fn size(&self, path: &str) -> Result<u64, StorageError> {
        let full = self.full_path(path);
        if !full.exists() {
            return Err(StorageError::NotFound(path.to_string()));
        }
        let meta = fs::metadata(&full).await?;
        Ok(meta.len())
    }

    async fn last_modified(&self, path: &str) -> Result<u64, StorageError> {
        let full = self.full_path(path);
        if !full.exists() {
            return Err(StorageError::NotFound(path.to_string()));
        }
        let meta = fs::metadata(&full).await?;
        meta.modified()
            .map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            })
            .map_err(|e| StorageError::General(e.to_string()))
    }

    async fn files(&self, directory: &str) -> Result<Vec<String>, StorageError> {
        let full = self.full_path(directory);
        if !full.exists() {
            return Err(StorageError::NotFound(directory.to_string()));
        }
        if !full.is_dir() {
            return Err(StorageError::NotADirectory(directory.to_string()));
        }
        let mut result = Vec::new();
        let mut entries = fs::read_dir(&full).await?;
        while let Some(entry) = entries.next_entry().await? {
            if entry.file_type().await?.is_file() {
                if let Some(name) = entry.file_name().to_str() {
                    result.push(name.to_string());
                }
            }
        }
        result.sort();
        Ok(result)
    }

    async fn all_files(&self, directory: &str) -> Result<Vec<String>, StorageError> {
        let full = self.full_path(directory);
        if !full.exists() {
            return Err(StorageError::NotFound(directory.to_string()));
        }
        let mut result = Vec::new();
        self.collect_files_recursive(&full, &full, &mut result)
            .await?;
        result.sort();
        Ok(result)
    }

    async fn directories(&self, directory: &str) -> Result<Vec<String>, StorageError> {
        let full = self.full_path(directory);
        if !full.exists() {
            return Err(StorageError::NotFound(directory.to_string()));
        }
        if !full.is_dir() {
            return Err(StorageError::NotADirectory(directory.to_string()));
        }
        let mut result = Vec::new();
        let mut entries = fs::read_dir(&full).await?;
        while let Some(entry) = entries.next_entry().await? {
            if entry.file_type().await?.is_dir() {
                if let Some(name) = entry.file_name().to_str() {
                    result.push(name.to_string());
                }
            }
        }
        result.sort();
        Ok(result)
    }

    async fn all_directories(&self, directory: &str) -> Result<Vec<String>, StorageError> {
        let full = self.full_path(directory);
        if !full.exists() {
            return Err(StorageError::NotFound(directory.to_string()));
        }
        let mut result = Vec::new();
        self.collect_dirs_recursive(&full, &full, &mut result)
            .await?;
        result.sort();
        Ok(result)
    }

    async fn make_directory(&self, path: &str) -> Result<(), StorageError> {
        let full = self.full_path(path);
        fs::create_dir_all(&full).await?;
        Ok(())
    }

    async fn delete_directory(&self, path: &str) -> Result<(), StorageError> {
        let full = self.full_path(path);
        if !full.exists() {
            return Err(StorageError::NotFound(path.to_string()));
        }
        fs::remove_dir_all(&full).await?;
        Ok(())
    }

    fn url(&self, path: &str) -> String {
        let sanitized = path.trim_start_matches('/');
        format!("{}/{}", self.url_prefix.trim_end_matches('/'), sanitized)
    }

    fn path(&self, relative: &str) -> PathBuf {
        self.full_path(relative)
    }
}

impl LocalDisk {
    async fn collect_files_recursive(
        &self,
        base: &Path,
        dir: &Path,
        result: &mut Vec<String>,
    ) -> Result<(), StorageError> {
        let mut entries = fs::read_dir(dir).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.is_dir() {
                Box::pin(self.collect_files_recursive(base, &path, result)).await?;
            } else if path.is_file() {
                if let Ok(relative) = path.strip_prefix(base) {
                    result.push(relative.to_string_lossy().to_string());
                }
            }
        }
        Ok(())
    }

    async fn collect_dirs_recursive(
        &self,
        base: &Path,
        dir: &Path,
        result: &mut Vec<String>,
    ) -> Result<(), StorageError> {
        let mut entries = fs::read_dir(dir).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.is_dir() {
                if let Ok(relative) = path.strip_prefix(base) {
                    result.push(relative.to_string_lossy().to_string());
                }
                Box::pin(self.collect_dirs_recursive(base, &path, result)).await?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct StorageManager {
    disks: HashMap<String, Arc<dyn Filesystem>>,
    default: String,
}

impl StorageManager {
    pub fn new(default_disk: String) -> Self {
        Self {
            disks: HashMap::new(),
            default: default_disk,
        }
    }

    pub fn register<D: Filesystem + 'static>(&mut self, name: &str, disk: D) {
        self.disks.insert(name.to_string(), Arc::new(disk));
    }

    pub fn disk(&self, name: &str) -> Result<Arc<dyn Filesystem>, StorageError> {
        self.disks
            .get(name)
            .cloned()
            .ok_or_else(|| StorageError::General(format!("Disk [{}] not configured", name)))
    }

    pub fn default_disk(&self) -> Result<Arc<dyn Filesystem>, StorageError> {
        self.disk(&self.default)
    }

    pub fn set_default(&mut self, name: &str) {
        self.default = name.to_string();
    }

    pub fn default_name(&self) -> &str {
        &self.default
    }

    pub fn disk_names(&self) -> Vec<String> {
        self.disks.keys().cloned().collect()
    }
}

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

    fn temp_dir() -> PathBuf {
        let mut rng = rand::rngs::OsRng;
        let suffix: u64 = rng.gen();
        std::env::temp_dir().join(format!("larastvel_storage_test_{}", suffix))
    }

    fn create_disk() -> (LocalDisk, PathBuf) {
        let root = temp_dir();
        let disk = LocalDisk::new(root.clone(), "/storage".to_string());
        (disk, root)
    }

    async fn cleanup(root: &Path) {
        if root.exists() {
            fs::remove_dir_all(root).await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_put_and_get() {
        let (disk, root) = create_disk();
        disk.put("hello.txt", b"world").await.unwrap();
        let contents = disk.get("hello.txt").await.unwrap();
        assert_eq!(contents, b"world");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_put_string_and_get_string() {
        let (disk, root) = create_disk();
        disk.put_string("greeting.txt", "Hello, World!")
            .await
            .unwrap();
        let contents = disk.get_string("greeting.txt").await.unwrap();
        assert_eq!(contents, "Hello, World!");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_exists() {
        let (disk, root) = create_disk();
        assert!(!disk.exists("test.txt").await);
        disk.put("test.txt", b"data").await.unwrap();
        assert!(disk.exists("test.txt").await);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_missing() {
        let (disk, root) = create_disk();
        assert!(disk.missing("nonexistent.txt").await);
        disk.put("exists.txt", b"x").await.unwrap();
        assert!(!disk.missing("exists.txt").await);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_delete_file() {
        let (disk, root) = create_disk();
        disk.put("delete_me.txt", b"bye").await.unwrap();
        assert!(disk.exists("delete_me.txt").await);
        disk.delete("delete_me.txt").await.unwrap();
        assert!(!disk.exists("delete_me.txt").await);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_delete_nonexistent() {
        let (disk, root) = create_disk();
        let result = disk.delete("nowhere.txt").await;
        assert!(result.is_err());
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_copy() {
        let (disk, root) = create_disk();
        disk.put("source.txt", b"source content").await.unwrap();
        disk.copy("source.txt", "dest.txt").await.unwrap();
        assert_eq!(disk.get("dest.txt").await.unwrap(), b"source content");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_move_file() {
        let (disk, root) = create_disk();
        disk.put("original.txt", b"move me").await.unwrap();
        disk.move_file("original.txt", "moved.txt").await.unwrap();
        assert!(!disk.exists("original.txt").await);
        assert_eq!(disk.get("moved.txt").await.unwrap(), b"move me");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_size() {
        let (disk, root) = create_disk();
        disk.put("sized.txt", b"12345").await.unwrap();
        assert_eq!(disk.size("sized.txt").await.unwrap(), 5);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_files() {
        let (disk, root) = create_disk();
        disk.put("a.txt", b"").await.unwrap();
        disk.put("b.txt", b"").await.unwrap();
        disk.put("sub/c.txt", b"").await.unwrap();
        let files = disk.files("").await.unwrap();
        assert_eq!(files, vec!["a.txt", "b.txt"]);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_all_files_recursive() {
        let (disk, root) = create_disk();
        disk.put("root.txt", b"").await.unwrap();
        disk.put("sub/a.txt", b"").await.unwrap();
        disk.put("sub/deep/b.txt", b"").await.unwrap();
        let all = disk.all_files("").await.unwrap();
        assert_eq!(all, vec!["root.txt", "sub/a.txt", "sub/deep/b.txt"]);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_directories() {
        let (disk, root) = create_disk();
        disk.put("sub1/file.txt", b"").await.unwrap();
        disk.put("sub2/file.txt", b"").await.unwrap();
        disk.put("root.txt", b"").await.unwrap();
        let dirs = disk.directories("").await.unwrap();
        assert_eq!(dirs, vec!["sub1", "sub2"]);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_all_directories_recursive() {
        let (disk, root) = create_disk();
        disk.put("a/x.txt", b"").await.unwrap();
        disk.put("a/b/y.txt", b"").await.unwrap();
        disk.put("a/b/c/z.txt", b"").await.unwrap();
        let dirs = disk.all_directories("").await.unwrap();
        assert_eq!(dirs, vec!["a", "a/b", "a/b/c"]);
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_make_and_delete_directory() {
        let (disk, root) = create_disk();
        disk.make_directory("new_dir").await.unwrap();
        assert!(root.join("new_dir").exists());
        disk.delete_directory("new_dir").await.unwrap();
        assert!(!root.join("new_dir").exists());
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_url() {
        let disk = LocalDisk::new(PathBuf::from("/tmp"), "/storage".to_string());
        assert_eq!(disk.url("file.txt"), "/storage/file.txt");
        assert_eq!(disk.url("/file.txt"), "/storage/file.txt");
        assert_eq!(disk.url("sub/file.txt"), "/storage/sub/file.txt");
    }

    #[tokio::test]
    async fn test_path() {
        let disk = LocalDisk::new(PathBuf::from("/app/storage"), "".to_string());
        assert_eq!(
            disk.path("file.txt"),
            PathBuf::from("/app/storage/file.txt")
        );
        assert_eq!(
            disk.path("sub/dir/file.txt"),
            PathBuf::from("/app/storage/sub/dir/file.txt")
        );
    }

    #[tokio::test]
    async fn test_get_nonexistent() {
        let (disk, root) = create_disk();
        let result = disk.get("nowhere.txt").await;
        assert!(result.is_err());
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_overwrite_file() {
        let (disk, root) = create_disk();
        disk.put("file.txt", b"original").await.unwrap();
        disk.put("file.txt", b"overwritten").await.unwrap();
        assert_eq!(disk.get("file.txt").await.unwrap(), b"overwritten");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_put_in_subdirectory() {
        let (disk, root) = create_disk();
        disk.put("nested/deep/file.txt", b"deep").await.unwrap();
        assert!(disk.exists("nested/deep/file.txt").await);
        assert_eq!(disk.get("nested/deep/file.txt").await.unwrap(), b"deep");
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_storage_manager() {
        let (disk, _root) = create_disk();
        let mut manager = StorageManager::new("local".to_string());
        manager.register("local", disk);

        let retrieved = manager.disk("local").unwrap();
        assert!(!retrieved.exists("nonexistent").await);

        let default = manager.default_disk().unwrap();
        assert!(!default.exists("nonexistent").await);
    }

    #[tokio::test]
    async fn test_storage_manager_missing_disk() {
        let manager = StorageManager::new("local".to_string());
        let result = manager.disk("nonexistent");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_storage_manager_default_name() {
        let manager = StorageManager::new("local".to_string());
        assert_eq!(manager.default_name(), "local");
    }

    #[tokio::test]
    async fn test_storage_manager_disk_names() {
        let mut manager = StorageManager::new("local".to_string());
        let (disk, _root) = create_disk();
        manager.register("local", disk);
        let (disk2, _root2) = create_disk();
        manager.register("s3", disk2);
        let mut names = manager.disk_names();
        names.sort();
        assert_eq!(names, vec!["local", "s3"]);
    }

    #[tokio::test]
    async fn test_delete_directory_with_contents() {
        let (disk, root) = create_disk();
        disk.put("dir/a.txt", b"").await.unwrap();
        disk.put("dir/sub/b.txt", b"").await.unwrap();
        assert!(root.join("dir").exists());
        disk.delete_directory("dir").await.unwrap();
        assert!(!root.join("dir").exists());
        cleanup(&root).await;
    }

    #[tokio::test]
    async fn test_last_modified() {
        let (disk, root) = create_disk();
        disk.put("fresh.txt", b"data").await.unwrap();
        let modified = disk.last_modified("fresh.txt").await.unwrap();
        assert!(modified > 0);
        cleanup(&root).await;
    }
}