pacha 0.2.5

Model, Data and Recipe Registry with full lineage tracking
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
//! Object store for content-addressed artifact storage.

use crate::error::{PachaError, Result};
use crate::storage::ContentAddress;
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

/// Content-addressed object store.
///
/// Stores artifacts using BLAKE3 hash prefixes for sharding:
/// ```text
/// objects/
/// ├── ab/
/// │   └── cdef1234...
/// ├── cd/
/// │   └── ef5678...
/// └── ...
/// ```
#[derive(Debug)]
pub struct ObjectStore {
    /// Base path for object storage.
    base_path: PathBuf,
}

impl ObjectStore {
    /// Create a new object store at the given path.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be created.
    pub fn new<P: AsRef<Path>>(base_path: P) -> Result<Self> {
        let base_path = base_path.as_ref().to_path_buf();
        fs::create_dir_all(&base_path)?;
        Ok(Self { base_path })
    }

    /// Open an existing object store.
    ///
    /// # Errors
    ///
    /// Returns an error if the path doesn't exist.
    pub fn open<P: AsRef<Path>>(base_path: P) -> Result<Self> {
        let base_path = base_path.as_ref().to_path_buf();
        if !base_path.exists() {
            return Err(PachaError::NotInitialized(base_path));
        }
        Ok(Self { base_path })
    }

    /// Get the base path.
    #[must_use]
    pub fn base_path(&self) -> &Path {
        &self.base_path
    }

    /// Store bytes and return their content address.
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    pub fn put(&self, data: &[u8]) -> Result<ContentAddress> {
        let addr = ContentAddress::from_bytes(data);
        self.put_with_address(data, &addr)?;
        Ok(addr)
    }

    /// Store bytes at a specific content address.
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails or hash doesn't match.
    pub fn put_with_address(&self, data: &[u8], addr: &ContentAddress) -> Result<()> {
        // Verify hash matches
        if !addr.verify(data) {
            return Err(PachaError::HashMismatch {
                expected: addr.hash_hex(),
                actual: ContentAddress::from_bytes(data).hash_hex(),
            });
        }

        let path = self.object_path(addr);

        // Skip if already exists (content-addressed = idempotent)
        if path.exists() {
            return Ok(());
        }

        // Create parent directory
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Write atomically via temp file
        let temp_path = path.with_extension("tmp");
        {
            let file = File::create(&temp_path)?;
            let mut writer = BufWriter::new(file);
            writer.write_all(data)?;
            writer.flush()?;
        }

        // Atomic rename
        fs::rename(&temp_path, &path)?;

        Ok(())
    }

    /// Store from a reader and return content address.
    ///
    /// # Errors
    ///
    /// Returns an error if reading or writing fails.
    pub fn put_reader<R: Read>(&self, mut reader: R) -> Result<ContentAddress> {
        // Read all data first to compute hash
        let mut data = Vec::new();
        reader.read_to_end(&mut data)?;
        self.put(&data)
    }

    /// Get data by content address.
    ///
    /// # Errors
    ///
    /// Returns an error if the object doesn't exist or reading fails.
    pub fn get(&self, addr: &ContentAddress) -> Result<Vec<u8>> {
        let path = self.object_path(addr);

        if !path.exists() {
            return Err(PachaError::NotFound {
                kind: "object".to_string(),
                name: addr.hash_hex(),
                version: "n/a".to_string(),
            });
        }

        let file = File::open(&path)?;
        let mut reader = BufReader::new(file);
        let capacity = usize::try_from(addr.size()).unwrap_or(0);
        let mut data = Vec::with_capacity(capacity);
        reader.read_to_end(&mut data)?;

        // Verify integrity
        if !addr.verify(&data) {
            return Err(PachaError::HashMismatch {
                expected: addr.hash_hex(),
                actual: ContentAddress::from_bytes(&data).hash_hex(),
            });
        }

        Ok(data)
    }

    /// Check if an object exists.
    #[must_use]
    pub fn exists(&self, addr: &ContentAddress) -> bool {
        self.object_path(addr).exists()
    }

    /// Delete an object by content address.
    ///
    /// # Errors
    ///
    /// Returns an error if deletion fails.
    pub fn delete(&self, addr: &ContentAddress) -> Result<bool> {
        let path = self.object_path(addr);

        if !path.exists() {
            return Ok(false);
        }

        fs::remove_file(&path)?;

        // Try to remove empty parent directory
        if let Some(parent) = path.parent() {
            let _ = fs::remove_dir(parent); // Ignore if not empty
        }

        Ok(true)
    }

    /// List all content addresses in the store.
    ///
    /// # Errors
    ///
    /// Returns an error if reading the directory fails.
    pub fn list(&self) -> Result<Vec<String>> {
        let mut addresses = Vec::new();

        if !self.base_path.exists() {
            return Ok(addresses);
        }

        for prefix_entry in fs::read_dir(&self.base_path)? {
            let prefix_entry = prefix_entry?;
            if !prefix_entry.file_type()?.is_dir() {
                continue;
            }

            for entry in fs::read_dir(prefix_entry.path())? {
                let entry = entry?;
                if entry.file_type()?.is_file() {
                    if let Some(name) = entry.file_name().to_str() {
                        // Skip temp files (we always create .tmp lowercase)
                        #[allow(clippy::case_sensitive_file_extension_comparisons)]
                        if !name.ends_with(".tmp") {
                            addresses.push(name.to_string());
                        }
                    }
                }
            }
        }

        Ok(addresses)
    }

