squigit-storage 0.1.0

Persistent profiles, threads, and content-addressed storage for Squigit
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
// Copyright 2026 a7mddra
// SPDX-License-Identifier: Apache-2.0

//! Content-addressable storage for images and generic files.

use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use fs2::FileExt;

use crate::error::{Result, StorageError};
use crate::threads::ThreadStorage;

mod types;

pub use types::{
    AttachmentFileType, DocumentConversion, ObjectFileContext, ObjectManifest, ObjectRemote,
    ReverseImageSearchCache, StoredImage, OBJECT_MANIFEST_SCHEMA_VERSION,
};

const OBJECT_MANIFEST_FILE: &str = "manifest.json";
const CACHE_DIR: &str = "cache";
const DOCUMENT_CONVERSIONS_DIR: &str = "document-conversions";
const OBJECT_MANIFEST_LOCK_FILE: &str = "manifest.lock";

pub struct ObjectManifestLock {
    file: File,
}

impl Drop for ObjectManifestLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

fn normalize_extension(extension: &str) -> String {
    let normalized = extension
        .trim()
        .trim_start_matches('.')
        .to_ascii_lowercase();
    if normalized.is_empty() {
        "bin".to_string()
    } else {
        normalized
    }
}

fn validate_hash(hash: &str) -> Result<()> {
    if hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        Ok(())
    } else {
        Err(StorageError::InvalidHash)
    }
}

fn classify_extension(extension: &str) -> AttachmentFileType {
    match extension {
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "svg" => AttachmentFileType::ImageUpload,
        "pdf" => AttachmentFileType::DocumentUpload,
        _ => AttachmentFileType::TextLocal,
    }
}

fn atomic_write(path: &Path, contents: &[u8]) -> Result<()> {
    reject_symlink_or_non_regular(path)?;
    let parent = path.parent().ok_or(StorageError::InvalidHash)?;
    ensure_private_directory(parent)?;
    let file_name = path
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or("data");
    let temporary = path.with_file_name(format!(".{file_name}.tmp-{}", uuid::Uuid::new_v4()));
    let result = (|| -> Result<()> {
        let mut options = OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let mut file = options.open(&temporary)?;
        file.write_all(contents)?;
        file.sync_all()?;
        drop(file);

        crate::secure_file::replace_file(&temporary, path)?;
        set_private_file_permissions(path)?;
        crate::secure_file::sync_parent(parent)?;
        Ok(())
    })();
    if result.is_err() {
        let _ = fs::remove_file(temporary);
    }
    result
}

fn reject_symlink_or_non_regular(path: &Path) -> Result<()> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            Err(StorageError::KeyStore(format!(
                "refusing unsafe CAS metadata target: {}",
                path.display()
            )))
        }
        Ok(_) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn ensure_private_directory(path: &Path) -> Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(StorageError::KeyStore(format!(
            "refusing unsafe CAS directory: {}",
            path.display()
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
    }
    Ok(())
}

fn set_private_file_permissions(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
    }
    Ok(())
}

impl ThreadStorage {
    /// Store image bytes using content-addressable storage.
    ///
    /// Returns the hash and path to the stored image.
    /// If the image already exists with the same hash, returns the existing path.
    pub fn store_image(&self, bytes: &[u8], explicit_tone: Option<String>) -> Result<StoredImage> {
        if bytes.is_empty() {
            return Err(StorageError::EmptyImage);
        }

        let hash = blake3::hash(bytes).to_hex().to_string();
        self.store_object(bytes, &hash, "png", explicit_tone)
    }

    /// Store an image from a file path.
    pub fn store_image_from_path(
        &self,
        path: &str,
        explicit_tone: Option<String>,
    ) -> Result<StoredImage> {
        let mut file = File::open(path)?;
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        let extension = Path::new(path)
            .extension()
            .and_then(|value| value.to_str())
            .unwrap_or("png");
        let hash = blake3::hash(&buffer).to_hex().to_string();
        self.store_object(&buffer, &hash, extension, explicit_tone)
    }

    /// Store a generic file using content-addressable storage, preserving the extension.
    pub fn store_file(
        &self,
        bytes: &[u8],
        extension: &str,
        explicit_tone: Option<String>,
    ) -> Result<StoredImage> {
        let hash = blake3::hash(bytes).to_hex().to_string();
        self.store_object(bytes, &hash, extension, explicit_tone)
    }

