acton-htmx 1.0.0-beta.7

Opinionated Rust web framework for HTMX applications
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
//! Local filesystem storage implementation

use super::traits::FileStorage;
use super::types::{StorageError, StorageResult, StoredFile, UploadedFile};
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::AsyncWriteExt;
use uuid::Uuid;

/// Local filesystem storage backend
///
/// Stores files in a local directory with UUID-based organization.
/// Each file is stored in a subdirectory based on the first 2 characters
/// of its UUID to avoid hitting filesystem limits on files per directory.
///
/// # Directory Structure
///
/// ```text
/// /var/uploads/
/// ├── 55/
/// │   └── 550e8400-e29b-41d4-a716-446655440000/
/// │       └── document.pdf
/// ├── a3/
/// │   └── a3bb189e-8bf9-4a9a-b5c7-9f9c3b8e5d7a/
/// │       └── image.png
/// ```
///
/// # Examples
///
/// ```rust,no_run
/// use acton_htmx::storage::{LocalFileStorage, FileStorage, UploadedFile};
/// use std::path::PathBuf;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Create storage (creates directory if it doesn't exist)
/// let storage = LocalFileStorage::new(PathBuf::from("/var/uploads"))?;
///
/// // Store a file
/// let file = UploadedFile::new("photo.jpg", "image/jpeg", vec![/* ... */]);
/// let stored = storage.store(file).await?;
///
/// // File is now at: /var/uploads/55/550e8400.../photo.jpg
/// println!("Stored at: {}", stored.storage_path);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct LocalFileStorage {
    /// Base directory for file storage
    base_path: PathBuf,
}

impl LocalFileStorage {
    /// Creates a new local file storage instance
    ///
    /// This will verify that the base path exists and is writable.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The base path doesn't exist and cannot be created
    /// - The base path is not a directory
    /// - Insufficient permissions to write to the directory
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use acton_htmx::storage::LocalFileStorage;
    /// use std::path::PathBuf;
    ///
    /// let storage = LocalFileStorage::new(PathBuf::from("/var/uploads"))?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(base_path: PathBuf) -> StorageResult<Self> {
        // Validate base path (synchronous check is OK for initialization)
        if base_path.exists() && !base_path.is_dir() {
            return Err(StorageError::InvalidPath(format!(
                "{} is not a directory",
                base_path.display()
            )));
        }

        Ok(Self { base_path })
    }

    /// Gets the filesystem path for a file ID
    ///
    /// Returns the directory path where the file should be stored,
    /// using the first 2 characters of the ID as a prefix.
    fn get_file_directory(&self, id: &str) -> PathBuf {
        // Use first 2 chars of ID as subdirectory to avoid too many files in one dir
        let prefix = &id[..2.min(id.len())];
        self.base_path.join(prefix).join(id)
    }

    /// Gets the full filesystem path for a stored file
    fn get_file_path(&self, id: &str, filename: &str) -> PathBuf {
        self.get_file_directory(id).join(filename)
    }

    /// Gets the path to the metadata file for a stored file
    fn get_metadata_path(&self, id: &str) -> PathBuf {
        self.get_file_directory(id).join(".metadata.json")
    }

    /// Ensures the storage directory exists
    async fn ensure_directory(&self, path: &Path) -> StorageResult<()> {
        fs::create_dir_all(path).await?;
        Ok(())
    }
}

#[async_trait]
impl FileStorage for LocalFileStorage {
    async fn store(&self, file: UploadedFile) -> StorageResult<StoredFile> {
        // Generate unique ID
        let id = Uuid::new_v4().to_string();

        // Create directory structure
        let dir = self.get_file_directory(&id);
        self.ensure_directory(&dir).await?;

        // Write file to disk
        let file_path = self.get_file_path(&id, &file.filename);
        let mut f = fs::File::create(&file_path).await?;
        f.write_all(&file.data).await?;
        f.flush().await?;

        // Create metadata
        let stored = StoredFile {
            id: id.clone(),
            filename: file.filename.clone(),
            content_type: file.content_type.clone(),
            size: file.size(),
            storage_path: file_path.to_string_lossy().to_string(),
        };

        // Write metadata to sidecar file
        let metadata_path = self.get_metadata_path(&id);
        let metadata_json = serde_json::to_string_pretty(&stored)
            .map_err(|e| StorageError::Other(format!("Failed to serialize metadata: {e}")))?;
        fs::write(&metadata_path, metadata_json).await?;

        Ok(stored)
    }

