suture-core 0.8.0

A patch-based version control system with semantic merge and format-aware drivers
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
//! Pack file support for the Content Addressable Storage.
//!
//! Pack files bundle multiple blobs into a single file, reducing
//! filesystem overhead for repositories with many small objects.

use crate::cas::compressor;
use crate::cas::hasher;
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufReader, Read, Seek, SeekFrom};
use std::path::PathBuf;
use suture_common::Hash;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum PackError {
    #[error("invalid pack magic: {0}")]
    InvalidMagic(String),
    #[error("unsupported pack version: {0}")]
    UnsupportedVersion(u32),
    #[error("invalid index magic: {0}")]
    InvalidIndexMagic(String),
    #[error("blob not found in pack: {0}")]
    BlobNotFound(String),
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),
    #[error("compression error: {0}")]
    CompressionError(String),
    #[error("decompression error: {0}")]
    DecompressionError(String),
    #[error("cannot create empty pack")]
    EmptyPack,
    #[error("unexpected object type: {0}")]
    UnexpectedObjectType(u8),
    #[error("hash mismatch in pack: expected {expected}, got {actual}")]
    HashMismatch { expected: String, actual: String },
}

const PACK_MAGIC: &[u8; 4] = b"SPCK";
const INDEX_MAGIC: &[u8; 4] = b"SIDX";
const PACK_VERSION: u32 = 1;
const TYPE_BLOB: u8 = 1;

#[derive(Clone, Debug)]
struct PackIndexEntry {
    hash: Hash,
    offset: u64,
}

#[derive(Clone, Debug)]
pub struct PackIndex {
    entries: Vec<PackIndexEntry>,
}

#[allow(dead_code)]
impl PackIndex {
    pub fn load(path: &std::path::Path) -> Result<Self, PackError> {
        let file = fs::File::open(path)?;
        let mut reader = BufReader::new(file);

        let mut magic = [0u8; 4];
        reader.read_exact(&mut magic)?;
        if &magic != INDEX_MAGIC {
            return Err(PackError::InvalidIndexMagic(
                String::from_utf8_lossy(&magic).to_string(),
            ));
        }

        let mut version = [0u8; 4];
        reader.read_exact(&mut version)?;
        let version = u32::from_le_bytes(version);
        if version != PACK_VERSION {
            return Err(PackError::UnsupportedVersion(version));
        }

        let mut count = [0u8; 4];
        reader.read_exact(&mut count)?;
        let count = u32::from_le_bytes(count) as usize;

        let mut entries = Vec::with_capacity(count);
        for _ in 0..count {
            let mut hash_bytes = [0u8; 32];
            reader.read_exact(&mut hash_bytes)?;
            let mut offset_bytes = [0u8; 8];
            reader.read_exact(&mut offset_bytes)?;
            entries.push(PackIndexEntry {
                hash: Hash::from(hash_bytes),
                offset: u64::from_le_bytes(offset_bytes),
            });
        }

        entries.sort_by_key(|e| e.hash);

        Ok(Self { entries })
    }

    pub fn find(&self, hash: &Hash) -> Option<u64> {
        self.entries
            .binary_search_by_key(hash, |e| e.hash)
            .ok()
            .map(|idx| self.entries[idx].offset)
    }

