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 RESERVED_PKG_TYPE: i8 = i8::MIN;
361
362pub const RESERVED_MODULES: &[&str] = &[
371 LOOKUP_MODULE,
372 TRIE_MODULE,
373 SIGN_ARTIFACTS_MODULE,
374 SIGN_ARCHIVE_MODULE,
375 META_MODULE,
376 GUNNAR_OID_MODULE,
377 GUNNAR_GRAPH_MODULE,
378 GUNNAR_REACH_MODULE,
379 GUNNAR_REFS_MODULE,
380 GUNNAR_SECRETS_MODULE,
381];
382
383pub fn is_reserved_module(module_name: &str) -> bool {
389 RESERVED_MODULES.contains(&module_name)
390}
391
392pub fn read_reserved_section_bytes(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
397 read_reserved_section(path, module_name)
398}
399
400pub fn lookup_schema() -> Arc<Schema> {
409 Arc::new(Schema::new(base_index_fields()))
410}
411
412pub fn data_subindex_schema() -> Arc<Schema> {
424 Arc::new(Schema::new_with_metadata(
425 base_index_fields(),
426 build_arrow_metadata_for_config(&crate::common_config::CONFIG),
427 ))
428}
429
430#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct ChunkLoc {
433 pub chunk_seq: u32,
434 pub fdata_offset: u64,
435 pub blob_offset: u64,
436 pub blob_size: u64,
437 pub uncompressed_size: u64,
438 pub compressed: bool,
439 pub checksum: [u8; 32],
440}
441
442#[derive(Debug, Clone, PartialEq)]
444pub enum IndexFooter {
445 Single { index_offset: u64 },
449 Multi { manifest_offset: u64 },
451}
452
453pub fn interpret_footer(tail: &[u8]) -> IndexFooter {
456 let n = tail.len();
457 let offset = u64::from_le_bytes(tail[n - 8..].try_into().unwrap());
458 if n >= 16 && tail[n - 16..n - 8] == MULTI_INDEX_MAGIC {
459 IndexFooter::Multi { manifest_offset: offset }
460 } else {
461 IndexFooter::Single { index_offset: offset }
462 }
463}
464
465fn manifest_schema() -> Arc<Schema> {
466 Arc::new(Schema::new(vec![
467 Field::new("pkg_type", DataType::Int8, false),
468 Field::new("repo", DataType::Utf8, false),
469 Field::new("module_name", DataType::Utf8, false),
470 Field::new("index_offset", DataType::UInt64, false),
471 Field::new("index_len", DataType::UInt64, false),
472 Field::new("row_count", DataType::UInt64, false),
473 ]))
474}
475
476pub fn write_manifest_bytes(entries: &[ManifestEntry]) -> Result<Vec<u8>> {
478 use arrow::ipc::writer::StreamWriter;
479
480 let len = entries.len();
481 let mut pkg_type = Int8Builder::with_capacity(len);
482 let mut repo = StringBuilder::with_capacity(len, len * 16);
483 let mut module_name = StringBuilder::with_capacity(len, len * 16);
484 let mut index_offset = UInt64Builder::with_capacity(len);
485 let mut index_len = UInt64Builder::with_capacity(len);
486 let mut row_count = UInt64Builder::with_capacity(len);
487 for e in entries {
488 pkg_type.append_value(e.pkg_type);
489 repo.append_value(&e.repo);
490 module_name.append_value(&e.module_name);
491 index_offset.append_value(e.index_offset);
492 index_len.append_value(e.index_len);
493 row_count.append_value(e.row_count);
494 }
495
496 let schema = manifest_schema();
497 let batch = RecordBatch::try_new(
498 schema.clone(),
499 vec![
500 Arc::new(pkg_type.finish()),
501 Arc::new(repo.finish()),
502 Arc::new(module_name.finish()),
503 Arc::new(index_offset.finish()),
504 Arc::new(index_len.finish()),
505 Arc::new(row_count.finish()),
506 ],
507 )?;
508
509 let mut buf = Vec::new();
510 {
511 let mut w = StreamWriter::try_new(&mut buf, &schema)?;
512 w.write(&batch)?;
513 w.finish()?;
514 }
515 Ok(buf)
516}
517
518pub fn read_manifest_bytes(bytes: &[u8]) -> Result<Vec<ManifestEntry>> {
520 use arrow::array::{Int8Array, StringArray, UInt64Array};
521 use arrow::ipc::reader::StreamReader;
522
523 let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
524 let mut out = Vec::new();
525 for batch in reader {
526 let batch = batch?;
527 let col = |name: &str| batch.column_by_name(name)
528 .ok_or_else(|| anyhow::anyhow!("manifest missing column {name}"));
529 let pkg_type = col("pkg_type")?.as_any().downcast_ref::<Int8Array>()
530 .ok_or_else(|| anyhow::anyhow!("pkg_type type"))?;
531 let repo = col("repo")?.as_any().downcast_ref::<StringArray>()
532 .ok_or_else(|| anyhow::anyhow!("repo type"))?;
533 let module_name = col("module_name")?.as_any().downcast_ref::<StringArray>()
534 .ok_or_else(|| anyhow::anyhow!("module_name type"))?;
535 let index_offset = col("index_offset")?.as_any().downcast_ref::<UInt64Array>()
536 .ok_or_else(|| anyhow::anyhow!("index_offset type"))?;
537 let index_len = col("index_len")?.as_any().downcast_ref::<UInt64Array>()
538 .ok_or_else(|| anyhow::anyhow!("index_len type"))?;
539 let row_count = col("row_count")?.as_any().downcast_ref::<UInt64Array>()
540 .ok_or_else(|| anyhow::anyhow!("row_count type"))?;
541 for i in 0..batch.num_rows() {
542 out.push(ManifestEntry {
543 pkg_type: pkg_type.value(i),
544 repo: repo.value(i).to_string(),
545 module_name: module_name.value(i).to_string(),
546 index_offset: index_offset.value(i),
547 index_len: index_len.value(i),
548 row_count: row_count.value(i),
549 });
550 }
551 }
552 Ok(out)
553}
554
555pub fn read_znippy_index(path: &Path) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
561 read_znippy_index_filtered(path, &IndexFilter::default())
562}
563
564#[derive(Debug, Clone, Default)]
570pub struct IndexFilter {
571 pub pkg_type: Option<i8>,
573 pub repo: Option<String>,
575}
576
577impl IndexFilter {
578 pub fn is_empty(&self) -> bool {
579 self.pkg_type.is_none() && self.repo.is_none()
580 }
581 fn matches(&self, e: &ManifestEntry) -> bool {
582 self.pkg_type.is_none_or(|t| e.pkg_type == t)
583 && self.repo.as_deref().is_none_or(|r| e.repo == r)
584 }
585}
586
587pub fn read_znippy_index_filtered(
589 path: &Path,
590 filter: &IndexFilter,
591) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
592 let mut file = File::open(path)?;
593 let file_len = file.metadata()?.len();
594 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 znippy archive");
595
596 file.seek(SeekFrom::End(-16))?;
597 let mut tail = [0u8; 16];
598 file.read_exact(&mut tail)?;
599
600 match interpret_footer(&tail) {
601 IndexFooter::Multi { manifest_offset } => {
602 read_multi_index(&mut file, file_len, manifest_offset, filter)
603 }
604 IndexFooter::Single { .. } => {
605 anyhow::bail!("v0.6 archives are not supported; re-compress with v0.7")
606 }
607 }
608}
609
610fn read_multi_index(
612 file: &mut File,
613 file_len: u64,
614 manifest_offset: u64,
615 filter: &IndexFilter,
616) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
617 use arrow::ipc::reader::StreamReader;
618
619 let manifest_end = file_len.checked_sub(16)
621 .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
622 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt v0.7 manifest_offset");
623 let manifest_len = (manifest_end - manifest_offset) as usize;
624
625 file.seek(SeekFrom::Start(manifest_offset))?;
626 let mut manifest_bytes = vec![0u8; manifest_len];
627 file.read_exact(&mut manifest_bytes)?;
628 let entries = read_manifest_bytes(&manifest_bytes)?;
629
630 let mut all_batches: Vec<RecordBatch> = Vec::new();
631 let mut schema: Option<Arc<Schema>> = None;
632
633 for entry in &entries {
634 if is_reserved_module(&entry.module_name) {
637 continue;
638 }
639 if !filter.matches(entry) {
641 continue;
642 }
643 anyhow::ensure!(
646 entry.index_offset.checked_add(entry.index_len)
647 .is_some_and(|end| end <= file_len),
648 "sub-index for module {} out of bounds (offset={}, len={}, file_len={})",
649 entry.module_name, entry.index_offset, entry.index_len, file_len
650 );
651 file.seek(SeekFrom::Start(entry.index_offset))?;
652 let mut sub_bytes = vec![0u8; entry.index_len as usize];
653 file.read_exact(&mut sub_bytes)?;
654 let cursor = std::io::Cursor::new(sub_bytes);
655 let reader = StreamReader::try_new(cursor, None)?;
656 if schema.is_none() {
657 let sub_schema = reader.schema();
658 check_format_version(sub_schema.metadata())?;
661 schema = Some(sub_schema);
662 }
663 for batch in reader {
664 all_batches.push(batch.map_err(|e| anyhow::anyhow!("sub-index read error: {}", e))?);
665 }
666 }
667
668 let schema = schema.unwrap_or_else(|| Arc::new(Schema::new(base_index_fields())));
669
670 let merged = if all_batches.len() <= 1 {
672 all_batches
673 } else {
674 let batch = arrow_select::concat::concat_batches(&schema, all_batches.iter())
675 .map_err(|e| anyhow::anyhow!("concat sub-indexes: {}", e))?;
676 vec![batch]
677 };
678
679 Ok((schema, merged))
680}
681
682pub fn read_znippy_manifest(path: &Path) -> Result<Vec<ManifestEntry>> {
685 let mut file = File::open(path)?;
686 let file_len = file.metadata()?.len();
687 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
688
689 file.seek(SeekFrom::End(-16))?;
690 let mut tail = [0u8; 16];
691 file.read_exact(&mut tail)?;
692
693 match interpret_footer(&tail) {
694 IndexFooter::Single { .. } => {
695 anyhow::bail!("not a v0.7 multi-index archive (no MULTI_INDEX_MAGIC)")
696 }
697 IndexFooter::Multi { manifest_offset } => {
698 let manifest_end = file_len - 16;
699 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
700 let manifest_len = (manifest_end - manifest_offset) as usize;
701 file.seek(SeekFrom::Start(manifest_offset))?;
702 let mut manifest_bytes = vec![0u8; manifest_len];
703 file.read_exact(&mut manifest_bytes)?;
704 let mut entries = read_manifest_bytes(&manifest_bytes)?;
705 entries.retain(|e| !is_reserved_module(&e.module_name));
707 Ok(entries)
708 }
709 }
710}
711
712pub fn read_znippy_full_manifest(path: &Path) -> Result<(Vec<ManifestEntry>, u64)> {
721 let mut file = File::open(path)?;
722 let file_len = file.metadata()?.len();
723 read_full_manifest(&mut file, file_len)
724}
725
726fn read_full_manifest(file: &mut File, file_len: u64) -> Result<(Vec<ManifestEntry>, u64)> {
728 anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
729 file.seek(SeekFrom::End(-16))?;
730 let mut tail = [0u8; 16];
731 file.read_exact(&mut tail)?;
732 let manifest_offset = match interpret_footer(&tail) {
733 IndexFooter::Multi { manifest_offset } => manifest_offset,
734 IndexFooter::Single { .. } => anyhow::bail!("not a v0.7 multi-index archive"),
735 };
736 let manifest_end = file_len.checked_sub(16)
737 .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
738 anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
739 let manifest_len = (manifest_end - manifest_offset) as usize;
740 file.seek(SeekFrom::Start(manifest_offset))?;
741 let mut manifest_bytes = vec![0u8; manifest_len];
742 file.read_exact(&mut manifest_bytes)?;
743 Ok((read_manifest_bytes(&manifest_bytes)?, manifest_offset))
744}
745
746fn read_reserved_section(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
748 let mut file = File::open(path)?;
749 let file_len = file.metadata()?.len();
750 let (entries, _) = read_full_manifest(&mut file, file_len)?;
751 let Some(entry) = entries.iter().find(|e| e.module_name == module_name) else {
752 return Ok(None);
753 };
754 anyhow::ensure!(
757 entry.index_offset.checked_add(entry.index_len)
758 .is_some_and(|end| end <= file_len),
759 "reserved section {} out of bounds (offset={}, len={}, file_len={})",
760 entry.module_name, entry.index_offset, entry.index_len, file_len
761 );
762 file.seek(SeekFrom::Start(entry.index_offset))?;
763 let mut bytes = vec![0u8; entry.index_len as usize];
764 file.read_exact(&mut bytes)?;
765 Ok(Some(bytes))
766}
767
768fn checksum32(col: &arrow::array::FixedSizeBinaryArray, i: usize) -> Result<[u8; 32]> {
781 if col.value_length() != 32 {
782 return Err(anyhow::anyhow!(
783 "checksum column has width {}, expected 32",
784 col.value_length()
785 ));
786 }
787 let mut ck = [0u8; 32];
788 ck.copy_from_slice(col.value(i));
789 Ok(ck)
790}
791
792fn decode_lookup(bytes: &[u8]) -> Result<LookupColumns> {
793 use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
794 use arrow::ipc::reader::StreamReader;
795
796 let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
797 let mut cols = LookupColumns::default();
798 for batch in reader {
799 let batch = batch?;
800 let get = |n: &str| batch.column_by_name(n)
801 .ok_or_else(|| anyhow::anyhow!("lookup missing column {n}"));
802 let paths = get("relative_path")?.as_any().downcast_ref::<StringArray>()
803 .ok_or_else(|| anyhow::anyhow!("relative_path type"))?;
804 let chunk_seq = get("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
805 .ok_or_else(|| anyhow::anyhow!("chunk_seq type"))?;
806 let fdata = get("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
807 .ok_or_else(|| anyhow::anyhow!("fdata_offset type"))?;
808 let compressed = get("compressed")?.as_any().downcast_ref::<BooleanArray>()
809 .ok_or_else(|| anyhow::anyhow!("compressed type"))?;
810 let usize_col = get("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
811 .ok_or_else(|| anyhow::anyhow!("uncompressed_size type"))?;
812 let blob_offset = get("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
813 .ok_or_else(|| anyhow::anyhow!("blob_offset type"))?;
814 let blob_size = get("blob_size")?.as_any().downcast_ref::<UInt64Array>()
815 .ok_or_else(|| anyhow::anyhow!("blob_size type"))?;
816 let checksum = get("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
817 .ok_or_else(|| anyhow::anyhow!("checksum type"))?;
818 for i in 0..batch.num_rows() {
819 cols.paths.push(paths.value(i).to_string());
820 let ck = checksum32(checksum, i)?;
821 cols.locs.push(ChunkLoc {
822 chunk_seq: chunk_seq.value(i),
823 fdata_offset: fdata.value(i),
824 blob_offset: blob_offset.value(i),
825 blob_size: blob_size.value(i),
826 uncompressed_size: usize_col.value(i),
827 compressed: compressed.value(i),
828 checksum: ck,
829 });
830 }
831 }
832 Ok(cols)
833}
834
835#[derive(Default)]
836struct LookupColumns {
837 paths: Vec<String>,
838 locs: Vec<ChunkLoc>,
839}
840
841pub fn locate_file(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
848 if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
849 let cols = decode_lookup(&lookup_bytes)?;
850 let n = cols.paths.len();
851
852 let hit = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
854 let map = fst::Map::new(trie_bytes)
855 .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
856 map.get(target.as_bytes()).map(|v| v as usize)
857 } else {
858 match cols.paths.binary_search_by(|p| p.as_str().cmp(target)) {
860 Ok(i) => Some(i),
861 Err(_) => None,
862 }
863 };
864
865 let Some(hit) = hit else { return Ok(Vec::new()); };
866
867 if hit >= n { return Ok(Vec::new()); }
872
873 let mut start = hit;
875 while start > 0 && cols.paths[start - 1] == target { start -= 1; }
876 let mut end = hit + 1;
877 while end < n && cols.paths[end] == target { end += 1; }
878
879 let mut out: Vec<ChunkLoc> = cols.locs[start..end].to_vec();
880 out.sort_by_key(|c| c.chunk_seq);
881 return Ok(out);
882 }
883
884 locate_file_via_index(path, target)
886}
887
888#[derive(Debug, Clone, PartialEq)]
891pub struct ArtifactMeta {
892 pub relative_path: String,
893 pub uncompressed_size: u64,
895 pub chunk_count: u32,
896 pub compressed: bool,
898}
899
900pub fn get_all_files_meta(path: &Path) -> Result<Vec<ArtifactMeta>> {
905 files_meta_impl(path, None)
906}
907
908pub fn get_files_meta_with_prefix(path: &Path, prefix: &str) -> Result<Vec<ArtifactMeta>> {
915 files_meta_impl(path, Some(prefix))
916}
917
918fn files_meta_impl(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
919 use fst::{IntoStreamer, Streamer};
920
921 if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
922 let cols = decode_lookup(&lookup_bytes)?; let n = cols.paths.len();
924
925 let (lo, hi) = match prefix {
927 None | Some("") => (0, n),
928 Some(pre) => {
929 let lo = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
932 let map = fst::Map::new(trie_bytes)
933 .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
934 let mut stream = map.range().ge(pre.as_bytes()).into_stream();
935 match stream.next() {
936 Some((k, v)) if k.starts_with(pre.as_bytes()) => v as usize,
937 _ => return Ok(Vec::new()),
938 }
939 } else {
940 cols.paths.partition_point(|p| p.as_str() < pre)
941 };
942 if lo >= n || !cols.paths[lo].starts_with(pre) {
943 return Ok(Vec::new());
944 }
945 let mut hi = lo;
946 while hi < n && cols.paths[hi].starts_with(pre) {
947 hi += 1;
948 }
949 (lo, hi)
950 }
951 };
952
953 let mut out = Vec::new();
955 let mut i = lo;
956 while i < hi {
957 let p = &cols.paths[i];
958 let mut total = 0u64;
959 let mut count = 0u32;
960 let mut compressed = false;
961 while i < hi && &cols.paths[i] == p {
962 total += cols.locs[i].uncompressed_size;
963 count += 1;
964 compressed |= cols.locs[i].compressed;
965 i += 1;
966 }
967 out.push(ArtifactMeta {
968 relative_path: p.clone(),
969 uncompressed_size: total,
970 chunk_count: count,
971 compressed,
972 });
973 }
974 return Ok(out);
975 }
976
977 files_meta_via_index(path, prefix)
978}
979
980pub struct ArchiveReader {
999 paths: Vec<String>,
1001 locs: Vec<ChunkLoc>,
1003 trie: Option<fst::Map<Vec<u8>>>,
1007 file: File,
1011 file_len: u64,
1014}
1015
1016impl ArchiveReader {
1017 pub fn open(path: &Path) -> Result<Self> {
1020 let mut file = File::open(path)?;
1021 let file_len = file.metadata()?.len();
1022 let (entries, _) = read_full_manifest(&mut file, file_len)?;
1023
1024 let mut read_section = |module: &str| -> Result<Option<Vec<u8>>> {
1028 let Some(entry) = entries.iter().find(|e| e.module_name == module) else {
1029 return Ok(None);
1030 };
1031 anyhow::ensure!(
1032 entry.index_offset.checked_add(entry.index_len)
1033 .is_some_and(|end| end <= file_len),
1034 "reserved section {} out of bounds (offset={}, len={}, file_len={})",
1035 entry.module_name, entry.index_offset, entry.index_len, file_len
1036 );
1037 file.seek(SeekFrom::Start(entry.index_offset))?;
1038 let mut bytes = vec![0u8; entry.index_len as usize];
1039 file.read_exact(&mut bytes)?;
1040 Ok(Some(bytes))
1041 };
1042
1043 let lookup_bytes = read_section(LOOKUP_MODULE)?.ok_or_else(|| {
1044 anyhow::anyhow!("archive has no lookup sub-index (not a v0.7 sealed archive)")
1045 })?;
1046 let cols = decode_lookup(&lookup_bytes)?;
1047 let trie = match read_section(TRIE_MODULE)? {
1048 Some(tb) => Some(fst::Map::new(tb).map_err(|e| anyhow::anyhow!("trie open: {e}"))?),
1049 None => None,
1050 };
1051
1052 Ok(Self { paths: cols.paths, locs: cols.locs, trie, file, file_len })
1053 }
1054
1055 pub fn row_count(&self) -> usize {
1057 self.paths.len()
1058 }
1059
1060 pub fn read_file(&self, target: &str) -> Result<Vec<u8>> {
1070 let chunks = self.locate(target);
1071 anyhow::ensure!(!chunks.is_empty(), "file not found in archive: {target}");
1072 crate::decompress::reassemble_file(&self.file, self.file_len, target, &chunks)
1073 }
1074
1075 pub fn locate(&self, target: &str) -> Vec<ChunkLoc> {
1078 let n = self.paths.len();
1079 let hit = match &self.trie {
1080 Some(map) => map.get(target.as_bytes()).map(|v| v as usize),
1081 None => self.paths.binary_search_by(|p| p.as_str().cmp(target)).ok(),
1082 };
1083 let Some(hit) = hit else { return Vec::new(); };
1084
1085 if hit >= n { return Vec::new(); }
1089
1090 let mut start = hit;
1092 while start > 0 && self.paths[start - 1] == target { start -= 1; }
1093 let mut end = hit + 1;
1094 while end < n && self.paths[end] == target { end += 1; }
1095
1096 let mut out: Vec<ChunkLoc> = self.locs[start..end].to_vec();
1097 out.sort_by_key(|c| c.chunk_seq);
1098 out
1099 }
1100
1101 pub fn files_meta(&self) -> Vec<ArtifactMeta> {
1104 self.aggregate(0, self.paths.len())
1105 }
1106
1107 pub fn files_meta_with_prefix(&self, prefix: &str) -> Vec<ArtifactMeta> {
1110 let (lo, hi) = self.window(prefix);
1111 self.aggregate(lo, hi)
1112 }
1113
1114 fn window(&self, prefix: &str) -> (usize, usize) {
1118 use fst::{IntoStreamer, Streamer};
1119 let n = self.paths.len();
1120 if prefix.is_empty() {
1121 return (0, n);
1122 }
1123 let lo = match &self.trie {
1124 Some(map) => {
1125 let mut stream = map.range().ge(prefix.as_bytes()).into_stream();
1126 match stream.next() {
1127 Some((k, v)) if k.starts_with(prefix.as_bytes()) => v as usize,
1128 _ => return (0, 0),
1129 }
1130 }
1131 None => self.paths.partition_point(|p| p.as_str() < prefix),
1132 };
1133 if lo >= n || !self.paths[lo].starts_with(prefix) {
1134 return (0, 0);
1135 }
1136 let mut hi = lo;
1137 while hi < n && self.paths[hi].starts_with(prefix) {
1138 hi += 1;
1139 }
1140 (lo, hi)
1141 }
1142
1143 fn aggregate(&self, lo: usize, hi: usize) -> Vec<ArtifactMeta> {
1146 let mut out = Vec::new();
1147 let mut i = lo;
1148 while i < hi {
1149 let p = &self.paths[i];
1150 let mut total = 0u64;
1151 let mut count = 0u32;
1152 let mut compressed = false;
1153 while i < hi && &self.paths[i] == p {
1154 total += self.locs[i].uncompressed_size;
1155 count += 1;
1156 compressed |= self.locs[i].compressed;
1157 i += 1;
1158 }
1159 out.push(ArtifactMeta {
1160 relative_path: p.clone(),
1161 uncompressed_size: total,
1162 chunk_count: count,
1163 compressed,
1164 });
1165 }
1166 out
1167 }
1168}
1169
1170fn files_meta_via_index(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
1172 use arrow::array::{BooleanArray, StringArray, UInt64Array};
1173
1174 let (schema, batches) = read_znippy_index(path)?;
1175 let batch = match batches.len() {
1176 0 => return Ok(Vec::new()),
1177 1 => batches.into_iter().next().unwrap(),
1178 _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1179 };
1180 let col = |n: &str| batch.column_by_name(n)
1185 .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1186 let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1187 .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1188 let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1189 .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1190 let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1191 .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1192
1193 let mut agg: HashMap<&str, (u64, u32, bool)> = HashMap::new();
1195 for i in 0..batch.num_rows() {
1196 let p = paths.value(i);
1197 if let Some(pre) = prefix {
1198 if !p.starts_with(pre) { continue; }
1199 }
1200 let e = agg.entry(p).or_insert((0, 0, false));
1201 e.0 += usize_col.value(i);
1202 e.1 += 1;
1203 e.2 |= compressed.value(i);
1204 }
1205 let mut out: Vec<ArtifactMeta> = agg.into_iter().map(|(p, (sz, c, comp))| ArtifactMeta {
1206 relative_path: p.to_string(),
1207 uncompressed_size: sz,
1208 chunk_count: c,
1209 compressed: comp,
1210 }).collect();
1211 out.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
1212 Ok(out)
1213}
1214
1215fn locate_file_via_index(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
1217 use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
1218
1219 let (schema, batches) = read_znippy_index(path)?;
1220 let batch = match batches.len() {
1221 0 => return Ok(Vec::new()),
1222 1 => batches.into_iter().next().unwrap(),
1223 _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1224 };
1225 let col = |n: &str| batch.column_by_name(n)
1228 .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1229 let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1230 .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1231 let chunk_seq = col("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
1232 .ok_or_else(|| anyhow::anyhow!("index column chunk_seq has unexpected type"))?;
1233 let fdata = col("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
1234 .ok_or_else(|| anyhow::anyhow!("index column fdata_offset has unexpected type"))?;
1235 let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1236 .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1237 let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1238 .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1239 let blob_offset = col("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
1240 .ok_or_else(|| anyhow::anyhow!("index column blob_offset has unexpected type"))?;
1241 let blob_size = col("blob_size")?.as_any().downcast_ref::<UInt64Array>()
1242 .ok_or_else(|| anyhow::anyhow!("index column blob_size has unexpected type"))?;
1243 let checksum = col("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
1244 .ok_or_else(|| anyhow::anyhow!("index column checksum has unexpected type"))?;
1245
1246 let mut out = Vec::new();
1247 for i in 0..batch.num_rows() {
1248 if paths.value(i) == target {
1249 let ck = checksum32(checksum, i)?;
1250 out.push(ChunkLoc {
1251 chunk_seq: chunk_seq.value(i),
1252 fdata_offset: fdata.value(i),
1253 blob_offset: blob_offset.value(i),
1254 blob_size: blob_size.value(i),
1255 uncompressed_size: usize_col.value(i),
1256 compressed: compressed.value(i),
1257 checksum: ck,
1258 });
1259 }
1260 }
1261 out.sort_by_key(|c| c.chunk_seq);
1262 Ok(out)
1263}
1264
1265pub fn is_probably_compressed(path: &Path) -> bool {
1266 if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1267 let ext = ext.to_ascii_lowercase();
1268 matches!(
1269 ext.as_str(),
1270 "zip" | "gz" | "bz2" | "xz" | "lz" | "lzma" | "7z" | "rar" | "cab"
1271 | "jar" | "war" | "ear" | "zst" | "sz" | "lz4" | "tgz" | "txz"
1272 | "tbz" | "apk" | "dmg" | "deb" | "rpm" | "arrow" | "mpeg" | "mpg"
1273 | "jpeg" | "jpg" | "gif" | "bmp" | "png" | "crate" | "znippy"
1274 | "zdata" | "parquet" | "webp" | "webm"
1275 | "age" | "iso" | "pdf"
1280 | "pack" | "idx" | "midx" | "bitmap"
1287 )
1288 } else {
1289 false
1290 }
1291}
1292
1293pub fn should_skip_compression(path: &Path) -> bool {
1302 is_probably_compressed(path)
1303}
1304
1305#[cfg(test)]
1306mod skip_compression_tests {
1307 use super::*;
1308
1309 #[test]
1310 fn skips_already_compressed_and_encrypted() {
1311 for p in ["secrets/secrets.age", "infra/talos/talos-1.13.iso", "s3/doc.pdf", "x.PDF"] {
1312 assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1313 }
1314 }
1315
1316 #[test]
1317 fn compresses_plain_dump_and_config() {
1318 for p in ["dbdump/njord.dump", "njord.sql", "lakespec.json", "njordconf/serverspec.json"] {
1320 assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1321 }
1322 }
1323
1324 #[test]
1327 fn skips_git_pack_directory_artefacts() {
1328 for p in [
1329 ".git/objects/pack/pack-9f2c.pack",
1330 ".git/objects/pack/pack-9f2c.idx",
1331 ".git/objects/pack/multi-pack-index.midx",
1332 ".git/objects/pack/pack-9f2c.bitmap",
1333 ] {
1334 assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1335 }
1336 }
1337
1338 #[test]
1342 fn still_compresses_the_compressible_git_artefacts() {
1343 for p in [
1344 ".git/objects/pack/pack-9f2c.rev",
1345 ".git/objects/pack/pack-9f2c.promisor",
1346 ".git/COMMIT_EDITMSG",
1347 ".git/config",
1348 ] {
1349 assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1350 }
1351 }
1352}
1353
1354#[derive(Debug, Default)]
1355pub struct VerifyReport {
1356 pub total_files: usize,
1357 pub verified_files: usize,
1358 pub corrupt_files: usize,
1359 pub total_bytes: u64,
1360 pub verified_bytes: u64,
1361 pub corrupt_bytes: u64,
1362 pub chunks: u64,
1363}
1364
1365pub fn list_archive_contents(path: &Path) -> Result<()> {
1366 let (_schema, batches) = read_znippy_index(path)?;
1367 for batch in &batches {
1368 let paths = batch
1369 .column_by_name("relative_path")
1370 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>())
1371 .ok_or_else(|| anyhow::anyhow!("missing relative_path column"))?;
1372 let sizes = batch
1373 .column_by_name("uncompressed_size")
1374 .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt64Array>())
1375 .ok_or_else(|| anyhow::anyhow!("missing uncompressed_size column"))?;
1376 let chunk_seqs = batch
1377 .column_by_name("chunk_seq")
1378 .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt32Array>());
1379 let group_ids = batch
1380 .column_by_name("group_id")
1381 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1382 let artifact_ids = batch
1383 .column_by_name("artifact_id")
1384 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1385 let versions = batch
1386 .column_by_name("version")
1387 .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1388 for i in 0..batch.num_rows() {
1389 if let Some(seqs) = chunk_seqs {
1391 if seqs.value(i) != 0 {
1392 continue;
1393 }
1394 }
1395 if let (Some(g), Some(a), Some(v)) = (group_ids, artifact_ids, versions) {
1396 if !g.is_null(i) {
1397 println!(
1398 "{}\t{}\t{}:{}:{}",
1399 paths.value(i),
1400 sizes.value(i),
1401 g.value(i),
1402 a.value(i),
1403 v.value(i)
1404 );
1405 continue;
1406 }
1407 }
1408 println!("{}\t{}", paths.value(i), sizes.value(i));
1409 }
1410 }
1411 Ok(())
1412}
1413
1414pub fn verify_archive_integrity(path: &Path) -> Result<VerifyReport> {
1415 let out_dir = PathBuf::from("/dev/null");
1416 decompress_archive(path, false, &out_dir)
1417}
1418
1419#[cfg(test)]
1420mod version_tests {
1421 use super::*;
1422
1423 #[test]
1424 fn current_and_older_versions_are_accepted() {
1425 let mut m = HashMap::new();
1426 check_format_version(&m).unwrap();
1428 m.insert(FORMAT_VERSION_KEY.into(), ZNIPPY_FORMAT_VERSION.to_string());
1430 check_format_version(&m).unwrap();
1431 m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION - 1).to_string());
1433 check_format_version(&m).unwrap();
1434 }
1435
1436 #[test]
1437 fn newer_version_is_rejected_clearly() {
1438 let mut m = HashMap::new();
1439 m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION + 1).to_string());
1440 let err = check_format_version(&m).unwrap_err().to_string();
1441 assert!(err.contains("newer than this reader supports"), "got: {err}");
1442 assert!(err.contains("upgrade znippy"), "got: {err}");
1443 }
1444
1445 #[test]
1446 fn writer_records_the_current_version() {
1447 let meta = build_arrow_metadata_for_config(&crate::common_config::CONFIG);
1448 assert_eq!(
1449 meta.get(FORMAT_VERSION_KEY).map(String::as_str),
1450 Some(ZNIPPY_FORMAT_VERSION.to_string().as_str())
1451 );
1452 }
1453}
1454
1455#[cfg(test)]
1456mod checksum_width_tests {
1457 use super::*;
1458 use arrow::array::FixedSizeBinaryArray;
1459
1460 #[test]
1467 fn narrow_checksum_column_errors_instead_of_panicking() {
1468 let narrow = FixedSizeBinaryArray::try_from_iter([[0u8; 16]].into_iter()).unwrap();
1469 assert_eq!(narrow.value_length(), 16);
1470 let err = checksum32(&narrow, 0).expect_err("a 16-byte checksum column must be an Err");
1471 assert!(
1472 err.to_string().contains("width 16"),
1473 "error must name the bad width, got: {err}"
1474 );
1475 }
1476
1477 #[test]
1478 fn wide_checksum_column_errors_instead_of_truncating() {
1479 let wide = FixedSizeBinaryArray::try_from_iter([[7u8; 64]].into_iter()).unwrap();
1480 assert!(checksum32(&wide, 0).is_err(), "a 64-byte checksum column must be an Err");
1481 }
1482
1483 #[test]
1484 fn correct_width_checksum_is_read_verbatim() {
1485 let mut digest = [0u8; 32];
1486 for (i, b) in digest.iter_mut().enumerate() {
1487 *b = i as u8;
1488 }
1489 let col = FixedSizeBinaryArray::try_from_iter([digest].into_iter()).unwrap();
1490 assert_eq!(checksum32(&col, 0).unwrap(), digest);
1491 }
1492}
1493
1494#[cfg(test)]
1495mod reserved_module_tests {
1496 use super::*;
1497
1498 #[test]
1508 fn every_reserved_module_is_classified_reserved() {
1509 for m in RESERVED_MODULES {
1510 assert!(
1511 is_reserved_module(m),
1512 "'{m}' is in RESERVED_MODULES but is_reserved_module says it is DATA — \
1513 its rows would be merged into the file index"
1514 );
1515 }
1516 }
1517
1518 #[test]
1522 fn the_git_format_modules_are_reserved() {
1523 for m in [
1524 GUNNAR_OID_MODULE,
1525 GUNNAR_GRAPH_MODULE,
1526 GUNNAR_REACH_MODULE,
1527 GUNNAR_REFS_MODULE,
1528 GUNNAR_SECRETS_MODULE,
1529 ] {
1530 assert!(is_reserved_module(m), "git package-format module '{m}' must be reserved");
1531 assert!(
1532 RESERVED_MODULES.contains(&m),
1533 "git package-format module '{m}' must be in the catalog"
1534 );
1535 }
1536 assert_eq!(GUNNAR_OID_MODULE, "__gunnar_oid__");
1537 assert_eq!(GUNNAR_GRAPH_MODULE, "__gunnar_graph__");
1538 assert_eq!(GUNNAR_REACH_MODULE, "__gunnar_reach__");
1539 assert_eq!(GUNNAR_REFS_MODULE, "__gunnar_refs__");
1540 assert_eq!(GUNNAR_SECRETS_MODULE, "__gunnar_secrets__");
1541 }
1542
1543 #[test]
1546 fn ordinary_module_names_stay_data() {
1547 for m in ["maven", "git", "rust", "", "__gunnar__", "gunnar_oid", "__gunnar_oid", "objects"] {
1548 assert!(!is_reserved_module(m), "'{m}' must be treated as a DATA sub-index");
1549 }
1550 }
1551
1552 #[test]
1554 fn the_catalog_is_well_formed() {
1555 let mut seen = std::collections::HashSet::new();
1556 for m in RESERVED_MODULES {
1557 assert!(!m.is_empty(), "empty reserved module name");
1558 assert!(seen.insert(*m), "duplicate reserved module name '{m}'");
1559 }
1560 assert_eq!(seen.len(), RESERVED_MODULES.len());
1561 }
1562}