    async fn retrieve(&self, id: &str) -> StorageResult<Vec<u8>> {
        // We need to find the file by ID, but we don't know the filename
        // List files in the ID directory and read the first non-hidden file
        let dir = self.get_file_directory(id);

        if !dir.exists() {
            return Err(StorageError::NotFound(id.to_string()));
        }

        let mut entries = fs::read_dir(&dir).await?;

        // Read the first non-hidden file in the directory
        while let Some(entry) = entries.next_entry().await? {
            let file_path = entry.path();
            // Use async metadata check
            if let Ok(metadata) = entry.metadata().await {
                if metadata.is_file() {
                    // Skip hidden files (like .metadata.json)
                    if let Some(name) = file_path.file_name().and_then(|n| n.to_str()) {
                        if !name.starts_with('.') {
                            let data = fs::read(&file_path).await?;
                            return Ok(data);
                        }
                    }
                }
            }
        }

        Err(StorageError::NotFound(id.to_string()))
    }

    async fn delete(&self, id: &str) -> StorageResult<()> {
        let dir = self.get_file_directory(id);

        // Idempotent - don't error if directory doesn't exist
        if dir.exists() {
            fs::remove_dir_all(&dir).await?;
        }

        Ok(())
    }

    async fn url(&self, id: &str) -> StorageResult<String> {
        // For local storage, return a relative URL path
        // In production, this would be served by the web server
        let dir = self.get_file_directory(id);

        if !dir.exists() {
            return Err(StorageError::NotFound(id.to_string()));
        }

        let mut entries = fs::read_dir(&dir).await?;

        // Find the first non-hidden file
        while let Some(entry) = entries.next_entry().await? {
            let file_path = entry.path();
            // Use async metadata check
            if let Ok(metadata) = entry.metadata().await {
                if metadata.is_file() {
                    // Skip hidden files (like .metadata.json)
                    let filename = file_path
                        .file_name()
                        .and_then(|n| n.to_str())
                        .ok_or_else(|| StorageError::InvalidPath(format!("Invalid filename in {id}")))?;

                    if !filename.starts_with('.') {
                        // Use first 2 chars as prefix
                        let prefix = &id[..2.min(id.len())];
                        return Ok(format!("/uploads/{prefix}/{id}/{filename}"));
                    }
                }
            }
        }

        Err(StorageError::NotFound(id.to_string()))
    }

    async fn exists(&self, id: &str) -> StorageResult<bool> {
        let dir = self.get_file_directory(id);
        Ok(dir.exists())
    }

