1use std::collections::HashMap;
13use std::fs::File;
14use std::io::{Read, Seek, SeekFrom};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use crate::common_config::StrategicConfig;
19use crate::meta::BlobMeta;
20use crate::plugin::ExtensionRow;
21use crate::{decompress_archive};
22use anyhow::Result;
23use arrow::array::{
24 Array, ArrayRef, BooleanBuilder, FixedSizeBinaryBuilder, Int8Builder, StringBuilder,
25 UInt32Builder, UInt64Builder,
26};
27use arrow::datatypes::{DataType, Field, Schema};
28use arrow::record_batch::RecordBatch;
29use once_cell::sync::Lazy;
30
31pub type FileExtMeta = Option<(i8, ExtensionRow)>;
34
35pub static ZNIPPY_INDEX_SCHEMA: Lazy<Arc<Schema>> = Lazy::new(|| {
40 Arc::new(Schema::new(base_index_fields()))
41});
42
43fn base_index_fields() -> Vec<Field> {
44 vec![
45 Field::new("relative_path", DataType::Utf8, false),
46 Field::new("chunk_seq", DataType::UInt32, false),
47 Field::new("fdata_offset", DataType::UInt64, false),
48 Field::new("compressed", DataType::Boolean, false),
49 Field::new("uncompressed_size", DataType::UInt64, false),
50 Field::new("blob_offset", DataType::UInt64, false),
51 Field::new("blob_size", DataType::UInt64, false),
52 Field::new("checksum", DataType::FixedSizeBinary(32), false),
53 ]
54}
55
56pub fn znippy_index_schema() -> &'static Arc<Schema> {
57 &ZNIPPY_INDEX_SCHEMA
58}
59
60pub fn compose_index_schema(ext_fields: &[Field]) -> Arc<Schema> {
64 let mut fields = base_index_fields();
65 if !ext_fields.is_empty() {
66 fields.push(Field::new("pkg_type", DataType::Int8, true));
67 fields.extend(ext_fields.iter().cloned());
68 }
69 Arc::new(Schema::new(fields))
70}
71
72pub const ZNIPPY_FORMAT_VERSION: u32 = 3;
78
79pub const FORMAT_VERSION_KEY: &str = "znippy_format_version";
81
82pub fn check_format_version(metadata: &HashMap<String, String>) -> Result<()> {
87 if let Some(raw) = metadata.get(FORMAT_VERSION_KEY) {
88 let version: u32 = raw
89 .parse()
90 .map_err(|_| anyhow::anyhow!("invalid znippy archive format version {raw:?}"))?;
91 anyhow::ensure!(
92 version <= ZNIPPY_FORMAT_VERSION,
93 "znippy archive format v{version} is newer than this reader supports \
94 (max v{ZNIPPY_FORMAT_VERSION}) — upgrade znippy",
95 );
96 }
97 Ok(())
98}
99
100pub fn build_arrow_metadata_for_config(config: &StrategicConfig) -> HashMap<String, String> {
102 let mut m = HashMap::new();
103 m.insert(FORMAT_VERSION_KEY.into(), ZNIPPY_FORMAT_VERSION.to_string());
104 m.insert("max_core_in_flight".into(), config.max_core_in_flight.to_string());
105 m.insert("max_core_in_compress".into(), config.max_core_in_compress.to_string());
106 m.insert("max_mem_allowed".into(), config.max_mem_allowed.to_string());
107 m.insert("min_free_memory_ratio".into(), config.min_free_memory_ratio.to_string());
108 m.insert("file_split_block_size".into(), config.file_split_block_size.to_string());
109 m.insert("max_chunks".into(), config.max_chunks.to_string());
110 m.insert("compression_level".into(), config.compression_level.to_string());
111 m.insert("zstd_output_buffer_size".into(), config.zstd_output_buffer_size.to_string());
112 m
113}
114
115pub fn extract_config_from_arrow_metadata(
116 metadata: &HashMap<String, String>,
117) -> anyhow::Result<StrategicConfig> {
118 Ok(StrategicConfig {
119 max_core_allowed: 0,
120 max_core_in_flight: metadata
121 .get("max_core_in_flight")
122 .ok_or_else(|| anyhow::anyhow!("Missing 'max_core_in_flight'"))?
123 .parse()?,
124 max_core_in_compress: metadata
125 .get("max_core_in_compress")
126 .ok_or_else(|| anyhow::anyhow!("Missing 'max_core_in_compress'"))?
127 .parse()?,
128 max_mem_allowed: metadata
129 .get("max_mem_allowed")
130 .ok_or_else(|| anyhow::anyhow!("Missing 'max_mem_allowed'"))?
131 .parse()?,
132 min_free_memory_ratio: metadata
133 .get("min_free_memory_ratio")
134 .ok_or_else(|| anyhow::anyhow!("Missing 'min_free_memory_ratio'"))?
135 .parse()?,
136 file_split_block_size: metadata
137 .get("file_split_block_size")
138 .ok_or_else(|| anyhow::anyhow!("Missing 'file_split_block_size'"))?
139 .parse()?,
140 max_chunks: metadata
141 .get("max_chunks")
142 .ok_or_else(|| anyhow::anyhow!("Missing 'max_chunks'"))?
143 .parse()?,
144 compression_level: metadata
145 .get("compression_level")
146 .ok_or_else(|| anyhow::anyhow!("Missing 'compression_level'"))?
147 .parse()?,
148 zstd_output_buffer_size: metadata
149 .get("zstd_output_buffer_size")
150 .ok_or_else(|| anyhow::anyhow!("Missing 'zstd_output_buffer_size'"))?
151 .parse()?,
152 })
153}
154
155pub fn build_metadata_batch<F>(
160 blobs: &[BlobMeta],
161 path_resolver: F,
162 ext_meta: &[FileExtMeta],
163 ext_fields: &[Field],
164) -> arrow::error::Result<RecordBatch>
165where
166 F: Fn(u64) -> String,
167{
168 let len = blobs.len();
169
170 let mut path_builder = StringBuilder::with_capacity(len, len * 64);
171 let mut seq_builder = UInt32Builder::with_capacity(len);
172 let mut fdata_builder = UInt64Builder::with_capacity(len);
173 let mut compressed_builder = BooleanBuilder::with_capacity(len);
174 let mut size_builder = UInt64Builder::with_capacity(len);
175 let mut blob_offset_builder = UInt64Builder::with_capacity(len);
176 let mut blob_size_builder = UInt64Builder::with_capacity(len);
177 let mut checksum_builder = FixedSizeBinaryBuilder::with_capacity(len, 32);
178
179 for blob in blobs {
180 let m = &blob.chunk_meta;
181 path_builder.append_value(path_resolver(m.file_index));
182 seq_builder.append_value(m.chunk_seq);
183 fdata_builder.append_value(m.fdata_offset);
184 compressed_builder.append_value(m.compressed);
185 size_builder.append_value(m.uncompressed_size);
186 blob_offset_builder.append_value(blob.blob_offset);
187 blob_size_builder.append_value(blob.blob_size);
188 checksum_builder.append_value(m.checksum)?;
189 }
190
191 let mut columns: Vec<ArrayRef> = vec![
192 Arc::new(path_builder.finish()),
193 Arc::new(seq_builder.finish()),
194 Arc::new(fdata_builder.finish()),
195 Arc::new(compressed_builder.finish()),
196 Arc::new(size_builder.finish()),
197 Arc::new(blob_offset_builder.finish()),
198 Arc::new(blob_size_builder.finish()),
199 Arc::new(checksum_builder.finish()),
200 ];
201
202 if !ext_fields.is_empty() {
204 let mut pkg_type_builder = Int8Builder::with_capacity(len);
205 for blob in blobs {
206 match ext_meta.get(blob.chunk_meta.file_index as usize).and_then(|x| x.as_ref()) {
207 Some((type_id, _)) => pkg_type_builder.append_value(*type_id),
208 None => pkg_type_builder.append_null(),
209 }
210 }
211 columns.push(Arc::new(pkg_type_builder.finish()));
212
213 for field in ext_fields {
214 columns.push(build_ext_column(field, blobs, ext_meta));
215 }
216 }
217
218 RecordBatch::try_new(compose_index_schema(ext_fields), columns)
219}
220
221fn build_ext_column(field: &Field, blobs: &[BlobMeta], ext_meta: &[FileExtMeta]) -> ArrayRef {
224 use crate::plugin::ExtensionValue;
225 let len = blobs.len();
226 let value_for = |blob: &BlobMeta| -> Option<&ExtensionValue> {
227 ext_meta
228 .get(blob.chunk_meta.file_index as usize)
229 .and_then(|x| x.as_ref())
230 .and_then(|(_, row)| row.fields.get(field.name()))
231 };
232
233 match field.data_type() {
234 DataType::UInt32 => {
235 let mut b = UInt32Builder::with_capacity(len);
236 for blob in blobs {
237 match value_for(blob) {
238 Some(ExtensionValue::U32(n)) => b.append_value(*n),
239 _ => b.append_null(),
240 }
241 }
242 Arc::new(b.finish())
243 }
244 _ => {
246 let mut b = StringBuilder::with_capacity(len, len * 16);
247 for blob in blobs {
248 match value_for(blob) {
249 Some(ExtensionValue::Str(s)) => b.append_value(s),
250 Some(ExtensionValue::OptStr(Some(s))) => b.append_value(s),
251 _ => b.append_null(),
252 }
253 }
254 Arc::new(b.finish())
255 }
256 }
257}
258
259pub const MULTI_INDEX_MAGIC: [u8; 8] = *b"ZNPYMIDX";
276
277#[derive(Debug, Clone, PartialEq)]
279pub struct ManifestEntry {
280 pub pkg_type: i8,
281 pub repo: String,
282 pub module_name: String,
283 pub index_offset: u64,
284 pub index_len: u64,
285 pub row_count: u64,
286}
287
288pub const LOOKUP_MODULE: &str = "__znippy_lookup__";
294
295pub const TRIE_MODULE: &str = "__znippy_trie__";
299
300pub const SIGN_ARTIFACTS_MODULE: &str = "__znippy_sign_artifacts__";
306
307pub const SIGN_ARCHIVE_MODULE: &str = "__znippy_sign_archive__";
310
311pub const META_MODULE: &str = "__znippy_meta__";
323
324pub const GUNNAR_OID_MODULE: &str = "__gunnar_oid__";
329
330pub const GUNNAR_GRAPH_MODULE: &str = "__gunnar_graph__";
336
337pub const GUNNAR_REACH_MODULE: &str = "__gunnar_reach__";
341
342pub const GUNNAR_REFS_MODULE: &str = "__gunnar_refs__";
352
353pub const GUNNAR_SECRETS_MODULE: &str = "__gunnar_secrets__";
358
359pub const ZNIPPY_DELTA_MODULE: &str = "__znippy_delta__";
386
387pub fn delta_map_schema() -> Arc<Schema> {
389 Arc::new(Schema::new(vec![
390 Field::new("relative_path", DataType::Utf8, false),
391 Field::new("chunk_seq", DataType::UInt32, false),
392 Field::new("base_path", DataType::Utf8, false),
393 ]))
394}
395
396pub const RESERVED_PKG_TYPE: i8 = i8::MIN;
398
399pub const RESERVED_MODULES: &[&str] = &[
408 LOOKUP_MODULE,
409 TRIE_MODULE,
410 SIGN_ARTIFACTS_MODULE,
411 SIGN_ARCHIVE_MODULE,
412 META_MODULE,
413 GUNNAR_OID_MODULE,
414 GUNNAR_GRAPH_MODULE,
415 GUNNAR_REACH_MODULE,
416 GUNNAR_REFS_MODULE,
417 GUNNAR_SECRETS_MODULE,
418 ZNIPPY_DELTA_MODULE,
419];
420
421pub fn is_reserved_module(module_name: &str) -> bool {
427 RESERVED_MODULES.contains(&module_name)
428}
429
430pub const CARRIED_RESERVED_MODULES: &[&str] = &[GUNNAR_REFS_MODULE, GUNNAR_SECRETS_MODULE];
454
455pub fn is_carried_reserved_module(module_name: &str) -> bool {
458 CARRIED_RESERVED_MODULES.contains(&module_name)
459}
460
461pub fn read_reserved_section_bytes(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
466 read_reserved_section(path, module_name)
467}
468
469pub fn lookup_schema() -> Arc<Schema> {
478 Arc::new(Schema::new(base_index_fields()))
479}
480
481pub fn data_subindex_schema() -> Arc<Schema> {
493 Arc::new(Schema::new_with_metadata(
494 base_index_fields(),
495 build_arrow_metadata_for_config(&crate::common_config::CONFIG),
496 ))
497}
498
499#[derive(Debug, Clone, PartialEq, Eq)]
501pub struct ChunkLoc {
502 pub chunk_seq: u32,
503 pub fdata_offset: u64,
504 pub blob_offset: u64,
505 pub blob_size: u64,
506 pub uncompressed_size: u64,
507 pub compressed: bool,
508 pub checksum: [u8; 32],
509}
510
511#[derive(Debug, Clone, PartialEq)]
513pub enum IndexFooter {
514 Single { index_offset: u64 },
518 Multi { manifest_offset: u64 },
520}
521
522pub fn interpret_footer(tail: &[u8]) -> IndexFooter {
525 let n = tail.len();
526 let offset = u64::from_le_bytes(tail[n - 8..].try_into().unwrap());
527 if n >= 16 && tail[n - 16..n - 8] == MULTI_INDEX_MAGIC {
528 IndexFooter::Multi { manifest_offset: offset }
529 } else {
530 IndexFooter::Single { index_offset: offset }
531 }
532}
533
534fn manifest_schema() -> Arc<Schema> {
535 Arc::new(Schema::new(vec![
536 Field::new("pkg_type", DataType::Int8, false),
537 Field::new("repo", DataType::Utf8, false),
538 Field::new("module_name", DataType::Utf8, false),
539 Field::new("index_offset", DataType::UInt64, false),
540 Field::new("index_len", DataType::UInt64, false),
541 Field::new("row_count", DataType::UInt64, false),
542 ]))
543}
544
545pub fn write_manifest_bytes(entries: &[ManifestEntry]) -> Result<Vec<u8>> {
547 use arrow::ipc::writer::StreamWriter;
548
549 let len = entries.len();
550 let mut pkg_type = Int8Builder::with_capacity(len);
551 let mut repo = StringBuilder::with_capacity(len, len * 16);
552 let mut module_name = StringBuilder::with_capacity(len, len * 16);
553 let mut index_offset = UInt64Builder::with_capacity(len);
554 let mut index_len = UInt64Builder::with_capacity(len);
555 let mut row_count = UInt64Builder::with_capacity(len);
556 for e in entries {
557 pkg_type.append_value(e.pkg_type);
558 repo.append_value(&e.repo);
559 module_name.append_value(&e.module_name);
560 index_offset.append_value(e.index_offset);
561 index_len.append_value(e.index_len);
562 row_count.append_value(e.row_count);
563 }
564
565 let schema = manifest_schema();
566 let batch = RecordBatch::try_new(
567 schema.clone(),
568 vec![
569 Arc::new(pkg_type.finish()),
570 Arc::new(repo.finish()),
571 Arc::new(module_name.finish()),
572 Arc::new(index_offset.finish()),
573 Arc::new(index_len.finish()),
574 Arc::new(row_count.finish()),
575 ],
576 )?;
577
578 let mut buf = Vec::new();
579 {
580 let mut w = StreamWriter::try_new(&mut buf, &schema)?;
581 w.write(&batch)?;
582 w.finish()?;
583 }
584 Ok(buf)
585}
586
587pub fn read_manifest_bytes(bytes: &[u8]) -> Result<Vec<ManifestEntry>> {
589 use arrow::array::{Int8Array, StringArray, UInt64Array};
590 use arrow::ipc::reader::StreamReader;
591
592 let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
593 let mut out = Vec::new();
594 for batch in reader {
595 let batch = batch?;
596 let col = |name: &str| batch.column_by_name(name)
597 .ok_or_else(|| anyhow::anyhow!("manifest missing column {name}"));
598 let pkg_type = col("pkg_type")?.as_any().downcast_ref::<Int8Array>()
599 .ok_or_else(|| anyhow::anyhow!("pkg_type type"))?;
600 let repo = col("repo")?.as_any().downcast_ref::<StringArray>()
601 .ok_or_else(|| anyhow::anyhow!("repo type"))?;
602 let module_name = col("module_name")?.as_any().downcast_ref::<StringArray>()
603 .ok_or_else(|| anyhow::anyhow!("module_name type"))?;
604 let index_offset = col("index_offset")?.as_any().downcast_ref::<UInt64Array>()
605 .ok_or_else(|| anyhow::anyhow!("index_offset type"))?;
606 let index_len = col("index_len")?.as_any().downcast_ref::<UInt64Array>()
607 .ok_or_else(|| anyhow::anyhow!("index_len type"))?;
608 let row_count = col("row_count")?.as_any().downcast_ref::<UInt64Array>()
609 .ok_or_else(|| anyhow::anyhow!("row_count type"))?;
610 for i in 0..batch.num_rows() {
611 out.push(ManifestEntry {
612 pkg_type: pkg_type.value(i),
613 repo: repo.value(i).to_string(),
614 module_name: module_name.value(i).to_string(),
615 index_offset: index_offset.value(i),
616 index_len: index_len.value(i),
617 row_count: row_count.value(i),
618 });
619 }
620 }
621 Ok(out)
622}
623
624pub fn read_znippy_index(path: &Path) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
630 read_znippy_index_filtered(path, &IndexFilter::default())
631}
632
633#[derive(Debug, Clone, Default)]
639pub struct IndexFilter {
640 pub pkg_type: Option<i8>,
642 pub repo: Option<String>,
644}
645
646impl IndexFilter {
647 pub fn is_empty(&self) -> bool {
648 self.pkg_type.is_none() && self.repo.is_none()
649 }
650 fn matches(&self, e: &ManifestEntry) -> bool {
651 self.pkg_type.is_none_or(|t| e.pkg_type == t)
652 && self.repo.as_deref().is_none_or(|r| e.repo == r)
653 }
654}
655
656pub fn read_znippy_index_filtered(
658 path: &Path,
659 filter: &IndexFilter,
660) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
661 let mut file = File::open(path)?;
662 let file_len = file.metadata()?.len();
663 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 znippy archive");
664
665 file.seek(SeekFrom::End(-16))?;
666 let mut tail = [0u8; 16];
667 file.read_exact(&mut tail)?;
668
669 match interpret_footer(&tail) {
670 IndexFooter::Multi { manifest_offset } => {
671 read_multi_index(&mut file, file_len, manifest_offset, filter)
672 }
673 IndexFooter::Single { .. } => {
674 anyhow::bail!("v0.6 archives are not supported; re-compress with v0.7")
675 }
676 }
677}
678
679fn read_multi_index(
681 file: &mut File,
682 file_len: u64,
683 manifest_offset: u64,
684 filter: &IndexFilter,
685) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
686 use arrow::ipc::reader::StreamReader;
687
688 let manifest_end = file_len.checked_sub(16)
690 .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
691 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt v0.7 manifest_offset");
692 let manifest_len = (manifest_end - manifest_offset) as usize;
693
694 file.seek(SeekFrom::Start(manifest_offset))?;
695 let mut manifest_bytes = vec![0u8; manifest_len];
696 file.read_exact(&mut manifest_bytes)?;
697 let entries = read_manifest_bytes(&manifest_bytes)?;
698
699 let mut all_batches: Vec<RecordBatch> = Vec::new();
700 let mut schema: Option<Arc<Schema>> = None;
701
702 for entry in &entries {
703 if is_reserved_module(&entry.module_name) {
706 continue;
707 }
708 if !filter.matches(entry) {
710 continue;
711 }
712 anyhow::ensure!(
715 entry.index_offset.checked_add(entry.index_len)
716 .is_some_and(|end| end <= file_len),
717 "sub-index for module {} out of bounds (offset={}, len={}, file_len={})",
718 entry.module_name, entry.index_offset, entry.index_len, file_len
719 );
720 file.seek(SeekFrom::Start(entry.index_offset))?;
721 let mut sub_bytes = vec![0u8; entry.index_len as usize];
722 file.read_exact(&mut sub_bytes)?;
723 let cursor = std::io::Cursor::new(sub_bytes);
724 let reader = StreamReader::try_new(cursor, None)?;
725 if schema.is_none() {
726 let sub_schema = reader.schema();
727 check_format_version(sub_schema.metadata())?;
730 schema = Some(sub_schema);
731 }
732 for batch in reader {
733 all_batches.push(batch.map_err(|e| anyhow::anyhow!("sub-index read error: {}", e))?);
734 }
735 }
736
737 let schema = schema.unwrap_or_else(|| Arc::new(Schema::new(base_index_fields())));
738
739 let merged = if all_batches.len() <= 1 {
741 all_batches
742 } else {
743 let batch = arrow_select::concat::concat_batches(&schema, all_batches.iter())
744 .map_err(|e| anyhow::anyhow!("concat sub-indexes: {}", e))?;
745 vec![batch]
746 };
747
748 Ok((schema, merged))
749}
750
751pub fn read_znippy_manifest(path: &Path) -> Result<Vec<ManifestEntry>> {
754 let mut file = File::open(path)?;
755 let file_len = file.metadata()?.len();
756 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
757
758 file.seek(SeekFrom::End(-16))?;
759 let mut tail = [0u8; 16];
760 file.read_exact(&mut tail)?;
761
762 match interpret_footer(&tail) {
763 IndexFooter::Single { .. } => {
764 anyhow::bail!("not a v0.7 multi-index archive (no MULTI_INDEX_MAGIC)")
765 }
766 IndexFooter::Multi { manifest_offset } => {
767 let manifest_end = file_len - 16;
768 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
769 let manifest_len = (manifest_end - manifest_offset) as usize;
770 file.seek(SeekFrom::Start(manifest_offset))?;
771 let mut manifest_bytes = vec![0u8; manifest_len];
772 file.read_exact(&mut manifest_bytes)?;
773 let mut entries = read_manifest_bytes(&manifest_bytes)?;
774 entries.retain(|e| !is_reserved_module(&e.module_name));
776 Ok(entries)
777 }
778 }
779}
780
781pub fn read_znippy_full_manifest(path: &Path) -> Result<(Vec<ManifestEntry>, u64)> {
790 let mut file = File::open(path)?;
791 let file_len = file.metadata()?.len();
792 read_full_manifest(&mut file, file_len)
793}
794
795fn read_full_manifest(file: &mut File, file_len: u64) -> Result<(Vec<ManifestEntry>, u64)> {
797 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
798 file.seek(SeekFrom::End(-16))?;
799 let mut tail = [0u8; 16];
800 file.read_exact(&mut tail)?;
801 let manifest_offset = match interpret_footer(&tail) {
802 IndexFooter::Multi { manifest_offset } => manifest_offset,
803 IndexFooter::Single { .. } => anyhow::bail!("not a v0.7 multi-index archive"),
804 };
805 let manifest_end = file_len.checked_sub(16)
806 .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
807 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
808 let manifest_len = (manifest_end - manifest_offset) as usize;
809 file.seek(SeekFrom::Start(manifest_offset))?;
810 let mut manifest_bytes = vec![0u8; manifest_len];
811 file.read_exact(&mut manifest_bytes)?;
812 Ok((read_manifest_bytes(&manifest_bytes)?, manifest_offset))
813}
814
815fn read_reserved_section(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
817 let mut file = File::open(path)?;
818 let file_len = file.metadata()?.len();
819 let (entries, _) = read_full_manifest(&mut file, file_len)?;
820 let Some(entry) = entries.iter().find(|e| e.module_name == module_name) else {
821 return Ok(None);
822 };
823 anyhow::ensure!(
826 entry.index_offset.checked_add(entry.index_len)
827 .is_some_and(|end| end <= file_len),
828 "reserved section {} out of bounds (offset={}, len={}, file_len={})",
829 entry.module_name, entry.index_offset, entry.index_len, file_len
830 );
831 file.seek(SeekFrom::Start(entry.index_offset))?;
832 let mut bytes = vec![0u8; entry.index_len as usize];
833 file.read_exact(&mut bytes)?;
834 Ok(Some(bytes))
835}
836
837fn checksum32(col: &arrow::array::FixedSizeBinaryArray, i: usize) -> Result<[u8; 32]> {
850 if col.value_length() != 32 {
851 return Err(anyhow::anyhow!(
852 "checksum column has width {}, expected 32",
853 col.value_length()
854 ));
855 }
856 let mut ck = [0u8; 32];
857 ck.copy_from_slice(col.value(i));
858 Ok(ck)
859}
860
861fn decode_lookup(bytes: &[u8]) -> Result<LookupColumns> {
862 use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
863 use arrow::ipc::reader::StreamReader;
864
865 let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
866 let mut cols = LookupColumns::default();
867 for batch in reader {
868 let batch = batch?;
869 let get = |n: &str| batch.column_by_name(n)
870 .ok_or_else(|| anyhow::anyhow!("lookup missing column {n}"));
871 let paths = get("relative_path")?.as_any().downcast_ref::<StringArray>()
872 .ok_or_else(|| anyhow::anyhow!("relative_path type"))?;
873 let chunk_seq = get("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
874 .ok_or_else(|| anyhow::anyhow!("chunk_seq type"))?;
875 let fdata = get("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
876 .ok_or_else(|| anyhow::anyhow!("fdata_offset type"))?;
877 let compressed = get("compressed")?.as_any().downcast_ref::<BooleanArray>()
878 .ok_or_else(|| anyhow::anyhow!("compressed type"))?;
879 let usize_col = get("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
880 .ok_or_else(|| anyhow::anyhow!("uncompressed_size type"))?;
881 let blob_offset = get("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
882 .ok_or_else(|| anyhow::anyhow!("blob_offset type"))?;
883 let blob_size = get("blob_size")?.as_any().downcast_ref::<UInt64Array>()
884 .ok_or_else(|| anyhow::anyhow!("blob_size type"))?;
885 let checksum = get("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
886 .ok_or_else(|| anyhow::anyhow!("checksum type"))?;
887 for i in 0..batch.num_rows() {
888 cols.paths.push(paths.value(i).to_string());
889 let ck = checksum32(checksum, i)?;
890 cols.locs.push(ChunkLoc {
891 chunk_seq: chunk_seq.value(i),
892 fdata_offset: fdata.value(i),
893 blob_offset: blob_offset.value(i),
894 blob_size: blob_size.value(i),
895 uncompressed_size: usize_col.value(i),
896 compressed: compressed.value(i),
897 checksum: ck,
898 });
899 }
900 }
901 Ok(cols)
902}
903
904#[derive(Default)]
905struct LookupColumns {
906 paths: Vec<String>,
907 locs: Vec<ChunkLoc>,
908}
909
910pub fn locate_file(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
917 if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
918 let cols = decode_lookup(&lookup_bytes)?;
919 let n = cols.paths.len();
920
921 let hit = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
923 let map = fst::Map::new(trie_bytes)
924 .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
925 map.get(target.as_bytes()).map(|v| v as usize)
926 } else {
927 match cols.paths.binary_search_by(|p| p.as_str().cmp(target)) {
929 Ok(i) => Some(i),
930 Err(_) => None,
931 }
932 };
933
934 let Some(hit) = hit else { return Ok(Vec::new()); };
935
936 if hit >= n { return Ok(Vec::new()); }
941
942 let mut start = hit;
944 while start > 0 && cols.paths[start - 1] == target { start -= 1; }
945 let mut end = hit + 1;
946 while end < n && cols.paths[end] == target { end += 1; }
947
948 let mut out: Vec<ChunkLoc> = cols.locs[start..end].to_vec();
949 out.sort_by_key(|c| c.chunk_seq);
950 return Ok(out);
951 }
952
953 locate_file_via_index(path, target)
955}
956
957#[derive(Debug, Clone, PartialEq)]
960pub struct ArtifactMeta {
961 pub relative_path: String,
962 pub uncompressed_size: u64,
964 pub chunk_count: u32,
965 pub compressed: bool,
967}
968
969pub fn get_all_files_meta(path: &Path) -> Result<Vec<ArtifactMeta>> {
974 files_meta_impl(path, None)
975}
976
977pub fn get_files_meta_with_prefix(path: &Path, prefix: &str) -> Result<Vec<ArtifactMeta>> {
984 files_meta_impl(path, Some(prefix))
985}
986
987fn files_meta_impl(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
988 use fst::{IntoStreamer, Streamer};
989
990 if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
991 let cols = decode_lookup(&lookup_bytes)?; let n = cols.paths.len();
993
994 let (lo, hi) = match prefix {
996 None | Some("") => (0, n),
997 Some(pre) => {
998 let lo = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
1001 let map = fst::Map::new(trie_bytes)
1002 .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
1003 let mut stream = map.range().ge(pre.as_bytes()).into_stream();
1004 match stream.next() {
1005 Some((k, v)) if k.starts_with(pre.as_bytes()) => v as usize,
1006 _ => return Ok(Vec::new()),
1007 }
1008 } else {
1009 cols.paths.partition_point(|p| p.as_str() < pre)
1010 };
1011 if lo >= n || !cols.paths[lo].starts_with(pre) {
1012 return Ok(Vec::new());
1013 }
1014 let mut hi = lo;
1015 while hi < n && cols.paths[hi].starts_with(pre) {
1016 hi += 1;
1017 }
1018 (lo, hi)
1019 }
1020 };
1021
1022 let mut out = Vec::new();
1024 let mut i = lo;
1025 while i < hi {
1026 let p = &cols.paths[i];
1027 let mut total = 0u64;
1028 let mut count = 0u32;
1029 let mut compressed = false;
1030 while i < hi && &cols.paths[i] == p {
1031 total += cols.locs[i].uncompressed_size;
1032 count += 1;
1033 compressed |= cols.locs[i].compressed;
1034 i += 1;
1035 }
1036 out.push(ArtifactMeta {
1037 relative_path: p.clone(),
1038 uncompressed_size: total,
1039 chunk_count: count,
1040 compressed,
1041 });
1042 }
1043 return Ok(out);
1044 }
1045
1046 files_meta_via_index(path, prefix)
1047}
1048
1049pub struct ArchiveReader {
1068 paths: Vec<String>,
1070 locs: Vec<ChunkLoc>,
1072 trie: Option<fst::Map<Vec<u8>>>,
1076 file: File,
1080 file_len: u64,
1083}
1084
1085impl ArchiveReader {
1086 pub fn open(path: &Path) -> Result<Self> {
1089 let mut file = File::open(path)?;
1090 let file_len = file.metadata()?.len();
1091 let (entries, _) = read_full_manifest(&mut file, file_len)?;
1092
1093 let mut read_section = |module: &str| -> Result<Option<Vec<u8>>> {
1097 let Some(entry) = entries.iter().find(|e| e.module_name == module) else {
1098 return Ok(None);
1099 };
1100 anyhow::ensure!(
1101 entry.index_offset.checked_add(entry.index_len)
1102 .is_some_and(|end| end <= file_len),
1103 "reserved section {} out of bounds (offset={}, len={}, file_len={})",
1104 entry.module_name, entry.index_offset, entry.index_len, file_len
1105 );
1106 file.seek(SeekFrom::Start(entry.index_offset))?;
1107 let mut bytes = vec![0u8; entry.index_len as usize];
1108 file.read_exact(&mut bytes)?;
1109 Ok(Some(bytes))
1110 };
1111
1112 let lookup_bytes = read_section(LOOKUP_MODULE)?.ok_or_else(|| {
1113 anyhow::anyhow!("archive has no lookup sub-index (not a v0.7 sealed archive)")
1114 })?;
1115 let cols = decode_lookup(&lookup_bytes)?;
1116 let trie = match read_section(TRIE_MODULE)? {
1117 Some(tb) => Some(fst::Map::new(tb).map_err(|e| anyhow::anyhow!("trie open: {e}"))?),
1118 None => None,
1119 };
1120
1121 Ok(Self { paths: cols.paths, locs: cols.locs, trie, file, file_len })
1122 }
1123
1124 pub fn row_count(&self) -> usize {
1126 self.paths.len()
1127 }
1128
1129 pub fn read_file(&self, target: &str) -> Result<Vec<u8>> {
1139 let chunks = self.locate(target);
1140 anyhow::ensure!(!chunks.is_empty(), "file not found in archive: {target}");
1141 crate::decompress::reassemble_file(&self.file, self.file_len, target, &chunks)
1142 }
1143
1144 pub fn locate(&self, target: &str) -> Vec<ChunkLoc> {
1147 let n = self.paths.len();
1148 let hit = match &self.trie {
1149 Some(map) => map.get(target.as_bytes()).map(|v| v as usize),
1150 None => self.paths.binary_search_by(|p| p.as_str().cmp(target)).ok(),
1151 };
1152 let Some(hit) = hit else { return Vec::new(); };
1153
1154 if hit >= n { return Vec::new(); }
1158
1159 let mut start = hit;
1161 while start > 0 && self.paths[start - 1] == target { start -= 1; }
1162 let mut end = hit + 1;
1163 while end < n && self.paths[end] == target { end += 1; }
1164
1165 let mut out: Vec<ChunkLoc> = self.locs[start..end].to_vec();
1166 out.sort_by_key(|c| c.chunk_seq);
1167 out
1168 }
1169
1170 pub fn files_meta(&self) -> Vec<ArtifactMeta> {
1173 self.aggregate(0, self.paths.len())
1174 }
1175
1176 pub fn files_meta_with_prefix(&self, prefix: &str) -> Vec<ArtifactMeta> {
1179 let (lo, hi) = self.window(prefix);
1180 self.aggregate(lo, hi)
1181 }
1182
1183 fn window(&self, prefix: &str) -> (usize, usize) {
1187 use fst::{IntoStreamer, Streamer};
1188 let n = self.paths.len();
1189 if prefix.is_empty() {
1190 return (0, n);
1191 }
1192 let lo = match &self.trie {
1193 Some(map) => {
1194 let mut stream = map.range().ge(prefix.as_bytes()).into_stream();
1195 match stream.next() {
1196 Some((k, v)) if k.starts_with(prefix.as_bytes()) => v as usize,
1197 _ => return (0, 0),
1198 }
1199 }
1200 None => self.paths.partition_point(|p| p.as_str() < prefix),
1201 };
1202 if lo >= n || !self.paths[lo].starts_with(prefix) {
1203 return (0, 0);
1204 }
1205 let mut hi = lo;
1206 while hi < n && self.paths[hi].starts_with(prefix) {
1207 hi += 1;
1208 }
1209 (lo, hi)
1210 }
1211
1212 fn aggregate(&self, lo: usize, hi: usize) -> Vec<ArtifactMeta> {
1215 let mut out = Vec::new();
1216 let mut i = lo;
1217 while i < hi {
1218 let p = &self.paths[i];
1219 let mut total = 0u64;
1220 let mut count = 0u32;
1221 let mut compressed = false;
1222 while i < hi && &self.paths[i] == p {
1223 total += self.locs[i].uncompressed_size;
1224 count += 1;
1225 compressed |= self.locs[i].compressed;
1226 i += 1;
1227 }
1228 out.push(ArtifactMeta {
1229 relative_path: p.clone(),
1230 uncompressed_size: total,
1231 chunk_count: count,
1232 compressed,
1233 });
1234 }
1235 out
1236 }
1237}
1238
1239fn files_meta_via_index(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
1241 use arrow::array::{BooleanArray, StringArray, UInt64Array};
1242
1243 let (schema, batches) = read_znippy_index(path)?;
1244 let batch = match batches.len() {
1245 0 => return Ok(Vec::new()),
1246 1 => batches.into_iter().next().unwrap(),
1247 _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1248 };
1249 let col = |n: &str| batch.column_by_name(n)
1254 .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1255 let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1256 .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1257 let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1258 .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1259 let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1260 .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1261
1262 let mut agg: HashMap<&str, (u64, u32, bool)> = HashMap::new();
1264 for i in 0..batch.num_rows() {
1265 let p = paths.value(i);
1266 if let Some(pre) = prefix {
1267 if !p.starts_with(pre) { continue; }
1268 }
1269 let e = agg.entry(p).or_insert((0, 0, false));
1270 e.0 += usize_col.value(i);
1271 e.1 += 1;
1272 e.2 |= compressed.value(i);
1273 }
1274 let mut out: Vec<ArtifactMeta> = agg.into_iter().map(|(p, (sz, c, comp))| ArtifactMeta {
1275 relative_path: p.to_string(),
1276 uncompressed_size: sz,
1277 chunk_count: c,
1278 compressed: comp,
1279 }).collect();
1280 out.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
1281 Ok(out)
1282}
1283
1284fn locate_file_via_index(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
1286 use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
1287
1288 let (schema, batches) = read_znippy_index(path)?;
1289 let batch = match batches.len() {
1290 0 => return Ok(Vec::new()),
1291 1 => batches.into_iter().next().unwrap(),
1292 _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1293 };
1294 let col = |n: &str| batch.column_by_name(n)
1297 .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1298 let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1299 .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1300 let chunk_seq = col("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
1301 .ok_or_else(|| anyhow::anyhow!("index column chunk_seq has unexpected type"))?;
1302 let fdata = col("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
1303 .ok_or_else(|| anyhow::anyhow!("index column fdata_offset has unexpected type"))?;
1304 let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1305 .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1306 let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1307 .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1308 let blob_offset = col("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
1309 .ok_or_else(|| anyhow::anyhow!("index column blob_offset has unexpected type"))?;
1310 let blob_size = col("blob_size")?.as_any().downcast_ref::<UInt64Array>()
1311 .ok_or_else(|| anyhow::anyhow!("index column blob_size has unexpected type"))?;
1312 let checksum = col("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
1313 .ok_or_else(|| anyhow::anyhow!("index column checksum has unexpected type"))?;
1314
1315 let mut out = Vec::new();
1316 for i in 0..batch.num_rows() {
1317 if paths.value(i) == target {
1318 let ck = checksum32(checksum, i)?;
1319 out.push(ChunkLoc {
1320 chunk_seq: chunk_seq.value(i),
1321 fdata_offset: fdata.value(i),
1322 blob_offset: blob_offset.value(i),
1323 blob_size: blob_size.value(i),
1324 uncompressed_size: usize_col.value(i),
1325 compressed: compressed.value(i),
1326 checksum: ck,
1327 });
1328 }
1329 }
1330 out.sort_by_key(|c| c.chunk_seq);
1331 Ok(out)
1332}
1333
1334pub fn is_probably_compressed(path: &Path) -> bool {
1335 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1336 let ext = ext.to_ascii_lowercase();
1337 matches!(
1338 ext.as_str(),
1339 "zip" | "gz" | "bz2" | "xz" | "lz" | "lzma" | "7z" | "rar" | "cab"
1340 | "jar" | "war" | "ear" | "zst" | "sz" | "lz4" | "tgz" | "txz"
1341 | "tbz" | "apk" | "dmg" | "deb" | "rpm" | "arrow" | "mpeg" | "mpg"
1342 | "jpeg" | "jpg" | "gif" | "bmp" | "png" | "crate" | "znippy"
1343 | "zdata" | "parquet" | "webp" | "webm"
1344 | "age" | "iso" | "pdf"
1349 | "pack" | "idx" | "midx" | "bitmap"
1356 )
1357 } else {
1358 false
1359 }
1360}
1361
1362pub fn should_skip_compression(path: &Path) -> bool {
1371 is_probably_compressed(path)
1372}
1373
1374#[cfg(test)]
1375mod skip_compression_tests {
1376 use super::*;
1377
1378 #[test]
1379 fn skips_already_compressed_and_encrypted() {
1380 for p in ["secrets/secrets.age", "infra/talos/talos-1.13.iso", "s3/doc.pdf", "x.PDF"] {
1381 assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1382 }
1383 }
1384
1385 #[test]
1386 fn compresses_plain_dump_and_config() {
1387 for p in ["dbdump/njord.dump", "njord.sql", "lakespec.json", "njordconf/serverspec.json"] {
1389 assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1390 }
1391 }
1392
1393 #[test]
1396 fn skips_git_pack_directory_artefacts() {
1397 for p in [
1398 ".git/objects/pack/pack-9f2c.pack",
1399 ".git/objects/pack/pack-9f2c.idx",
1400 ".git/objects/pack/multi-pack-index.midx",
1401 ".git/objects/pack/pack-9f2c.bitmap",
1402 ] {
1403 assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1404 }
1405 }
1406
1407 #[test]
1411 fn still_compresses_the_compressible_git_artefacts() {
1412 for p in [
1413 ".git/objects/pack/pack-9f2c.rev",
1414 ".git/objects/pack/pack-9f2c.promisor",
1415 ".git/COMMIT_EDITMSG",
1416 ".git/config",
1417 ] {
1418 assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1419 }
1420 }
1421}
1422
1423#[derive(Debug, Default)]
1424pub struct VerifyReport {
1425 pub total_files: usize,
1426 pub verified_files: usize,
1427 pub corrupt_files: usize,
1428 pub total_bytes: u64,
1429 pub verified_bytes: u64,
1430 pub corrupt_bytes: u64,
1431 pub chunks: u64,
1432}
1433
1434pub fn list_archive_contents(path: &Path) -> Result<()> {
1435 let (_schema, batches) = read_znippy_index(path)?;
1436 for batch in &batches {
1437 let paths = batch
1438 .column_by_name("relative_path")
1439 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>())
1440 .ok_or_else(|| anyhow::anyhow!("missing relative_path column"))?;
1441 let sizes = batch
1442 .column_by_name("uncompressed_size")
1443 .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt64Array>())
1444 .ok_or_else(|| anyhow::anyhow!("missing uncompressed_size column"))?;
1445 let chunk_seqs = batch
1446 .column_by_name("chunk_seq")
1447 .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt32Array>());
1448 let group_ids = batch
1449 .column_by_name("group_id")
1450 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1451 let artifact_ids = batch
1452 .column_by_name("artifact_id")
1453 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1454 let versions = batch
1455 .column_by_name("version")
1456 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1457 for i in 0..batch.num_rows() {
1458 if let Some(seqs) = chunk_seqs {
1460 if seqs.value(i) != 0 {
1461 continue;
1462 }
1463 }
1464 if let (Some(g), Some(a), Some(v)) = (group_ids, artifact_ids, versions) {
1465 if !g.is_null(i) {
1466 println!(
1467 "{}\t{}\t{}:{}:{}",
1468 paths.value(i),
1469 sizes.value(i),
1470 g.value(i),
1471 a.value(i),
1472 v.value(i)
1473 );
1474 continue;
1475 }
1476 }
1477 println!("{}\t{}", paths.value(i), sizes.value(i));
1478 }
1479 }
1480 Ok(())
1481}
1482
1483pub fn verify_archive_integrity(path: &Path) -> Result<VerifyReport> {
1484 let out_dir = PathBuf::from("/dev/null");
1485 decompress_archive(path, false, &out_dir)
1486}
1487
1488#[cfg(test)]
1489mod version_tests {
1490 use super::*;
1491
1492 #[test]
1493 fn current_and_older_versions_are_accepted() {
1494 let mut m = HashMap::new();
1495 check_format_version(&m).unwrap();
1497 m.insert(FORMAT_VERSION_KEY.into(), ZNIPPY_FORMAT_VERSION.to_string());
1499 check_format_version(&m).unwrap();
1500 m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION - 1).to_string());
1502 check_format_version(&m).unwrap();
1503 }
1504
1505 #[test]
1506 fn newer_version_is_rejected_clearly() {
1507 let mut m = HashMap::new();
1508 m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION + 1).to_string());
1509 let err = check_format_version(&m).unwrap_err().to_string();
1510 assert!(err.contains("newer than this reader supports"), "got: {err}");
1511 assert!(err.contains("upgrade znippy"), "got: {err}");
1512 }
1513
1514 #[test]
1515 fn writer_records_the_current_version() {
1516 let meta = build_arrow_metadata_for_config(&crate::common_config::CONFIG);
1517 assert_eq!(
1518 meta.get(FORMAT_VERSION_KEY).map(String::as_str),
1519 Some(ZNIPPY_FORMAT_VERSION.to_string().as_str())
1520 );
1521 }
1522}
1523
1524#[cfg(test)]
1525mod checksum_width_tests {
1526 use super::*;
1527 use arrow::array::FixedSizeBinaryArray;
1528
1529 #[test]
1536 fn narrow_checksum_column_errors_instead_of_panicking() {
1537 let narrow = FixedSizeBinaryArray::try_from_iter([[0u8; 16]].into_iter()).unwrap();
1538 assert_eq!(narrow.value_length(), 16);
1539 let err = checksum32(&narrow, 0).expect_err("a 16-byte checksum column must be an Err");
1540 assert!(
1541 err.to_string().contains("width 16"),
1542 "error must name the bad width, got: {err}"
1543 );
1544 }
1545
1546 #[test]
1547 fn wide_checksum_column_errors_instead_of_truncating() {
1548 let wide = FixedSizeBinaryArray::try_from_iter([[7u8; 64]].into_iter()).unwrap();
1549 assert!(checksum32(&wide, 0).is_err(), "a 64-byte checksum column must be an Err");
1550 }
1551
1552 #[test]
1553 fn correct_width_checksum_is_read_verbatim() {
1554 let mut digest = [0u8; 32];
1555 for (i, b) in digest.iter_mut().enumerate() {
1556 *b = i as u8;
1557 }
1558 let col = FixedSizeBinaryArray::try_from_iter([digest].into_iter()).unwrap();
1559 assert_eq!(checksum32(&col, 0).unwrap(), digest);
1560 }
1561}
1562
1563#[cfg(test)]
1564mod reserved_module_tests {
1565 use super::*;
1566
1567 #[test]
1577 fn every_reserved_module_is_classified_reserved() {
1578 for m in RESERVED_MODULES {
1579 assert!(
1580 is_reserved_module(m),
1581 "'{m}' is in RESERVED_MODULES but is_reserved_module says it is DATA — \
1582 its rows would be merged into the file index"
1583 );
1584 }
1585 }
1586
1587 #[test]
1591 fn the_git_format_modules_are_reserved() {
1592 for m in [
1593 GUNNAR_OID_MODULE,
1594 GUNNAR_GRAPH_MODULE,
1595 GUNNAR_REACH_MODULE,
1596 GUNNAR_REFS_MODULE,
1597 GUNNAR_SECRETS_MODULE,
1598 ] {
1599 assert!(is_reserved_module(m), "git package-format module '{m}' must be reserved");
1600 assert!(
1601 RESERVED_MODULES.contains(&m),
1602 "git package-format module '{m}' must be in the catalog"
1603 );
1604 }
1605 assert_eq!(GUNNAR_OID_MODULE, "__gunnar_oid__");
1606 assert_eq!(GUNNAR_GRAPH_MODULE, "__gunnar_graph__");
1607 assert_eq!(GUNNAR_REACH_MODULE, "__gunnar_reach__");
1608 assert_eq!(GUNNAR_REFS_MODULE, "__gunnar_refs__");
1609 assert_eq!(GUNNAR_SECRETS_MODULE, "__gunnar_secrets__");
1610 }
1611
1612 #[test]
1615 fn ordinary_module_names_stay_data() {
1616 for m in ["maven", "git", "rust", "", "__gunnar__", "gunnar_oid", "__gunnar_oid", "objects"] {
1617 assert!(!is_reserved_module(m), "'{m}' must be treated as a DATA sub-index");
1618 }
1619 }
1620
1621 #[test]
1623 fn the_catalog_is_well_formed() {
1624 let mut seen = std::collections::HashSet::new();
1625 for m in RESERVED_MODULES {
1626 assert!(!m.is_empty(), "empty reserved module name");
1627 assert!(seen.insert(*m), "duplicate reserved module name '{m}'");
1628 }
1629 assert_eq!(seen.len(), RESERVED_MODULES.len());
1630 }
1631}