    fn store_object(
        &self,
        bytes: &[u8],
        hash: &str,
        extension: &str,
        explicit_tone: Option<String>,
    ) -> Result<StoredImage> {
        let extension = normalize_extension(extension);
        let object_dir = self.object_dir(hash)?;
        let existing_path = self.find_object_blob(hash).ok();
        let manifest_path = object_dir.join(OBJECT_MANIFEST_FILE);
        let new_file_context = if manifest_path.exists() {
            None
        } else {
            let file_type = classify_extension(&extension);
            let file_brief = if file_type == AttachmentFileType::TextLocal {
                Some(std::str::from_utf8(bytes)?.to_string())
            } else {
                None
            };
            Some(ObjectFileContext {
                file_type,
                image_tone: None,
                file_brief,
            })
        };
        fs::create_dir_all(&object_dir)?;
        let file_path = existing_path
            .clone()
            .unwrap_or_else(|| object_dir.join(format!("{hash}.{extension}")));
        if existing_path.is_none() {
            let mut file = File::create(&file_path)?;
            file.write_all(bytes)?;
        }

        let mut manifest = if manifest_path.exists() {
            self.load_object_manifest(hash)?
        } else {
            ObjectManifest::new(new_file_context.expect("new object context must exist"))
        };

        if manifest.file_context.file_type == AttachmentFileType::ImageUpload {
            let tone = explicit_tone
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string)
                .or_else(|| manifest.file_context.image_tone.clone())
                .unwrap_or_else(|| "dark".to_string());
            manifest.file_context.image_tone = Some(tone);
        }
        self.save_object_manifest(hash, &manifest)?;