    async fn get_metadata(&self, id: &str) -> StorageResult<StoredFile> {
        let metadata_path = self.get_metadata_path(id);

        if !metadata_path.exists() {
            return Err(StorageError::NotFound(id.to_string()));
        }

        // Read and parse metadata JSON
        let metadata_json = fs::read_to_string(&metadata_path).await?;
        let stored: StoredFile = serde_json::from_str(&metadata_json)
            .map_err(|e| StorageError::Other(format!("Failed to parse metadata: {e}")))?;

        Ok(stored)
    }
}

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

    fn create_test_storage() -> (LocalFileStorage, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let storage = LocalFileStorage::new(temp_dir.path().to_path_buf()).unwrap();
        (storage, temp_dir)
    }

    #[tokio::test]
    async fn test_store_and_retrieve() {
        let (storage, _temp) = create_test_storage();

        let file = UploadedFile::new("test.txt", "text/plain", b"Hello, World!".to_vec());

        // Store
        let stored = storage.store(file).await.unwrap();
        assert!(!stored.id.is_empty());
        assert_eq!(stored.filename, "test.txt");
        assert_eq!(stored.size, 13);

        // Retrieve
        let data = storage.retrieve(&stored.id).await.unwrap();
        assert_eq!(data, b"Hello, World!");
    }

    #[tokio::test]
    async fn test_delete() {
        let (storage, _temp) = create_test_storage();

        let file = UploadedFile::new("test.txt", "text/plain", b"Test".to_vec());
        let stored = storage.store(file).await.unwrap();

        // Verify exists
        assert!(storage.exists(&stored.id).await.unwrap());

        // Delete
        storage.delete(&stored.id).await.unwrap();

        // Verify doesn't exist
        assert!(!storage.exists(&stored.id).await.unwrap());

        // Delete again (idempotent)
        storage.delete(&stored.id).await.unwrap();
    }

    #[tokio::test]
    async fn test_url_generation() {
        let (storage, _temp) = create_test_storage();

        let file = UploadedFile::new("photo.jpg", "image/jpeg", b"fake image".to_vec());
        let stored = storage.store(file).await.unwrap();

        let url = storage.url(&stored.id).await.unwrap();
        assert!(url.starts_with("/uploads/"));
        assert!(url.contains(&stored.id));
        assert!(url.ends_with("/photo.jpg"));
    }

    #[tokio::test]
    async fn test_retrieve_nonexistent() {
        let (storage, _temp) = create_test_storage();

        let result = storage.retrieve("nonexistent-id").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StorageError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_exists() {
        let (storage, _temp) = create_test_storage();

        // Nonexistent
        assert!(!storage.exists("nonexistent-id").await.unwrap());

        // Create file
        let file = UploadedFile::new("test.txt", "text/plain", b"Test".to_vec());
        let stored = storage.store(file).await.unwrap();

        // Should exist
        assert!(storage.exists(&stored.id).await.unwrap());
    }

    #[tokio::test]
    async fn test_directory_structure() {
        let (storage, temp) = create_test_storage();

        let file = UploadedFile::new("test.txt", "text/plain", b"Test".to_vec());
        let stored = storage.store(file).await.unwrap();

        // Verify directory structure: base/prefix/id/filename
        let prefix = &stored.id[..2];
        let expected_path = temp.path().join(prefix).join(&stored.id).join("test.txt");
        assert!(expected_path.exists());
    }

    #[tokio::test]
    async fn test_invalid_base_path() {
        // Try to create storage with a file instead of directory
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("not-a-directory");
        std::fs::write(&file_path, b"test").unwrap();

        let result = LocalFileStorage::new(file_path);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StorageError::InvalidPath(_)));
    }

    #[tokio::test]
    async fn test_get_metadata() {
        let (storage, _temp) = create_test_storage();

        let file = UploadedFile::new("document.pdf", "application/pdf", b"fake pdf".to_vec());
        let stored = storage.store(file).await.unwrap();

        // Get metadata
        let metadata = storage.get_metadata(&stored.id).await.unwrap();
        assert_eq!(metadata.id, stored.id);
        assert_eq!(metadata.filename, "document.pdf");
        assert_eq!(metadata.content_type, "application/pdf");
        assert_eq!(metadata.size, 8);
    }

    #[tokio::test]
    async fn test_get_metadata_preserves_content_type() {
        let (storage, _temp) = create_test_storage();

        // Store files with various content types
        let test_cases = vec![
            ("image.png", "image/png"),
            ("video.mp4", "video/mp4"),
            ("document.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
            ("data.json", "application/json"),
        ];

        for (filename, content_type) in test_cases {
            let file = UploadedFile::new(filename, content_type, b"test data".to_vec());
            let stored = storage.store(file).await.unwrap();

            // Verify metadata preserves original content type
            let metadata = storage.get_metadata(&stored.id).await.unwrap();
            assert_eq!(metadata.content_type, content_type, "Content type mismatch for {filename}");
            assert_eq!(metadata.filename, filename);
        }
    }

    #[tokio::test]
    async fn test_get_metadata_nonexistent() {
        let (storage, _temp) = create_test_storage();

        let result = storage.get_metadata("nonexistent-id").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), StorageError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_metadata_file_created() {
        let (storage, _temp) = create_test_storage();

        let file = UploadedFile::new("test.txt", "text/plain", b"Hello".to_vec());
        let stored = storage.store(file).await.unwrap();

        // Verify metadata file exists
        let metadata_path = storage.get_metadata_path(&stored.id);
        assert!(metadata_path.exists(), "Metadata file should exist");

        // Verify it's valid JSON with expected structure
        let metadata_json = std::fs::read_to_string(&metadata_path).unwrap();
        let metadata: StoredFile = serde_json::from_str(&metadata_json).unwrap();
        assert_eq!(metadata.id, stored.id);
        assert_eq!(metadata.filename, "test.txt");
        assert_eq!(metadata.content_type, "text/plain");
    }
}