    /// Get total size of all stored objects in bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if reading fails.
    pub fn total_size(&self) -> Result<u64> {
        let mut total = 0u64;

        if !self.base_path.exists() {
            return Ok(0);
        }

        for prefix_entry in fs::read_dir(&self.base_path)? {
            let prefix_entry = prefix_entry?;
            if !prefix_entry.file_type()?.is_dir() {
                continue;
            }

            for entry in fs::read_dir(prefix_entry.path())? {
                let entry = entry?;
                if entry.file_type()?.is_file() {
                    total += entry.metadata()?.len();
                }
            }
        }

        Ok(total)
    }

    /// Get the file path for a content address.
    fn object_path(&self, addr: &ContentAddress) -> PathBuf {
        self.base_path
            .join(addr.storage_prefix())
            .join(addr.hash_hex())
    }
}

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

    fn setup() -> (TempDir, ObjectStore) {
        let dir = TempDir::new().unwrap();
        let store = ObjectStore::new(dir.path().join("objects")).unwrap();
        (dir, store)
    }

    #[test]
    fn test_put_and_get() {
        let (_dir, store) = setup();
        let data = b"hello world";

        let addr = store.put(data).unwrap();
        assert_eq!(addr.size(), 11);

        let retrieved = store.get(&addr).unwrap();
        assert_eq!(retrieved, data);
    }

    #[test]
    fn test_put_idempotent() {
        let (_dir, store) = setup();
        let data = b"test data";

        let addr1 = store.put(data).unwrap();
        let addr2 = store.put(data).unwrap();

        assert_eq!(addr1, addr2);
    }

    #[test]
    fn test_exists() {
        let (_dir, store) = setup();
        let data = b"test";

        let addr = ContentAddress::from_bytes(data);
        assert!(!store.exists(&addr));

        store.put(data).unwrap();
        assert!(store.exists(&addr));
    }

    #[test]
    fn test_delete() {
        let (_dir, store) = setup();
        let data = b"delete me";

        let addr = store.put(data).unwrap();
        assert!(store.exists(&addr));

        let deleted = store.delete(&addr).unwrap();
        assert!(deleted);
        assert!(!store.exists(&addr));

        // Delete non-existent returns false
        let deleted_again = store.delete(&addr).unwrap();
        assert!(!deleted_again);
    }

    #[test]
    fn test_get_not_found() {
        let (_dir, store) = setup();
        let addr = ContentAddress::from_bytes(b"nonexistent");

        let result = store.get(&addr);
        assert!(matches!(result, Err(PachaError::NotFound { .. })));
    }

    #[test]
    fn test_put_with_wrong_address() {
        let (_dir, store) = setup();
        let data = b"actual data";
        let wrong_addr = ContentAddress::from_bytes(b"different data");

        let result = store.put_with_address(data, &wrong_addr);
        assert!(matches!(result, Err(PachaError::HashMismatch { .. })));
    }

    #[test]
    fn test_list() {
        let (_dir, store) = setup();

        store.put(b"one").unwrap();
        store.put(b"two").unwrap();
        store.put(b"three").unwrap();

        let addresses = store.list().unwrap();
        assert_eq!(addresses.len(), 3);
    }

    #[test]
    fn test_total_size() {
        let (_dir, store) = setup();

        store.put(b"12345").unwrap();
        store.put(b"67890").unwrap();

        let size = store.total_size().unwrap();
        assert_eq!(size, 10);
    }

    #[test]
    fn test_open_nonexistent() {
        let dir = TempDir::new().unwrap();
        let result = ObjectStore::open(dir.path().join("nonexistent"));
        assert!(matches!(result, Err(PachaError::NotInitialized(_))));
    }

    // Property-based tests
    proptest! {
        #[test]
        fn prop_roundtrip(data: Vec<u8>) {
            let dir = TempDir::new().unwrap();
            let store = ObjectStore::new(dir.path().join("objects")).unwrap();

            let addr = store.put(&data).unwrap();
            let retrieved = store.get(&addr).unwrap();

            prop_assert_eq!(data, retrieved);
        }

        #[test]
        fn prop_idempotent(data: Vec<u8>) {
            let dir = TempDir::new().unwrap();
            let store = ObjectStore::new(dir.path().join("objects")).unwrap();

            let addr1 = store.put(&data).unwrap();
            let addr2 = store.put(&data).unwrap();

            prop_assert_eq!(addr1, addr2);
        }

        #[test]
        fn prop_deduplication(data: Vec<u8>) {
            let dir = TempDir::new().unwrap();
            let store = ObjectStore::new(dir.path().join("objects")).unwrap();

            // Store same data twice
            store.put(&data).unwrap();
            store.put(&data).unwrap();

            // Should only have one object
            let addresses = store.list().unwrap();
            prop_assert_eq!(addresses.len(), 1);
        }
    }
}