        Ok(StoredImage {
            hash: hash.to_string(),
            path: file_path.to_string_lossy().to_string(),
            tone: manifest.file_context.image_tone,
        })
    }

    pub fn object_dir(&self, hash: &str) -> Result<PathBuf> {
        validate_hash(hash)?;
        let prefix = hash.get(..2).ok_or(StorageError::InvalidHash)?;
        Ok(self.objects_dir.join(prefix).join(hash))
    }

    fn document_conversion_path(
        &self,
        source_hash: &str,
        source_extension: &str,
    ) -> Result<PathBuf> {
        validate_hash(source_hash)?;
        let source_extension = normalize_extension(source_extension);
        if !matches!(source_extension.as_str(), "docx" | "xlsx" | "pptx") {
            return Err(StorageError::InvalidDocumentConversion(
                "source extension must be docx, xlsx, or pptx".to_string(),
            ));
        }
        let prefix = source_hash.get(..2).ok_or(StorageError::InvalidHash)?;
        let config_root = self.objects_dir.parent().ok_or(StorageError::NoDataDir)?;
        Ok(config_root
            .join(CACHE_DIR)
            .join(DOCUMENT_CONVERSIONS_DIR)
            .join(prefix)
            .join(format!("{source_hash}.{source_extension}.json")))
    }

    pub fn load_document_conversion(
        &self,
        source_hash: &str,
        source_extension: &str,
    ) -> Result<Option<DocumentConversion>> {
        let path = self.document_conversion_path(source_hash, source_extension)?;
        if !path.exists() {
            return Ok(None);
        }
        let conversion = serde_json::from_slice::<DocumentConversion>(&fs::read(path)?)?;
        validate_hash(&conversion.source_hash)?;
        validate_hash(&conversion.pdf_hash)?;
        let expected_extension = normalize_extension(source_extension);
        if !conversion.source_hash.eq_ignore_ascii_case(source_hash)
            || conversion.source_extension != expected_extension
        {
            return Err(StorageError::InvalidDocumentConversion(
                "conversion receipt does not match its source identity".to_string(),
            ));
        }
        Ok(Some(conversion))
    }

    pub fn save_document_conversion(&self, conversion: &DocumentConversion) -> Result<()> {
        validate_hash(&conversion.source_hash)?;
        validate_hash(&conversion.pdf_hash)?;
        if conversion.recipe.trim().is_empty() {
            return Err(StorageError::InvalidDocumentConversion(
                "conversion recipe cannot be empty".to_string(),
            ));
        }
        let path =
            self.document_conversion_path(&conversion.source_hash, &conversion.source_extension)?;
        let parent = path
            .parent()
            .ok_or_else(|| StorageError::InvalidDocumentConversion("invalid path".to_string()))?;
        fs::create_dir_all(parent)?;
        atomic_write(&path, serde_json::to_vec_pretty(conversion)?.as_slice())
    }

    pub fn object_manifest_path(&self, hash: &str) -> Result<PathBuf> {
        Ok(self.object_dir(hash)?.join(OBJECT_MANIFEST_FILE))
    }

    pub fn find_object_blob(&self, hash: &str) -> Result<PathBuf> {
        let object_dir = self.object_dir(hash)?;
        let entries =
            fs::read_dir(&object_dir).map_err(|_| StorageError::ImageNotFound(hash.to_string()))?;
        for entry in entries {
            let path = entry?.path();
            let is_blob = path.is_file()
                && path.file_stem().and_then(|value| value.to_str()) == Some(hash)
                && path.file_name().and_then(|value| value.to_str()) != Some(OBJECT_MANIFEST_FILE);
            if is_blob {
                return Ok(path);
            }
        }
        Err(StorageError::ImageNotFound(hash.to_string()))
    }

    pub fn load_object_manifest(&self, hash: &str) -> Result<ObjectManifest> {
        let path = self.object_manifest_path(hash)?;
        reject_symlink_or_non_regular(&path)?;
        let json = fs::read_to_string(path)?;
        let manifest: ObjectManifest = serde_json::from_str(&json).map_err(|error| {
            StorageError::KeyStore(format!("malformed-object-manifest: {error}"))
        })?;
        manifest.validate().map_err(|error| {
            StorageError::KeyStore(format!("malformed-object-manifest: {error}"))
        })?;
        Ok(manifest)
    }

    pub fn save_object_manifest(&self, hash: &str, manifest: &ObjectManifest) -> Result<()> {
        manifest.validate().map_err(|error| {
            StorageError::KeyStore(format!("malformed-object-manifest: {error}"))
        })?;
        let path = self.object_manifest_path(hash)?;
        let parent = path.parent().ok_or(StorageError::InvalidHash)?;
        fs::create_dir_all(parent)?;
        atomic_write(&path, serde_json::to_string_pretty(manifest)?.as_bytes())
    }

    pub fn lock_object_manifest(&self, hash: &str) -> Result<ObjectManifestLock> {
        let object_dir = self.object_dir(hash)?;
        fs::create_dir_all(&object_dir)?;
        ensure_private_directory(&object_dir)?;
        let lock_path = object_dir.join(OBJECT_MANIFEST_LOCK_FILE);
        reject_symlink_or_non_regular(&lock_path)?;
        let mut options = OpenOptions::new();
        options.read(true).write(true).create(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let file = options.open(&lock_path)?;
        set_private_file_permissions(&lock_path)?;
        file.lock_exclusive()?;
        Ok(ObjectManifestLock { file })
    }

    pub fn has_object_remotes(&self) -> Result<bool> {
        if !self.objects_dir.exists() {
            return Ok(false);
        }
        for prefix in fs::read_dir(&self.objects_dir)? {
            let prefix = prefix?.path();
            if !prefix.is_dir() {
                continue;
            }
            for object in fs::read_dir(prefix)? {
                let object = object?.path();
                let Some(hash) = object.file_name().and_then(|value| value.to_str()) else {
                    continue;
                };
                if validate_hash(hash).is_err() {
                    continue;
                }
                let manifest_path = object.join(OBJECT_MANIFEST_FILE);
                if !manifest_path.exists() {
                    continue;
                }
                if !self.load_object_manifest(hash)?.object_remotes.is_empty() {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    /// Get the canonical blob path by hash.
    pub fn get_image_path(&self, hash: &str) -> Result<String> {
        self.find_object_blob(hash)
            .map(|path| path.to_string_lossy().to_string())
    }

    /// Get the cached tone for a stored image by hash.
    pub fn get_image_tone(&self, hash: &str) -> Option<String> {
        self.load_object_manifest(hash)
            .ok()
            .and_then(|manifest| manifest.file_context.image_tone)
    }

    pub fn get_reverse_image_search_cache(
        &self,
        hash: &str,
    ) -> Result<Option<ReverseImageSearchCache>> {
        self.load_object_manifest(hash)
            .map(|manifest| manifest.reverse_image_search)
    }

    pub fn save_reverse_image_search_cache(
        &self,
        hash: &str,
        imgbb_url: String,
        google_lens_url: String,
    ) -> Result<()> {
        let _lock = self.lock_object_manifest(hash)?;
        let mut manifest = self.load_object_manifest(hash)?;
        manifest.reverse_image_search = Some(ReverseImageSearchCache {
            imgbb_url,
            google_lens_url,
            created_at: chrono::Utc::now(),
        });
        self.save_object_manifest(hash, &manifest)
    }
}