    pub fn hashes(&self) -> Vec<Hash> {
        self.entries.iter().map(|e| e.hash).collect()
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

pub struct PackFile;

impl PackFile {
    pub fn create(
        pack_dir: &std::path::Path,
        objects: &[(Hash, Vec<u8>)],
    ) -> Result<(PathBuf, PathBuf), PackError> {
        if objects.is_empty() {
            return Err(PackError::EmptyPack);
        }

        fs::create_dir_all(pack_dir)?;

        let mut pack_data = Vec::new();
        let mut index_entries = Vec::new();

        pack_data.extend_from_slice(PACK_MAGIC);
        pack_data.extend_from_slice(&PACK_VERSION.to_le_bytes());
        pack_data.extend_from_slice(&(objects.len() as u32).to_le_bytes());

        for (hash, data) in objects {
            let offset = pack_data.len() as u64;

            let compressed = compressor::compress(data, compressor::DEFAULT_COMPRESSION_LEVEL)
                .map_err(|e| PackError::CompressionError(e.to_string()))?;

            pack_data.push(TYPE_BLOB);
            pack_data.extend_from_slice(&(data.len() as u32).to_le_bytes());
            pack_data.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
            pack_data.extend_from_slice(&hash.0);
            pack_data.extend_from_slice(&compressed);

            index_entries.push(PackIndexEntry {
                hash: *hash,
                offset,
            });
        }

        let index_data = Self::serialize_index(&index_entries);
        let index_hash = hasher::hash_bytes(&index_data);
        let name = format!("pack-{}", index_hash.to_hex());

        let pack_path = pack_dir.join(format!("{}.pack", name));
        let idx_path = pack_dir.join(format!("{}.idx", name));

        fs::write(&pack_path, &pack_data)?;
        fs::write(&idx_path, &index_data)?;

        Ok((pack_path, idx_path))
    }

    fn serialize_index(entries: &[PackIndexEntry]) -> Vec<u8> {
        let mut data = Vec::new();
        data.extend_from_slice(INDEX_MAGIC);
        data.extend_from_slice(&PACK_VERSION.to_le_bytes());
        data.extend_from_slice(&(entries.len() as u32).to_le_bytes());

        for entry in entries {
            data.extend_from_slice(&entry.hash.0);
            data.extend_from_slice(&entry.offset.to_le_bytes());
        }

        data
    }

    pub fn read_blob(
        pack_path: &std::path::Path,
        index: &PackIndex,
        hash: &Hash,
    ) -> Result<Vec<u8>, PackError> {
        let offset = index
            .find(hash)
            .ok_or_else(|| PackError::BlobNotFound(hash.to_hex()))?;

        let file = fs::File::open(pack_path)?;
        let mut reader = BufReader::new(file);

        reader.seek(SeekFrom::Start(offset))?;

        let mut type_byte = [0u8; 1];
        reader.read_exact(&mut type_byte)?;
        if type_byte[0] != TYPE_BLOB {
            return Err(PackError::UnexpectedObjectType(type_byte[0]));
        }

        let mut uncomp_size = [0u8; 4];
        reader.read_exact(&mut uncomp_size)?;
        let _uncomp_size = u32::from_le_bytes(uncomp_size) as usize;

        let mut comp_size = [0u8; 4];
        reader.read_exact(&mut comp_size)?;
        let comp_size = u32::from_le_bytes(comp_size) as usize;

        let mut stored_hash = [0u8; 32];
        reader.read_exact(&mut stored_hash)?;

        let mut compressed = vec![0u8; comp_size];
        reader.read_exact(&mut compressed)?;

        let data = compressor::decompress(&compressed)
            .map_err(|e| PackError::DecompressionError(e.to_string()))?;

        let actual_hash = hasher::hash_bytes(&data);
        if actual_hash != *hash {
            return Err(PackError::HashMismatch {
                expected: hash.to_hex(),
                actual: actual_hash.to_hex(),
            });
        }

        Ok(data)
    }

    pub fn list_packs(pack_dir: &std::path::Path) -> io::Result<Vec<PathBuf>> {
        if !pack_dir.exists() {
            return Ok(Vec::new());
        }
        let mut packs = Vec::new();
        for entry in fs::read_dir(pack_dir)? {
            let entry = entry?;
            if let Some(name) = entry.file_name().to_str()
                && name.ends_with(".pack")
            {
                packs.push(entry.path());
            }
        }
        packs.sort();
        Ok(packs)
    }
}

/// Cache of loaded pack indices for efficient lookup.
#[derive(Debug)]
pub struct PackCache {
    indices: HashMap<PathBuf, PackIndex>,
}

#[allow(dead_code)]
impl PackCache {
    pub fn new() -> Self {
        Self {
            indices: HashMap::new(),
        }
    }

    /// Load all pack indices from the pack directory.
    pub fn load_all(pack_dir: &std::path::Path) -> Result<Self, PackError> {
        let mut cache = Self::new();
        let pack_files = PackFile::list_packs(pack_dir)?;

        for pack_path in &pack_files {
            let idx_path = pack_path.with_extension("idx");
            if idx_path.exists() {
                let index = PackIndex::load(&idx_path)?;
                cache.indices.insert(pack_path.clone(), index);
            }
        }

        Ok(cache)
    }

    /// Find a hash across all loaded pack indices, returning the pack path and offset.
    pub fn find(&self, hash: &Hash) -> Option<(&PathBuf, u64)> {
        for (pack_path, index) in &self.indices {
            if let Some(offset) = index.find(hash) {
                return Some((pack_path, offset));
            }
        }
        None
    }

    /// List all hashes across all loaded pack indices.
    pub fn all_hashes(&self) -> Vec<Hash> {
        let mut hashes = Vec::new();
        for index in self.indices.values() {
            hashes.extend(index.hashes());
        }
        hashes.sort();
        hashes.dedup();
        hashes
    }

    /// Number of pack files loaded.
    pub fn pack_count(&self) -> usize {
        self.indices.len()
    }

    /// Total number of objects across all packs.
    pub fn object_count(&self) -> usize {
        self.indices.values().map(|i| i.len()).sum()
    }
}

impl Default for PackCache {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn make_test_objects() -> Vec<(Hash, Vec<u8>)> {
        vec![
            {
                let data = b"hello, world!".to_vec();
                let hash = hasher::hash_bytes(&data);
                (hash, data)
            },
            {
                let data = b"second blob content".to_vec();
                let hash = hasher::hash_bytes(&data);
                (hash, data)
            },
            {
                let data = vec![0u8; 1024];
                let hash = hasher::hash_bytes(&data);
                (hash, data)
            },
        ]
    }

    #[test]
    fn test_pack_create_and_read() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let objects = make_test_objects();

        let (pack_path, idx_path) = PackFile::create(&pack_dir, &objects).unwrap();
        assert!(pack_path.exists());
        assert!(idx_path.exists());
        assert!(pack_path.to_str().unwrap().ends_with(".pack"));
        assert!(idx_path.to_str().unwrap().ends_with(".idx"));

        let index = PackIndex::load(&idx_path).unwrap();
        assert_eq!(index.len(), 3);

        for (hash, data) in &objects {
            let retrieved = PackFile::read_blob(&pack_path, &index, hash).unwrap();
            assert_eq!(*data, retrieved);
        }
    }

    #[test]
    fn test_pack_index_sorted() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let objects = make_test_objects();

        let (_, idx_path) = PackFile::create(&pack_dir, &objects).unwrap();
        let index = PackIndex::load(&idx_path).unwrap();

        let hashes = index.hashes();
        let mut sorted = hashes.clone();
        sorted.sort();
        assert_eq!(hashes, sorted);
    }

    #[test]
    fn test_pack_index_find_missing() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let objects = make_test_objects();

        let (_, idx_path) = PackFile::create(&pack_dir, &objects).unwrap();
        let index = PackIndex::load(&idx_path).unwrap();

        let missing = Hash::from_hex(&"f".repeat(64)).unwrap();
        assert!(index.find(&missing).is_none());
    }

    #[test]
    fn test_pack_create_empty_fails() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let result = PackFile::create(&pack_dir, &[]);
        assert!(matches!(result, Err(PackError::EmptyPack)));
    }

    #[test]
    fn test_pack_list_packs() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");

        assert_eq!(PackFile::list_packs(&pack_dir).unwrap().len(), 0);

        let objects = make_test_objects();
        PackFile::create(&pack_dir, &objects).unwrap();

        let packs = PackFile::list_packs(&pack_dir).unwrap();
        assert_eq!(packs.len(), 1);
        assert!(packs[0].to_str().unwrap().ends_with(".pack"));
    }

    #[test]
    fn test_pack_cache() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let objects = make_test_objects();

        PackFile::create(&pack_dir, &objects).unwrap();

        let cache = PackCache::load_all(&pack_dir).unwrap();
        assert_eq!(cache.pack_count(), 1);
        assert_eq!(cache.object_count(), 3);

        let all_hashes = cache.all_hashes();
        assert_eq!(all_hashes.len(), 3);

        for (hash, _data) in &objects {
            let (pack_path, offset) = cache.find(hash).unwrap();
            assert!(pack_path.exists());
            assert!(offset > 0);
        }
    }

    #[test]
    fn test_pack_cache_missing() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let objects = make_test_objects();

        PackFile::create(&pack_dir, &objects).unwrap();

        let cache = PackCache::load_all(&pack_dir).unwrap();
        let missing = Hash::from_hex(&"a".repeat(64)).unwrap();
        assert!(cache.find(&missing).is_none());
    }

    #[test]
    fn test_pack_invalid_magic() {
        let dir = tempfile::tempdir().unwrap();
        let bad_idx = dir.path().join("bad.idx");
        fs::write(&bad_idx, b"XXXX").unwrap();

        let result = PackIndex::load(&bad_idx);
        assert!(matches!(result, Err(PackError::InvalidIndexMagic(_))));
    }

    #[test]
    fn test_pack_single_object() {
        let dir = tempfile::tempdir().unwrap();
        let pack_dir = dir.path().join("pack");
        let data = b"single object".to_vec();
        let hash = hasher::hash_bytes(&data);

        let (pack_path, idx_path) = PackFile::create(&pack_dir, &[(hash, data.clone())]).unwrap();

        let index = PackIndex::load(&idx_path).unwrap();
        assert_eq!(index.len(), 1);

        let retrieved = PackFile::read_blob(&pack_path, &index, &hash).unwrap();
        assert_eq!(data, retrieved);
    }
}